Connecting to Cloud SQL from Cloud Run (fully managed)

This page contains information and examples for connecting to a Cloud SQL instance from a service running in Cloud Run (fully managed).

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.

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 Cloud Run (fully managed)

Console

  1. Go to Cloud Run

  2. Click CREATE SERVICE if you are adding a Cloud SQL connection on a new service you are deploying to. If you are adding a Cloud SQL connectionon an existing service, then click on the service, then click DEPLOY NEW REVISION.

  3. Click SHOW OPTIONAL SETTINGS:

    Add Cloud SQL connection

    • If you are adding a connection to a Cloud SQL instance in your project, select the desired Cloud SQL instance from the dropdown menu.
    • If you are using a Cloud SQL instance from anther project, select custom connection string in the dropdown and then enter the full instance connection name in the format PROJECT-ID:REGION:INSTANCE-ID.

    • If you are deleting a connection, hover your cursor to the right of the connection to display the Trash icon, and click it.

  4. Click Create or Deploy.

Command line

Before using any of the commands below, make the following replacements:

  • IMAGE with the image you are deploying
  • SERVICE with the name of your Cloud Run service
  • INSTANCE-CONNECTION-NAME with the instance connection name of your Cloud SQL instance, or a comma delimited list of connection names.

If you are deploying a new container, use the following command:

gcloud run deploy --image IMAGE --add-cloudsql-instances INSTANCE-CONNECTION-NAME --set-env-vars INSTANCE-CONNECTION-NAME="INSTANCE-CONNECTION-NAME"

If you are updating an existing service, use the following command:

gcloud run services update SERVICE --add-cloudsql-instances INSTANCE-CONNECTION-NAME --set-env-vars INSTANCE-CONNECTION-NAME="INSTANCE-CONNECTION-NAME"

Cloud Run (fully managed) 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 PROJECT_NUMBER-compute@developer.gserviceaccount.com.

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 using the Unix domain socket located at /cloudsql/INSTANCE_CONNECTION_NAME. These connections are automatically encrypted without any additional configuration.

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

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,

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

Ruby

development:
  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.

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.

You can also testing using the Cloud SQL Proxy via a docker container.

Connection Pools

Connections to underlying databases may be dropped, either by the database server itself, or by the platform infrastructure. To mitigate this, we recommend that you use a client library that supports connection pools that automatically reconnect broken client connections.

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

Connection Limits

Both the MySQL and PostgreSQL editions of Cloud SQL impose a maximum limit on concurrent connections, and these limits may vary depending on the database engine chosen (see the Cloud SQL Quotas and Limits) page.

Cloud Run has the ability to automatically create more intances as load increases, which may cause you to exceed these limits. You can limit the maximum number of connections used per instance by using a connection pool. For more detailed examples on how to limit the number of connections, see the Managing database connections page.

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

Send feedback about...

Cloud SQL for MySQL
Need help? Visit our support page.