Connecting from App Engine

This page contains information and examples for connecting to a Cloud SQL instance from a service running in App Engine.

Setting up Cloud SQL

  1. Create a Cloud SQL for MySQL instance.

  2. Find the Instance connection name for the instance on the Instance details page. It uses the format [PROJECT_ID]:[REGION]:[INSTANCE_ID], and is used to identify the Cloud SQL instance you are connecting to.

  3. Enable the Cloud SQL Cloud SQL Admin API, if you haven't already done so.

    Enable the API

  4. Set one of following IAM roles on the service account:

    • Cloud SQL Client (preferred)
    • Cloud SQL Editor
    • Cloud SQL Admin

    Or, you can manually assign one of the following IAM permissions:

    • cloudsql.instances.connect
    • cloudsql.instances.get

    For detailed instructions on adding IAM roles to a service account, see Granting Roles to Service Accounts.

    When connecting resources in two different projects, make sure that both projects have enabled the correct IAM roles and have given the service account the correct permissions.

Configuring App Engine

Standard

You use the App Engine service account to authenticate your connections. The service account must have the correct IAM permissions (see Setting up Cloud SQL for correct permissions). Unless otherwise specified, this service account uses the format service-[YOUR_PROJECT_NUMBER]@gae-api-prod.google.com.iam.gserviceaccount.com.

The App Engine Standard environment automatically provides a Unix domain socket, making your instance accessible at /cloudsql/INSTANCE_CONNECTION_NAME.

Flexible

You use the App Engine service account to authenticate your connections. The service account must have the correct IAM permissions (see Setting up Cloud SQL for correct permissions). Unless otherwise specified, this service account uses the format service-[YOUR_PROJECT_NUMBER]@gae-api-prod.google.com.iam.gserviceaccount.com.

Update your project's app.yaml file with the option that works best. You can use a comma separated list of instances to specify multiple options at once.

Enabling a Unix domain socket

You can enable a Unix domain socket by adding the following to your project's app.yamlfile:

beta_settings:
  cloud_sql_instances: <INSTANCE_CONNECTION_NAME>

This makes your instance accessible at /cloudsql/INSTANCE_CONNECTION_NAME.

Enabling a TCP Port

You can enable a local TCP port by adding the following to your project's app.yaml file:

beta_settings:
  cloud_sql_instances: <INSTANCE_CONNECTION_NAME>&=tcp:<PORT>

This makes your instance accessible at 127.0.0.1:<PORT>.

Connecting to Cloud SQL

Python

# The SQLAlchemy engine will help manage interactions, including automatically
# managing a pool of connections to your database
db = sqlalchemy.create_engine(
    # Equivalent URL:
    # mysql+pymysql://<db_user>:<db_pass>@/<db_name>?unix_socket=/cloudsql/<cloud_sql_instance_name>
    sqlalchemy.engine.url.URL(
        drivername='mysql+pymysql',
        username=db_user,
        password=db_pass,
        database=db_name,
        query={
            'unix_socket': '/cloudsql/{}/'.format(cloud_sql_connection_name)
        }
    ),
    # ... Specify additional properties here.
    # ...
)
To see this snippet in the context of a web application, view the source code on GitHub.

Java

// The configuration object specifies behaviors for the connection pool.
HikariConfig config = new HikariConfig();

// Configure which instance and what database user to connect with.
config.setJdbcUrl(String.format("jdbc:mysql:///%s", DB_NAME));
config.setUsername(DB_USER); // e.g. "root", "postgres"
config.setPassword(DB_PASS); // e.g. "my-password"

// For Java users, the Cloud SQL JDBC Socket Factory can provide authenticated connections.
// See https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory for details.
config.addDataSourceProperty("socketFactory", "com.google.cloud.sql.mysql.SocketFactory");
config.addDataSourceProperty("cloudSqlInstance", CLOUD_SQL_CONNECTION_NAME);
config.addDataSourceProperty("useSSL", "false");

// ... Specify additional connection properties here.
// ...

// Initialize the connection pool using the configuration object.
DataSource pool = new HikariDataSource(config);
To see this snippet in the context of a web application, view the source code on GitHub.

Node.js

const pool = mysql.createPool({
  user: process.env.DB_USER, // e.g. 'my-db-user'
  password: process.env.DB_PASS, // e.g. 'my-db-password'
  database: process.env.DB_NAME, // e.g. 'my-database'
  // If connecting via unix domain socket, specify the path
  socketPath: `/cloudsql/${process.env.CLOUD_SQL_CONNECTION_NAME}`,
  // If connecting via TCP, enter the IP and port instead
  // host: 'localhost',
  // port: 3306,

  //...
});
To see this snippet in the context of a web application, view the source code on GitHub.

Best Practices & Other Information

When you are connecting to Cloud SQL from App Engine, keep these best practices in mind:

  • App Engine has the ability to automatically create more instances when load increases. If the number of App Engine instances increases beyond what the Cloud SQL instance is sized to handle, your Cloud SQL instance will not be able to meet the demand. To avoid this issue, limit the maximum number of App Engine instances. For more information, see Scaling elements.

  • Database connections consume resources; your application should use best practices for connection management to reduce the number of connections needed. For the App Engine standard environment, there is a hard limit for the number of connections an App Engine instance can have open to Cloud SQL.

Var denne side nyttig? Giv os en anmeldelse af den:

Send feedback om...

Cloud SQL for MySQL