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.

  • Ensure that the Cloud SQL Admin API is enabled for the project containing the Cloud SQL instance.

    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.

For PostgreSQL, you might need to add the .s.PGSQL.5432 suffix to the socket path. Some connector libraries apply the suffix automatically, but others require the socket path to specified as follows: /cloudsql/INSTANCE_CONNECTION_NAME/.s.PGSQL.5432.

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 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:postgresql:///%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.postgres.SocketFactory");
config.addDataSourceProperty("cloudSqlInstance", CLOUD_SQL_CONNECTION_NAME);

// ... 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.

Node.js

// Initialize Knex, a Node.js SQL query builder library with built-in connection pooling.
const knex = connect();

function connect() {
  // Configure which instance and what database user to connect with.
  // Remember - storing secrets in plaintext is potentially unsafe. Consider using
  // something like https://cloud.google.com/kms/ to help keep secrets secret.
  const config = {
    user: process.env.DB_USER, // e.g. 'my-user'
    password: process.env.DB_PASS, // e.g. 'my-user-password'
    database: process.env.DB_NAME, // e.g. 'my-database'
  };

  config.host = `/cloudsql/${process.env.CLOUD_SQL_CONNECTION_NAME}`;

  // Establish a connection to the database
  const knex = Knex({
    client: 'pg',
    connection: config,
  });

  // ... Specify additional properties here.
  // ...
  return knex;
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.

What's next

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

Send feedback about...

Cloud SQL for PostgreSQL