Connecting from App Engine

This page contains information and examples for connecting to a Cloud SQL instance from an App Engine application.

Setting up Cloud SQL and App Engine

For more information about setting up a Cloud SQL instance or an App Engine application, see the following instructions:

  • Identify the connection name for the Cloud SQL instance. This is a unique string for each instance in the format <PROJECT_ID>:<REGION>:<INSTANCE_ID>. It is listed under Instance connection name on the Instance details page for your instance, or under connectionName when using the gcloud sql instances describe <INSTANCE_ID> command.

  • If you are using the Java programming language, enable the Cloud SQL Admin API.

    Enable the API

Your application should use connection pooling for the best performance and response times. For specific examples of connection pooling, see Managing Database Connections.

Connecting the App Engine standard environment to Cloud SQL

The App Engine standard environment provides a Unix domain socket for connecting to Cloud SQL instances. These connections are automatically authorized using the App Engine default service account.

The socket is found at /cloudsql/INSTANCE_CONNECTION_NAME and can be used directly by the application. For example usage, see below.

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_instance_name)
        }
    ),
    # ... Specify additional properties here.
    # ...
)
To see the snippet above in the context of an application, the entire project is available here.

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_INSTANCE_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 the snippet above in the context of an application, the entire project is available here.

Connecting the App Engine flexible environment to Cloud SQL

The App Engine flexible environment provides secure connection options to Cloud SQL instances using either a Unix domain socket or TCP connection.

Unix domain socket

Add the following to your project's app.yaml to enable the provided Unix socket:
beta_settings:
  cloud_sql_instances: <INSTANCE_CONNECTION_NAME> 
Your application can connect to the Cloud SQL instance using the Unix socket located at /cloudsql/<INSTANCE_CONNECTION_NAME>.
When connecting to multiple Cloud SQL instances, use a comma-separated list of instance connection names. Each instance listed will create a different socket, derived from the instance connection name.

TCP connection

Add the following to your project's app.yaml to enable the provided TCP port:
beta_settings:
  cloud_sql_instances: <INSTANCE_CONNECTION_NAME>=tcp:<TCP_PORT>
Your application can connect to the Cloud SQL instance using the TCP port listening on 127.0.0.1:<TCP_PORT>.
When you connect to multiple Cloud SQL instances, use a comma-separated list of instance connection names. Each instance must use a different local port.

Additional information

App Engine and Cloud SQL in different projects

For App Engine applications and Cloud SQL instances in different projects, you must grant the default appengine service account ([PROJECT-ID]@appspot.gserviceaccount.com) one of the following IAM roles:

  • Cloud SQL Client
  • Cloud SQL Editor
  • Cloud SQL Admin

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

Best practices

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. You can avoid this issue by limiting 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 App Engine standard environment, there is a hard limit on the number of connections an App Engine instance can have open to Cloud SQL.

Connecting App Engine standard environment to Cloud SQL First Generation

First Generation Cloud SQL instances only support connections from App Engine standard environment, and require authorization. To grant authorization, follow the steps below.

Console

  1. Go to the Cloud SQL Instances page in the Google Cloud Platform Console.

    Go to the Cloud SQL Instances page

  2. Click the instance name to open its Instance details page.
  3. Select the Connections tab.
  4. In the Authorized App Engine Standard applications section, click Add project ID and enter the project ID for the application you want to authorize.
  5. Click Done to exit edit mode.
  6. Click Save to update the instance.

gcloud

  1. List the existing authorized App Engine projects for the instance.
    gcloud sql instances describe [INSTANCE_NAME]
    
  2. Use the sql instances patch command to provide the project ID for all applications that can access this instance. Use commas to separate multiple IDs.
    gcloud sql instances patch [INSTANCE_NAME] --authorized-gae-apps [GAE_APP_PROJECT_ID]
    

What's next

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud SQL for MySQL