This sample demonstrates how to use Google Cloud SQL (or any other SQL server) on Google App Engine Flexible.
This sample has instructions for both MySQL and Postgres.
Before you can run or deploy the sample, you will need to do the following:
-
In order for some of the commands below to work, you need to enable the Cloud SQL Admin API.
-
Create a Second Generation Cloud SQL instance. You can do this from the Cloud Console or via the Cloud SDK. To create it via the SDK use the following command:
gcloud sql instances create [YOUR_INSTANCE_NAME] \ --activation-policy=ALWAYS \ --tier=db-n1-standard-1where
[YOUR_INSTANCE_NAME]is a name of your choice. -
Set the root password on your Cloud SQL instance:
gcloud sql instances set-root-password [YOUR_INSTANCE_NAME] --password [YOUR_INSTANCE_ROOT_PASSWORD]where
[YOUR_INSTANCE_NAME]is the name you chose in step 1 and[YOUR_INSTANCE_ROOT_PASSWORD]is a password of your choice. -
Using the Cloud SQL console, select your Cloud SQL instance. Then, create a user (using the button in the Access Control > Users tab) and a database (using the button in the Databases tab).
-
Create and download a Service Account for your project. You will use this service account to connect to your Cloud SQL instance locally.
-
Download and install the Cloud SQL Proxy.
-
Start the proxy to allow connecting to your instance from your local machine:
./cloud_sql_proxy \ -instances=[YOUR_INSTANCE_CONNECTION_NAME]=tcp:[PORT] \ -credential_file=PATH_TO_YOUR_SERVICE_ACCOUNT_JSON_FILEwhere
[YOUR_INSTANCE_CONNECTION_NAME]is the connection name of your instance on its Overview page in the Google Cloud Platform Console, or use[YOUR_PROJECT_ID]:[YOUR_REGION]:[YOUR_INSTANCE_NAME]. If you're using MySQL,[PORT]will be3306; for Postgres, it will be5432. -
In a separate terminal, set the
SQL_USER,SQL_PASSWORD, andSQL_DATABASEenvironment variables to their respective values. This allows your local app to connect to your Cloud SQL instance through the proxy.export SQL_USER="..." export SQL_PASSWORD="..." export SQL_DATABASE="..."
Choose which database connector to use via the SQL_CLIENT environment variable.
To use MySQL, set it to mysql:
export SQL_CLIENT="mysql"
To use Postgres, set it to pg:
export SQL_CLIENT="pg"
-
Update the values in
app.yamlwith your instance configuration. -
Finally, run
createTables.jsto ensure that the database is properly configured and to create the tables needed for the sample.
Refer to the top-level README for instructions on running and deploying.
It's recommended to follow the instructions above to run the Cloud SQL proxy. You will need to set the appropriate environment variables (as shown above) and run the following commands via your shell to run the sample:
npm install
npm start