Connecting to Cloud SQL from App Engine

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

Cloud SQL is a fully-managed database service that makes it easy to set up, maintain, manage, and administer your relational PostgreSQL and MySQL databases in the cloud.

App Engine is a fully managed, serverless platform for developing and hosting web applications at scale. You can choose from several popular languages, libraries, and frameworks to develop your apps, then let App Engine take care of provisioning servers and scaling your app instances based on demand.

Setting up a Cloud SQL instance

  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 Admin API, if you haven't already done so:

    Enable the API

Configuring App Engine


App Engine does not require any special configuration beyond making sure the service account that you use has the correct permissions.


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

To enable a Unix domain socket, add the following to your project's app.yaml file:

  cloud_sql_instances: <INSTANCE_CONNECTION_NAME>

Enabling a TCP Port

To enable a local TCP port, add the following to your project's app.yaml file:

  cloud_sql_instances: <INSTANCE_CONNECTION_NAME>=tcp:<PORT>

App Engine uses a service account to authorize your connections to Cloud SQL. This service account must have the correct IAM permissions to successfully connect. Unless otherwise configured, the default service account is in the format

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.

Ensure that the service account for your service has one of the following IAM roles:

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

Or, you can manually assign 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.

Connecting to Cloud SQL

Once correctly configured, you can connect your service to your Cloud SQL instance's unix domain socket using the format: /cloudsql/INSTANCE_CONNECTION_NAME.

These connections are automatically encrypted without any additional configuration.

App Engine flexible environment also supports connecting through TCP. If you have configured an instance with a TCP port, configure your application to connect to instead.


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


// 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 for details.
config.addDataSourceProperty("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.


let pool;
const createPool = async () => {
  pool = await 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.


var connectionString = new MySqlConnectionStringBuilder(
// ConnectionString set in appsetings.json formatted as:
// "Uid=aspnetuser;Pwd=;Host=cloudsql;Database=votes"
    // Connecting to a local proxy that does not support ssl.
    SslMode = MySqlSslMode.None,
connectionString.Pooling = true;
// ...
DbConnection connection =
    new MySqlConnection(connectionString.ConnectionString);
To see this snippet in the context of a web application, view the source code on GitHub.


  adapter: mysql2
  # ...
  username: <%= ENV["MYSQL_USERNAME"] %>
  password: <%= ENV["MYSQL_PASSWORD"] %>
  database: <%= ENV.fetch("MYSQL_DATABASE") { "vote_development" } %>
  socket:   "/cloudsql/<%= ENV["INSTANCE_CONNECTION_NAME"] %>"
To see this snippet in the context of a web application, view the source code on GitHub.


var (
	dbUser                 = mustGetenv("DB_USER")
	dbPwd                  = mustGetenv("DB_PASS")
	instanceConnectionName = mustGetenv("INSTANCE_CONNECTION_NAME")
	dbName                 = mustGetenv("DB_NAME")

var dbURI string
dbURI = fmt.Sprintf("%s:%s@unix(/cloudsql/%s)/%s", dbUser, dbPwd, instanceConnectionName, dbName)

// dbPool is the pool of database connections.
dbPool, err := sql.Open("mysql", dbURI)
if err != nil {
	return nil, fmt.Errorf("sql.Open: %v", err)

// ...

return dbPool, nil
To see this snippet in the context of a web application, view the source code on GitHub.

Best Practices & Other Information

You can use the Cloud SQL proxy when testing your application locally. See the quickstart for using the proxy for local testing for detailed instructions.

Connection Pools

Connections to underlying databases may be dropped, either by the database server itself, or by the underlying infrastructure. To mitigate this, we recommend that you use a client library that supports connection pools and automatic reconnection.

For more detailed examples on how to use connection pools, see Managing database connections.

Connection Limits

Cloud SQL imposes a maximum limit on concurrent connections, and these limits may vary depending on the database engine chosen (see Cloud SQL Quotas and Limits).

App Engine has the ability to automatically create more instances as load increases, which may cause you to exceed these limits. To avoid this issue, limit the maximum number of App Engine instances. For more information, see Scaling elements.

Each App Engine instance running in a standard environment cannot have more than 100 concurrent connections to an instance. For PHP 5.5 apps, the limit is 60 concurrent connections.

App Engine applications are subject to request time limits depending on usage and environment. For more information, see how instances are managed in App Engine standard and flexible environments.

App Engine applications are also subject to additional App Engine quotas and limits as discussed on the App Engine Quotas page.