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.

Before you begin

To connect a service running in a Cloud Run instance to a Cloud SQL, you need to have your service containerized and uploaded to the Container Registry.

If you don't already have one, see these instructions about building and deploying a container image.

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)


  1. Go to Cloud Run

  2. Configure the service:

    • If you are adding a Cloud SQL connection to a new service:

      • You need to have your service containerized and uploaded to the Container Registry. If you don't already have one, see these instructions about building and deploying a container image.

      • Click CREATE SERVICE.

    • If you are adding Cloud SQL connections to an existing service:

      • Click on the service name.


  3. Enable connecting to a Cloud SQL:


    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 another 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-NAME 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
` If you are updating an existing service, use the following command:
gcloud run services update SERVICE-NAME 
--add-cloudsql-instances 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

You can optionally allow other applications or clients to connect, or prohibit from connecting, to your Cloud SQL instance. For more information, see Authentication options to determine who is allowed to connect to your instance and from where.

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.

The code samples shown below are extracts from more complete examples on the GitHub site. Click View on GitHub to see more. On the GitHub site, look for the README file in the same directory as the code. The README file discusses important setup topics, such as the use of environment variables for credentials, connection paths, and database variables. The README file also offers testing and deployment tips.


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


  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.

You can also test 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 instances 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.

Next steps