Connect using the Cloud SQL Auth Proxy

MySQL  |  PostgreSQL  |  SQL Server

This page describes how to connect to your Cloud SQL instance using theCloud SQL Auth Proxy.

For more information about how the Cloud SQL Auth Proxy works, seeAbout the Cloud SQL Auth Proxy.

Overview

Using theCloud SQL Auth Proxy is therecommended method for connecting to a Cloud SQL instance. The Cloud SQL Auth Proxy:

  • Works with both public and private IP endpoints
  • Validates connections using credentials for a user or service account
  • Wraps the connection in a SSL/TLS layer that's authorized for a Cloud SQLinstance

Some Google Cloud services and applications use the Cloud SQL Auth Proxy to provideconnections for public IP paths with encryption and authorization, including:

Applications running inGoogle Kubernetes Engine can connect using the Cloud SQL Auth Proxy.

Note: For connecting from Google Kubernetes Engine, we recommend running theCloud SQL Auth Proxy in asidecar pattern, as anadditional container that shares a pod with your application. Also see therelatedquickstart.

See theQuickstart for usingthe Cloud SQL Auth Proxy for a basic introduction to its usage.

You can also connect, with or without the Cloud SQL Auth Proxy, using a psqlclientfrom a local machine or Compute Engine.

Before you begin

Before you can connect to a Cloud SQL instance, do the following:

    • For a user or service account, make sure the account has the Cloud SQL Client role. This role contains thecloudsql.instances.connect permission, which authorizes a principal to connect to all Cloud SQL instances in a project.

      Go to the IAM page

    • You can optionally include anIAM condition in the IAM policy binding that grants the account permission to connect only to one specific Cloud SQL instance.
  1. Enable the Cloud SQL Admin API.

    Enable the API

  2. Install and initialize thegcloud CLI.
  3. Optional. Install theCloud SQL Auth Proxy Docker client.

Download the Cloud SQL Auth Proxy

Linux 64-bit

  1. Download the Cloud SQL Auth Proxy:
    curl-ocloud-sql-proxyhttps://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.18.0/cloud-sql-proxy.linux.amd64
  2. Make the Cloud SQL Auth Proxy executable:
    chmod+xcloud-sql-proxy

Linux 32-bit

  1. Download the Cloud SQL Auth Proxy:
    curl-ocloud-sql-proxyhttps://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.18.0/cloud-sql-proxy.linux.386
  2. If thecurl command is not found, runsudo apt install curl and repeat the download command.
  3. Make the Cloud SQL Auth Proxy executable:
    chmod+xcloud-sql-proxy

macOS 64-bit

  1. Download the Cloud SQL Auth Proxy:
    curl-ocloud-sql-proxyhttps://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.18.0/cloud-sql-proxy.darwin.amd64
  2. Make the Cloud SQL Auth Proxy executable:
    chmod+xcloud-sql-proxy

Mac M1

  1. Download the Cloud SQL Auth Proxy:
    curl-ocloud-sql-proxyhttps://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.18.0/cloud-sql-proxy.darwin.arm64
  2. Make the Cloud SQL Auth Proxy executable:
    chmod+xcloud-sql-proxy

Windows 64-bit

Right-clickhttps://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.18.0/cloud-sql-proxy.x64.exe and selectSave Link As to download the Cloud SQL Auth Proxy. Rename the file tocloud-sql-proxy.exe.

Windows 32-bit

Right-clickhttps://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.18.0/cloud-sql-proxy.x86.exe and selectSave Link As to download the Cloud SQL Auth Proxy. Rename the file tocloud-sql-proxy.exe.

Cloud SQL Auth Proxy Docker image

The Cloud SQL Auth Proxy has different container images, such asdistroless,alpine,andbuster. The default Cloud SQL Auth Proxy container image usesdistroless, whichcontains no shell. If you need a shell or related tools, then download an image based onalpine orbuster.For more information, seeCloud SQL Auth Proxy Container Images.

You can pull the latest image to your local machine using Docker by using the following command:

docker pull gcr.io/cloud-sql-connectors/cloud-sql-proxy:2.18.0

Note: The Cloud SQL Auth Proxy uses a repository that supports thegcr.io domain but serves images from Artifact Registry. For more information, seeTransition from Container Registry.

Other OS

For other operating systems not included here, you cancompile the Cloud SQL Auth Proxy from source.

Start the Cloud SQL Auth Proxy

Depending on your language and environment, you can start the Cloud SQL Auth Proxy using TCP sockets,Unix sockets, or the Cloud SQL Auth Proxy Docker image. The Cloud SQL Auth Proxy binary connects to one or more Cloud SQLinstances specified on the command line, and opens a local connection as either TCP or a Unixsocket. Other applications and services, such as your application code ordatabase management client tools, can connect to Cloud SQL instancesthrough those TCP or Unix socket connections.

Warning: Be careful when binding the Cloud SQL Auth Proxy to an external interface.Anyone with access to that interface/port will be authorized to connect to your instance.

TCP sockets

For TCP connections, the Cloud SQL Auth Proxy listens onlocalhost(127.0.0.1) by default.So, when you specify--port PORT_NUMBER for an instance, the local connectionis at127.0.0.1:PORT_NUMBER.

Alternatively, you can specify a different address for the local connection.For example, here's how to make the Cloud SQL Auth Proxy listen at0.0.0.0:1234 for thelocal connection:

./cloud-sql-proxy--address0.0.0.0--port1234INSTANCE_CONNECTION_NAME
  1. Copy yourINSTANCE_CONNECTION_NAME. This can be found on theOverview page for your instance in theGoogle Cloud console or by running the following command:

    gcloudsqlinstancesdescribeINSTANCE_NAME--format='value(connectionName)'

    For example:myproject:myregion:myinstance.

  2. If the instance has both public and private IP configured, and you want the Cloud SQL Auth Proxy to use theprivate IP address, you must provide the following option when you start the Cloud SQL Auth Proxy:
    --private-ip
  3. If you are using a service account to authenticate the Cloud SQL Auth Proxy, note the location on your client machine of the private key file that was created when you createdthe service account.
  4. Start the Cloud SQL Auth Proxy.

    Some possible Cloud SQL Auth Proxy invocation strings:

    • Using Cloud SDK authentication:
      ./cloud-sql-proxy--port5432INSTANCE_CONNECTION_NAME
      The specified port must not already be in use, for example, by a local database server.
    • Using a service account and explicitly including the name of the instance connection (recommended for production environments):
      ./cloud-sql-proxy\--credentials-filePATH_TO_KEY_FILEINSTANCE_CONNECTION_NAME&

    For more information about Cloud SQL Auth Proxy options, seeOptions for authenticating the Cloud SQL Auth Proxy.

Unix sockets

Note: The Cloud SQL Auth Proxy currently does not support Unix sockets on Windows, so this option is only available for Linux and macOS platforms.

The Cloud SQL Auth Proxy can listen on a Unix socket, which is a Posix standardmechanism for using a folder to manage communication between two processesrunning on the same host. Advantages to using Unix sockets are improved securityand lower latency, however, you cannot access a Unix socket from anexternal machine.

Note:The PostgreSQL standard requires a `.s.PGSQL.5432` suffix in the socket path. Some libraries apply this suffix automatically, but others require you to specify the socket path as follows:
/cloudsql/INSTANCE_CONNECTION_NAME/.s.PGSQL.5432

To create and use a Unix socket, the target directory must existand both the Cloud SQL Auth Proxy and application must have read and write access to it.

  1. Copy yourINSTANCE_CONNECTION_NAME. This can be found on theOverview page for your instance in theGoogle Cloud console or by running the following command:

    gcloudsqlinstancesdescribeINSTANCE_NAME--format='value(connectionName)'

    For example:myproject:myregion:myinstance.

  2. Create the directory where the Cloud SQL Auth Proxy sockets will live:
    sudomkdir/cloudsql;sudochmod777/cloudsql
  3. If you are using a service account to authenticate the Cloud SQL Auth Proxy, note the location on your client machine of the private key file that was created when you createdthe service account.
  4. Open a new Cloud Shell terminal window and start the Cloud SQL Auth Proxy.

    Some possible Cloud SQL Auth Proxy invocation strings:

    • Using Google Cloud SDK authentication:
      ./cloud-sql-proxy--unix-socket/cloudsqlINSTANCE_CONNECTION_NAME&
    • Using a service account:
      ./cloud-sql-proxy--unix-socket/cloudsql--credentials-filePATH_TO_KEY_FILEINSTANCE_CONNECTION_NAME&

    Start the Cloud SQL Auth Proxy in its own Cloud Shell terminal so you can monitor its output without it mixing with the output from other programs.

    For more information about Cloud SQL Auth Proxy options, seeOptions for authenticating the Cloud SQL Auth Proxy.NOTE: When using a unix socket to connect to Cloud SQL using the Cloud SQL Auth Proxy, make sure the socket filename's length does not surpass the system's limit. It depends on the system, but it's usually between 91-108 characters. On Linux, the length is usually defined as 108, and you can use the following command to check:

    cat/usr/include/linux/un.h|grep"define UNIX_PATH_MAX"

Docker

To run the Cloud SQL Auth Proxy in a Docker container, use the Cloud SQL Auth Proxy Dockerimage available from theGoogle Container Registry.

You can start the Cloud SQL Auth Proxy using either TCP sockets or Unix sockets, with thecommands shown below. The options use anINSTANCE_CONNECTION_NAME asthe connection string to identify a Cloud SQL instance. You can find theINSTANCE_CONNECTION_NAME on theOverview page for yourinstance in theGoogle Cloud console. or by running thefollowing command:

gcloudsqlinstancesdescribeINSTANCE_NAME
.

For example:myproject:myregion:myinstance.

Note: The Cloud SQL Auth Proxy doesn't support listening on Unix domain sockets on Windows.

Depending on your language and environment, you can start the Cloud SQL Auth Proxy using either TCP sockets or Unix sockets. Unix sockets are not supported for applications written in the Java programming language or for the Windows environment.

Using TCP sockets

dockerrun-d\\-vPATH_TO_KEY_FILE:/path/to/service-account-key.json\\-p127.0.0.1:5432:5432\\gcr.io/cloud-sql-connectors/cloud-sql-proxy:2.18.0\\--address0.0.0.0--port5432\\--credentials-file/path/to/service-account-key.jsonINSTANCE_CONNECTION_NAME

If you're using the credentials provided by your Compute Engine instance, don't include the--credentials-file parameter and the-vPATH_TO_KEY_FILE:/path/to/service-account-key.json line.

Always specify127.0.0.1 prefix in -p so that the Cloud SQL Auth Proxy is not exposed outside the local host. The "0.0.0.0" in the instances parameter is required to make the port accessible from outside of the Docker container.

Using Unix sockets

dockerrun-d-v/cloudsql:/cloudsql\\-vPATH_TO_KEY_FILE:/path/to/service-account-key.json\\gcr.io/cloud-sql-connectors/cloud-sql-proxy:2.18.0--unix-socket=/cloudsql\\--credentials-file/path/to/service-account-key.jsonINSTANCE_CONNECTION_NAME

If you're using the credentials provided by your Compute Engine instance, don't include the--credentials-file parameter and the-vPATH_TO_KEY_FILE:/path/to/service-account-key.json line.

If you are using a container optimized image, use a writeable directory in place of/cloudsql, for example:

-v /mnt/stateful_partition/cloudsql:/cloudsql

You can specify more than one instance, separated by commas. You can also useCompute Engine metadata to dynamically determine the instances to connect to.Learn more about the Cloud SQL Auth Proxy parameters.

Connect with the psql client

Debian/Ubuntu

Install the psql client from the package manager:

sudoapt-getupdatesudoapt-getinstallpostgresql-client

CentOS/RHEL

Install the psql client from the package manager:

sudoyuminstallpostgresql

openSUSE

Install the psql client from the package manager:

sudozypperinstallpostgresql

Other platforms

  1. Download the PostgreSQL Core Distribution for your platform from thePostgreSQL Downloads page.
    The Core Distribution includes the psql client.
  2. Install the PostgreSQL database, following the directions on the download page.

The connection string you use depends on whether you started the Cloud SQL Auth Proxy using a TCP socket ora UNIX socket or Docker.

TCP sockets

  1. Start the psql client:
    psql"host=127.0.0.1 sslmode=disable dbname=DB_NAME user=USERNAME"

    Even though thesslmode parameter is set todisable, the Cloud SQL Auth Proxy does provide an encrypted connection.

    When you connect using TCP sockets, the Cloud SQL Auth Proxy is accessed through127.0.0.1.

  2. If prompted, enter the password.
  3. The psql prompt appears.

Using Unix sockets

  1. Start the psql client:
    psql"sslmode=disable host=/cloudsql/INSTANCE_CONNECTION_NAME dbname=DB_NAME user=USERNAME"

    Even though thesslmode parameter is set todisable, the Cloud SQL Auth Proxy does provide an encrypted connection.

  2. Enter the password.
  3. The psql prompt appears.

Need help? For help troubleshooting the proxy, seeTroubleshooting Cloud SQL Auth Proxy connections, or see ourCloud SQL Support page.

Connect with an application

You can connect to the Cloud SQL Auth Proxy from any language that enables you to connect to aUnix or TCP socket. Below are some code snippets from complete examples on GitHub to help youunderstand how they work together in your application.

Connecting with TCP

Cloud SQL Auth Proxy invocation statement:

./cloud-sql-proxyINSTANCE_CONNECTION_NAME&

Python

To see this snippet in the context of a web application, viewthe README on GitHub.

importosimportsslimportsqlalchemydefconnect_tcp_socket()->sqlalchemy.engine.base.Engine:"""Initializes a TCP connection pool for a Cloud SQL instance of Postgres."""# Note: Saving credentials in environment variables is convenient, but not# secure - consider a more secure solution such as# Cloud Secret Manager (https://cloud.google.com/secret-manager) to help# keep secrets safe.db_host=os.environ["INSTANCE_HOST"]# e.g. '127.0.0.1' ('172.17.0.1' if deployed to GAE Flex)db_user=os.environ["DB_USER"]# e.g. 'my-db-user'db_pass=os.environ["DB_PASS"]# e.g. 'my-db-password'db_name=os.environ["DB_NAME"]# e.g. 'my-database'db_port=os.environ["DB_PORT"]# e.g. 5432pool=sqlalchemy.create_engine(# Equivalent URL:# postgresql+pg8000://<db_user>:<db_pass>@<db_host>:<db_port>/<db_name>sqlalchemy.engine.url.URL.create(drivername="postgresql+pg8000",username=db_user,password=db_pass,host=db_host,port=db_port,database=db_name,),# ...)returnpool

Java

To see this snippet in the context of a web application, viewthe README on GitHub.

Note:

importcom.zaxxer.hikari.HikariConfig;importcom.zaxxer.hikari.HikariDataSource;importjavax.sql.DataSource;publicclassTcpConnectionPoolFactoryextendsConnectionPoolFactory{// Note: Saving credentials in environment variables is convenient, but not// secure - consider a more secure solution such as// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help// keep secrets safe.privatestaticfinalStringDB_USER=System.getenv("DB_USER");privatestaticfinalStringDB_PASS=System.getenv("DB_PASS");privatestaticfinalStringDB_NAME=System.getenv("DB_NAME");privatestaticfinalStringINSTANCE_HOST=System.getenv("INSTANCE_HOST");privatestaticfinalStringDB_PORT=System.getenv("DB_PORT");publicstaticDataSourcecreateConnectionPool(){// The configuration object specifies behaviors for the connection pool.HikariConfigconfig=newHikariConfig();// The following URL is equivalent to setting the config options below:// jdbc:postgresql://<INSTANCE_HOST>:<DB_PORT>/<DB_NAME>?user=<DB_USER>&password=<DB_PASS>// See the link below for more info on building a JDBC URL for the Cloud SQL JDBC Socket Factory// https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory#creating-the-jdbc-url// Configure which instance and what database user to connect with.config.setJdbcUrl(String.format("jdbc:postgresql://%s:%s/%s",INSTANCE_HOST,DB_PORT,DB_NAME));config.setUsername(DB_USER);// e.g. "root", "postgres"config.setPassword(DB_PASS);// e.g. "my-password"// ... Specify additional connection properties here.// ...// Initialize the connection pool using the configuration object.returnnewHikariDataSource(config);}}

Node.js

To see this snippet in the context of a web application, viewthe README on GitHub.

constKnex=require('knex');constfs=require('fs');// createTcpPool initializes a TCP connection pool for a Cloud SQL// instance of Postgres.constcreateTcpPool=asyncconfig=>{// Note: Saving credentials in environment variables is convenient, but not// secure - consider a more secure solution such as// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help// keep secrets safe.constdbConfig={client:'pg',connection:{host:process.env.INSTANCE_HOST,// e.g. '127.0.0.1'port:process.env.DB_PORT,// e.g. '5432'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'},// ... Specify additional properties here....config,};// Establish a connection to the database.returnKnex(dbConfig);};

Go

To see this snippet in the context of a web application, viewthe README on GitHub.

packagecloudsqlimport("database/sql""fmt""log""os"// Note: If connecting using the App Engine Flex Go runtime, use// "github.com/jackc/pgx/stdlib" instead, since v5 requires// Go modules which are not supported by App Engine Flex._"github.com/jackc/pgx/v5/stdlib")// connectTCPSocket initializes a TCP connection pool for a Cloud SQL// instance of Postgres.funcconnectTCPSocket()(*sql.DB,error){mustGetenv:=func(kstring)string{v:=os.Getenv(k)ifv==""{log.Fatalf("Fatal Error in connect_tcp.go: %s environment variable not set.",k)}returnv}// Note: Saving credentials in environment variables is convenient, but not// secure - consider a more secure solution such as// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help// keep secrets safe.var(dbUser=mustGetenv("DB_USER")// e.g. 'my-db-user'dbPwd=mustGetenv("DB_PASS")// e.g. 'my-db-password'dbTCPHost=mustGetenv("INSTANCE_HOST")// e.g. '127.0.0.1' ('172.17.0.1' if deployed to GAE Flex)dbPort=mustGetenv("DB_PORT")// e.g. '5432'dbName=mustGetenv("DB_NAME")// e.g. 'my-database')dbURI:=fmt.Sprintf("host=%s user=%s password=%s port=%s database=%s",dbTCPHost,dbUser,dbPwd,dbPort,dbName)// dbPool is the pool of database connections.dbPool,err:=sql.Open("pgx",dbURI)iferr!=nil{returnnil,fmt.Errorf("sql.Open: %w",err)}// ...returndbPool,nil}

C#

To see this snippet in the context of a web application, viewthe README on GitHub.

usingNpgsql;usingSystem;namespaceCloudSql{publicclassPostgreSqlTcp{publicstaticNpgsqlConnectionStringBuilderNewPostgreSqlTCPConnectionString(){// Equivalent connection string:// "Uid=<DB_USER>;Pwd=<DB_PASS>;Host=<INSTANCE_HOST>;Database=<DB_NAME>;"varconnectionString=newNpgsqlConnectionStringBuilder(){// Note: Saving credentials in environment variables is convenient, but not// secure - consider a more secure solution such as// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help// keep secrets safe.Host=Environment.GetEnvironmentVariable("INSTANCE_HOST"),// e.g. '127.0.0.1'// Set Host to 'cloudsql' when deploying to App Engine Flexible environmentUsername=Environment.GetEnvironmentVariable("DB_USER"),// e.g. 'my-db-user'Password=Environment.GetEnvironmentVariable("DB_PASS"),// e.g. 'my-db-password'Database=Environment.GetEnvironmentVariable("DB_NAME"),// e.g. 'my-database'// The Cloud SQL proxy provides encryption between the proxy and instance.SslMode=SslMode.Disable,};connectionString.Pooling=true;// Specify additional properties here.returnconnectionString;}}}

Ruby

To see this snippet in the context of a web application, viewthe README on GitHub.

tcp:&tcpadapter:postgresql# Configure additional properties here.# Note: Saving credentials in environment variables is convenient, but not# secure - consider a more secure solution such as# Cloud Secret Manager (https://cloud.google.com/secret-manager) to help# keep secrets safe.username:<%= ENV["DB_USER"] %>  # e.g. "my-database-user"  password: <%=ENV["DB_PASS"]%># e.g. "my-database-password"database:<%= ENV.fetch("DB_NAME") { "vote_development" } %>  host: <%=ENV.fetch("INSTANCE_HOST"){"127.0.0.1"}%># '172.17.0.1' if deployed to GAE Flexport:<%=ENV.fetch("DB_PORT"){5432}%>

PHP

To see this snippet in the context of a web application, viewthe README on GitHub.

namespace Google\Cloud\Samples\CloudSQL\Postgres;use PDO;use PDOException;use RuntimeException;use TypeError;class DatabaseTcp{    public static function initTcpDatabaseConnection(): PDO    {        try {            // Note: Saving credentials in environment variables is convenient, but not            // secure - consider a more secure solution such as            // Cloud Secret Manager (https://cloud.google.com/secret-manager) to help            // keep secrets safe.            $username = getenv('DB_USER'); // e.g. 'your_db_user'            $password = getenv('DB_PASS'); // e.g. 'your_db_password'            $dbName = getenv('DB_NAME'); // e.g. 'your_db_name'            $instanceHost = getenv('INSTANCE_HOST'); // e.g. '127.0.0.1' ('172.17.0.1' for GAE Flex)            // Connect using TCP            $dsn = sprintf('pgsql:dbname=%s;host=%s', $dbName, $instanceHost);            // Connect to the database            $conn = new PDO(                $dsn,                $username,                $password,                # ...            );        } catch (TypeError $e) {            throw new RuntimeException(                sprintf(                    'Invalid or missing configuration! Make sure you have set ' .                        '$username, $password, $dbName, and $instanceHost (for TCP mode). ' .                        'The PHP error was %s',                    $e->getMessage()                ),                $e->getCode(),                $e            );        } catch (PDOException $e) {            throw new RuntimeException(                sprintf(                    'Could not connect to the Cloud SQL Database. Check that ' .                        'your username and password are correct, that the Cloud SQL ' .                        'proxy is running, and that the database exists and is ready ' .                        'for use. For more assistance, refer to %s. The PDO error was %s',                    'https://cloud.google.com/sql/docs/postgres/connect-external-app',                    $e->getMessage()                ),                $e->getCode(),                $e            );        }        return $conn;    }}

Connecting with Unix sockets

Cloud SQL Auth Proxy invocation statement:

./cloud-sql-proxy --unix-socket /cloudsqlINSTANCE_CONNECTION_NAME &

Python

To see this snippet in the context of a web application, viewthe README on GitHub.

importosimportsqlalchemydefconnect_unix_socket()->sqlalchemy.engine.base.Engine:"""Initializes a Unix socket connection pool for a Cloud SQL instance of Postgres."""# Note: Saving credentials in environment variables is convenient, but not# secure - consider a more secure solution such as# Cloud Secret Manager (https://cloud.google.com/secret-manager) to help# keep secrets safe.db_user=os.environ["DB_USER"]# e.g. 'my-database-user'db_pass=os.environ["DB_PASS"]# e.g. 'my-database-password'db_name=os.environ["DB_NAME"]# e.g. 'my-database'unix_socket_path=os.environ["INSTANCE_UNIX_SOCKET"]# e.g. '/cloudsql/project:region:instance'pool=sqlalchemy.create_engine(# Equivalent URL:# postgresql+pg8000://<db_user>:<db_pass>@/<db_name>#                         ?unix_sock=<INSTANCE_UNIX_SOCKET>/.s.PGSQL.5432# Note: Some drivers require the `unix_sock` query parameter to use a different key.# For example, 'psycopg2' uses the path set to `host` in order to connect successfully.sqlalchemy.engine.url.URL.create(drivername="postgresql+pg8000",username=db_user,password=db_pass,database=db_name,query={"unix_sock":f"{unix_socket_path}/.s.PGSQL.5432"},),# ...)returnpool

Java

To see this snippet in the context of a web application, viewthe README on GitHub.

importcom.zaxxer.hikari.HikariConfig;importcom.zaxxer.hikari.HikariDataSource;importjavax.sql.DataSource;publicclassConnectorConnectionPoolFactoryextendsConnectionPoolFactory{// Note: Saving credentials in environment variables is convenient, but not// secure - consider a more secure solution such as// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help// keep secrets safe.privatestaticfinalStringINSTANCE_CONNECTION_NAME=System.getenv("INSTANCE_CONNECTION_NAME");privatestaticfinalStringINSTANCE_UNIX_SOCKET=System.getenv("INSTANCE_UNIX_SOCKET");privatestaticfinalStringDB_USER=System.getenv("DB_USER");privatestaticfinalStringDB_PASS=System.getenv("DB_PASS");privatestaticfinalStringDB_NAME=System.getenv("DB_NAME");publicstaticDataSourcecreateConnectionPool(){// The configuration object specifies behaviors for the connection pool.HikariConfigconfig=newHikariConfig();// The following URL is equivalent to setting the config options below:// jdbc:postgresql:///<DB_NAME>?cloudSqlInstance=<INSTANCE_CONNECTION_NAME>&// socketFactory=com.google.cloud.sql.postgres.SocketFactory&user=<DB_USER>&password=<DB_PASS>// See the link below for more info on building a JDBC URL for the Cloud SQL JDBC Socket Factory// https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory#creating-the-jdbc-url// 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"config.addDataSourceProperty("socketFactory","com.google.cloud.sql.postgres.SocketFactory");config.addDataSourceProperty("cloudSqlInstance",INSTANCE_CONNECTION_NAME);// Unix sockets are not natively supported in Java, so it is necessary to use the Cloud SQL// Java Connector to connect. When setting INSTANCE_UNIX_SOCKET, the connector will// call an external package that will enable Unix socket connections.// Note: For Java users, the Cloud SQL Java Connector can provide authenticated connections// which is usually preferable to using the Cloud SQL Proxy with Unix sockets.// See https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory for details.if(INSTANCE_UNIX_SOCKET!=null){config.addDataSourceProperty("unixSocketPath",INSTANCE_UNIX_SOCKET);}// cloudSqlRefreshStrategy set to "lazy" is used to perform a// refresh when needed, rather than on a scheduled interval.// This is recommended for serverless environments to// avoid background refreshes from throttling CPU.config.addDataSourceProperty("cloudSqlRefreshStrategy","lazy");// ... Specify additional connection properties here.// ...// Initialize the connection pool using the configuration object.returnnewHikariDataSource(config);}}

Node.js

To see this snippet in the context of a web application, viewthe README on GitHub.

constKnex=require('knex');// createUnixSocketPool initializes a Unix socket connection pool for// a Cloud SQL instance of Postgres.constcreateUnixSocketPool=asyncconfig=>{// Note: Saving credentials in environment variables is convenient, but not// secure - consider a more secure solution such as// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help// keep secrets safe.returnKnex({client:'pg',connection:{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'host:process.env.INSTANCE_UNIX_SOCKET,// e.g. '/cloudsql/project:region:instance'},// ... Specify additional properties here....config,});};

C#

To see this snippet in the context of a web application, viewthe README on GitHub.

usingNpgsql;usingSystem;namespaceCloudSql{publicclassPostgreSqlUnix{publicstaticNpgsqlConnectionStringBuilderNewPostgreSqlUnixSocketConnectionString(){// Equivalent connection string:// "Server=<INSTANCE_UNIX_SOCKET>;Uid=<DB_USER>;Pwd=<DB_PASS>;Database=<DB_NAME>"varconnectionString=newNpgsqlConnectionStringBuilder(){// The Cloud SQL proxy provides encryption between the proxy and instance.SslMode=SslMode.Disable,// Note: Saving credentials in environment variables is convenient, but not// secure - consider a more secure solution such as// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help// keep secrets safe.Host=Environment.GetEnvironmentVariable("INSTANCE_UNIX_SOCKET"),// e.g. '/cloudsql/project:region:instance'Username=Environment.GetEnvironmentVariable("DB_USER"),// e.g. 'my-db-userPassword=Environment.GetEnvironmentVariable("DB_PASS"),// e.g. 'my-db-password'Database=Environment.GetEnvironmentVariable("DB_NAME"),// e.g. 'my-database'};connectionString.Pooling=true;// Specify additional properties here.returnconnectionString;}}}

Go

To see this snippet in the context of a web application, viewthe README on GitHub.

packagecloudsqlimport("database/sql""fmt""log""os"// Note: If connecting using the App Engine Flex Go runtime, use// "github.com/jackc/pgx/stdlib" instead, since v5 requires// Go modules which are not supported by App Engine Flex._"github.com/jackc/pgx/v5/stdlib")// connectUnixSocket initializes a Unix socket connection pool for// a Cloud SQL instance of Postgres.funcconnectUnixSocket()(*sql.DB,error){mustGetenv:=func(kstring)string{v:=os.Getenv(k)ifv==""{log.Fatalf("Fatal Error in connect_unix.go: %s environment variable not set.\n",k)}returnv}// Note: Saving credentials in environment variables is convenient, but not// secure - consider a more secure solution such as// Cloud Secret Manager (https://cloud.google.com/secret-manager) to help// keep secrets safe.var(dbUser=mustGetenv("DB_USER")// e.g. 'my-db-user'dbPwd=mustGetenv("DB_PASS")// e.g. 'my-db-password'unixSocketPath=mustGetenv("INSTANCE_UNIX_SOCKET")// e.g. '/cloudsql/project:region:instance'dbName=mustGetenv("DB_NAME")// e.g. 'my-database')dbURI:=fmt.Sprintf("user=%s password=%s database=%s host=%s",dbUser,dbPwd,dbName,unixSocketPath)// dbPool is the pool of database connections.dbPool,err:=sql.Open("pgx",dbURI)iferr!=nil{returnnil,fmt.Errorf("sql.Open: %w",err)}// ...returndbPool,nil}

Ruby

To see this snippet in the context of a web application, viewthe README on GitHub.

unix:&unixadapter:postgresql# Configure additional properties here.# Note: Saving credentials in environment variables is convenient, but not# secure - consider a more secure solution such as# Cloud Secret Manager (https://cloud.google.com/secret-manager) to help# keep secrets safe.username:<%= ENV["DB_USER"] %>  # e.g. "my-database-user"  password: <%=ENV["DB_PASS"]%># e.g. "my-database-password"database:<%= ENV.fetch("DB_NAME") { "vote_development" } %>  # Specify the Unix socket path as host  host: "<%=ENV["INSTANCE_UNIX_SOCKET"]%>"

PHP

To see this snippet in the context of a web application, viewthe README on GitHub.

namespace Google\Cloud\Samples\CloudSQL\Postgres;use PDO;use PDOException;use RuntimeException;use TypeError;class DatabaseUnix{    public static function initUnixDatabaseConnection(): PDO    {        try {            // Note: Saving credentials in environment variables is convenient, but not            // secure - consider a more secure solution such as            // Cloud Secret Manager (https://cloud.google.com/secret-manager) to help            // keep secrets safe.            $username = getenv('DB_USER'); // e.g. 'your_db_user'            $password = getenv('DB_PASS'); // e.g. 'your_db_password'            $dbName = getenv('DB_NAME'); // e.g. 'your_db_name'            $instanceUnixSocket = getenv('INSTANCE_UNIX_SOCKET'); // e.g. '/cloudsql/project:region:instance'            // Connect using UNIX sockets            $dsn = sprintf(                'pgsql:dbname=%s;host=%s',                $dbName,                $instanceUnixSocket            );            // Connect to the database.            $conn = new PDO(                $dsn,                $username,                $password,                # ...            );        } catch (TypeError $e) {            throw new RuntimeException(                sprintf(                    'Invalid or missing configuration! Make sure you have set ' .                        '$username, $password, $dbName, ' .                        'and $instanceUnixSocket (for UNIX socket mode). ' .                        'The PHP error was %s',                    $e->getMessage()                ),                (int) $e->getCode(),                $e            );        } catch (PDOException $e) {            throw new RuntimeException(                sprintf(                    'Could not connect to the Cloud SQL Database. Check that ' .                        'your username and password are correct, that the Cloud SQL ' .                        'proxy is running, and that the database exists and is ready ' .                        'for use. For more assistance, refer to %s. The PDO error was %s',                    'https://cloud.google.com/sql/docs/postgres/connect-external-app',                    $e->getMessage()                ),                (int) $e->getCode(),                $e            );        }        return $conn;    }}

Additional topics

Cloud SQL Auth Proxy command-line arguments

The examples above cover the most common use cases, but the Cloud SQL Auth Proxyalso has other configuration options that can be set with command-linearguments. For help on command-line arguments, use the--help flagto view the latest documentation:

./cloud-sql-proxy--help

See theREADME on the Cloud SQL Auth Proxy GitHub repositoryfor additional examples of how to use Cloud SQL Auth Proxy command-line options.

Options for authenticating the Cloud SQL Auth Proxy

When you authenticate the Cloud SQL Auth Proxy, you enable it to accessGoogle Cloud on behalf of your application, using a set of Googlecredentials. This is separate from database user authentication.IAM user database authentication is integrated with theCloud SQL Auth Proxy.

All of these options use anINSTANCE_CONNECTION_NAME asthe connection string to identify a Cloud SQL instance. You can find theINSTANCE_CONNECTION_NAME on theOverview page for yourinstance in theGoogle Cloud console. or by running thefollowing command:

gcloud sql instances describe --projectPROJECT_IDINSTANCE_CONNECTION_NAME.

For example:gcloud sql instances describe --project myproject myinstance .

Some of these options use a JSON credentials file that includes the RSA privatekey for the account. For instructions on creating a JSON credentials file for aservice account, seeCreating a service account.

The Cloud SQL Auth Proxy provides several alternatives for authentication, depending onyour environment. The Cloud SQL Auth Proxy checks for each of the following items, in the followingorder, using the first one it finds to attempt to authenticate:

  1. Credentials supplied by the credentials-file flag.

    Use aservice account to create and download the associated JSON file, and set the--credentials-file flag to the path of the file when you start the Cloud SQL Auth Proxy. The service account must have therequired permissions for the Cloud SQL instance.

    To use this option on the command-line, invoke thecloud-sql-proxy command with the--credentials-file flag set to the path and filename of a JSON credential file. The path can be absolute, or relative to the current working directory. For example:

    ./cloud-sql-proxy--credentials-filePATH_TO_KEY_FILE\INSTANCE_CONNECTION_NAME

    For detailed instructions about adding IAM roles to a service account, seeGranting Roles to Service Accounts.

    For more information about the roles Cloud SQL supports, seeIAM roles for Cloud SQL.

  2. Credentials supplied by an access token.

    Create an access token and invoke thecloud-sql-proxy command with the--token flag set to an OAuth 2.0 access token. For example:
    ./cloud-sql-proxy--tokenACCESS_TOKEN\INSTANCE_CONNECTION_NAME
  3. Credentials supplied by an environment variable.

    This option is similar to using the--credentials-file flag, except you specify the JSON credential file you set in theGOOGLE_APPLICATION_CREDENTIALS environment variable instead of using the--credentials-file command-line argument.
  4. Credentials from an authenticatedgcloud CLI client.

    If you have installed thegcloud CLI and have authenticated with your personal account, the Cloud SQL Auth Proxy can use the same account credentials. This method is especially helpful for getting a development environment up and running.

    To enable the Cloud SQL Auth Proxy to use your gcloud CLI credentials, use the following command to authenticate the gcloud CLI:

    gcloudauthapplication-defaultlogin
  5. Credentials associated with the Compute Engine instance.

    If you are connecting to Cloud SQL from a Compute Engine instance, theCloud SQL Auth Proxy can use the service account associated with the Compute Engine instance.If the service account has therequired permissionsfor the Cloud SQL instance, the Cloud SQL Auth Proxy authenticates successfully.

    If the Compute Engine instance is in the same project as the Cloud SQLinstance, the default service account for the Compute Engine instance has thenecessary permissions for authenticating the Cloud SQL Auth Proxy.If the two instances are in different projects, you must add the Compute Engineinstance's service account to the project containing the Cloud SQLinstance.

  6. Environment's default service account

    If the Cloud SQL Auth Proxy cannot find credentials in any of the places covered earlier, itfollows the logic documented inSetting Up Authentication for Server to Server ProductionApplications. Some environment (such as Compute Engine, App Engine, and others) provide adefault service account that your application can use to authenticate by default. Ifyou use a default service account, it must have the permissions outlined inroles and permissionsFor more information about Google Cloud's approach to authentication, seeAuthentication overview.

Create a service account

If you are connecting from Compute Engine, make sureyour VM has the properscope to connect using the Cloud SQL Admin API.

Configure the service account to have either of the following access scopes:

  • https://www.googleapis.com/auth/sqlservice.admin
  • https://www.googleapis.com/auth/cloud-platform
  1. In the Google Cloud console, go to theService accounts page.

    Go to Service accounts

  2. Select the project that contains your Cloud SQL instance.
  3. ClickCreate service account.
  4. In theService account name field, enter a descriptive name for the service account.
  5. Change theService account ID to a unique, recognizable value and then clickCreate and continue.
  6. Click theSelect a role field and select one of the following roles:
  7. ClickDone to finish creating the service account.
  8. Click the action menu for your new service account and then selectManage keys.
  9. Click theAdd key drop-down menu and then clickCreate new key.
  10. Confirm that the key type is JSON and then clickCreate.

    The private key file is downloaded to your machine. You can move it to another location. Keep the key file secure.

Use the Cloud SQL Auth Proxy with private IP

To connect to a Cloud SQL instance using private IP, the Cloud SQL Auth Proxymust be on a resource with access to the same VPC network as theinstance.

The Cloud SQL Auth Proxy uses IP to establish a connection with your Cloud SQL instance.By default, the Cloud SQL Auth Proxy attempts to connect using a public IPv4 address.

If your Cloud SQL instance has only private IP or the instance has bothpublic and private IP configured, and you want the Cloud SQL Auth Proxy to use the privateIP address, then you must provide the following option when you start the Cloud SQL Auth Proxy:

--private-ip

Use the Cloud SQL Auth Proxy with instances that have Private Service Connect enabled

You can use the Cloud SQL Auth Proxy to connect to a Cloud SQL instance with Private Service Connect enabled.

The Cloud SQL Auth Proxy is a connector that provides secure access to this instance without a need for authorized networks or for configuring SSL.

To allow Cloud SQL Auth Proxy client connections, you must set up aDNS record which matches the recommendedDNS name that's provided for the instance. The DNS record is a mapping between a DNS resource and a domain name.

For more information about using the Cloud SQL Auth Proxy to connect to instances with Private Service Connect enabled, seeConnect using the Cloud SQL Auth Proxy.

Run the Cloud SQL Auth Proxy in a separate process

Running the Cloud SQL Auth Proxy in a separate Cloud Shell terminal process can be useful, to avoidmixing its console output with output from other programs. Use the syntaxshown below to invoke the Cloud SQL Auth Proxy in a separate process.

Linux

On Linux or macOS, use a trailing& on the command line tolaunch the Cloud SQL Auth Proxy in a separate process:

./cloud-sql-proxyINSTANCE_CONNECTION_NAME--credentials-filePATH_TO_KEY_FILE&

Windows

In Windows PowerShell, use theStart-Process command to launchthe Cloud SQL Auth Proxy in a separate process:

Start-Process--filepath "cloud-sql-proxy.exe"--ArgumentList "--credentials-filePATH_TO_KEY_FILEINSTANCE_CONNECTION_NAME"

Run the Cloud SQL Auth Proxy in a Docker container

To run the Cloud SQL Auth Proxy in a Docker container, use the Cloud SQL Auth Proxy Dockerimage available from theGoogle Container Registry.You can install the Cloud SQL Auth Proxy Docker image using the following command:

dockerpullgcr.io/cloud-sql-connectors/cloud-sql-proxy:2.18.0

You can start the Cloud SQL Auth Proxy using either TCP sockets or Unix sockets, with thecommands shown below.

Note: Unix sockets are not supported for applications written in the Javaprogramming language or for the Windows environment.

TCP sockets

dockerrun-d\-vPATH_TO_KEY_FILE:/path/to/service-account-key.json\-p127.0.0.1:5432:5432\gcr.io/cloud-sql-connectors/cloud-sql-proxy:2.18.0\--address0.0.0.0\--credentials-file/path/to/service-account-key.json\INSTANCE_CONNECTION_NAME

Unix sockets

dockerrun-d\-v/PATH_TO_HOST_TARGET:/PATH_TO_GUEST_TARGET\-vPATH_TO_KEY_FILE:/path/to/service-account-key.json\gcr.io/cloud-sql-connectors/cloud-sql-proxy:2.18.0--unix-socket/cloudsql\--credentials-file/path/to/service-account-key.json/PATH_TO_KEY_FILE\INSTANCE_CONNECTION_NAME

If you are using a container optimized image, use a writeable directoryin place of/cloudsql, for example:

v/mnt/stateful_partition/cloudsql:/cloudsql

If you are using the credentials provided by your Compute Engine instance,do not include thecredential_file parameter and the-vPATH_TO_KEY_FILE:/path/to/service-account-key.json line.

Running the Cloud SQL Auth Proxy as a service

Running the Cloud SQL Auth Proxy as a background service is an option for local developmentand production workloads. In development, when you need to access yourCloud SQL instance, you can start the service in the background and stop itwhen you're finished.

For production workloads, the Cloud SQL Auth Proxy doesn't currently provide built-insupport for running as a Windows service, but third-party service managers canbe used to run it as a service. For example, you can useNSSMto configure the Cloud SQL Auth Proxy as a Windows service, and NSSM monitors theCloud SQL Auth Proxy and restarts it automatically if it stops responding. See theNSSM documentation for more information.

Note: If you run the Cloud SQL Auth Proxy as a service, keep in mind that it uses a secureconnection to communicate with Cloud SQL instances, but connectionsfrom your application to the Cloud SQL Auth Proxy are not encrypted. For this reason, ensurethat only trusted users are able to access the address and portthat the Cloud SQL Auth Proxy is listening on.

Enforce the use of the Cloud SQL Auth Proxy

Enable the use of the Cloud SQL Auth Proxy in Cloud SQL usingConnectorEnforcement.

If you're using aPrivate Service Connect-enabled instance, then there's a limitation. If the instance has connector enforcement enabled, then you can't create read replicas for the instance. Similarly, if the instance has read replicas, then you can't enable connector enforcement for the instance.

gcloud

The following command enforces the use of Cloud SQL connectors.

gcloudsqlinstancespatchINSTANCE_NAME\--connector-enforcementREQUIRED

To disable the enforcement, use the following line of code:--connector-enforcement NOT_REQUIRED The update doesn't trigger a restart.

REST v1

The following command enforces the use of Cloud SQL connectors

Before using any of the request data, make the following replacements:

  • project-id: The project ID.
  • instance-id: The instance ID.

HTTP method and URL:

PATCH https://sqladmin.googleapis.com/v1/projects/project-id/instances/instance-id

Request JSON body:

{  "settings": {                         "connectorEnforcement": "REQUIRED"      }                                             }

To send your request, expand one of these options:

curl (Linux, macOS, or Cloud Shell)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

curl -X PATCH \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://sqladmin.googleapis.com/v1/projects/project-id/instances/instance-id"

PowerShell (Windows)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method PATCH `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://sqladmin.googleapis.com/v1/projects/project-id/instances/instance-id" | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{  "kind": "sql#operation",  "targetLink": "https://sqladmin.googleapis.com/v1/projects/project-id/instances/instance-id",  "status": "PENDING",  "user": "user@example.com",  "insertTime": "2020-01-16T02:32:12.281Z",  "operationType": "UPDATE",  "name": "operation-id",  "targetId": "instance-id",  "selfLink": "https://sqladmin.googleapis.com/v1/projects/project-id/operations/operation-id",  "targetProject": "project-id"}

To disable the enforcement, use"connectorEnforcement": "NOT_REQUIRED" instead. The update does not trigger a restart.

REST v1beta4

The following command enforces the use of Cloud SQL connectors.

Before using any of the request data, make the following replacements:

  • project-id: The project ID.
  • instance-id: The instance ID.

HTTP method and URL:

PATCH https://sqladmin.googleapis.com/sql/v1beta4/projects/project-id/instances/instance-id

Request JSON body:

{  "settings": {    "connectorEnforcement": "REQUIRED"  }}

To send your request, expand one of these options:

curl (Linux, macOS, or Cloud Shell)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login , or by usingCloud Shell, which automatically logs you into thegcloud CLI . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

curl -X PATCH \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://sqladmin.googleapis.com/sql/v1beta4/projects/project-id/instances/instance-id"

PowerShell (Windows)

Note: The following command assumes that you have logged in to thegcloud CLI with your user account by runninggcloud init orgcloud auth login . You can check the currently active account by runninggcloud auth list.

Save the request body in a file namedrequest.json, and execute the following command:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method PATCH `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://sqladmin.googleapis.com/sql/v1beta4/projects/project-id/instances/instance-id" | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{  "kind": "sql#operation",  "targetLink": "https://sqladmin.googleapis.com/sql/v1beta4/projects/project-id/instances/instance-id",  "status": "PENDING",  "user": "user@example.com",  "insertTime": "2020-01-16T02:32:12.281Z",  "operationType": "UPDATE",  "name": "operation-id",  "targetId": "instance-id",  "selfLink": "https://sqladmin.googleapis.com/sql/v1beta4/projects/project-id/operations/operation-id",  "targetProject": "project-id"}

To disable the enforcement, use"connectorEnforcement": "NOT_REQUIRED" instead. The update does not trigger a restart.

Tips for working with Cloud SQL Auth Proxy

Invoke the Cloud SQL Auth Proxy

All of the sample proxy invocations start the Cloud SQL Auth Proxy in the background, so aprompt is returned. Reserve that Cloud Shell terminal for the Cloud SQL Auth Proxy, toavoid having its output mixed with the output from other programs. Also, theoutput from the Cloud SQL Auth Proxy can help you diagnose connection problems, so it can behelpful to capture in a log file. If you do not start the Cloud SQL Auth Proxy in the background,the output goes to stdout unless redirected.

You do not have to use/cloudsql as the directory for the Cloud SQL Auth Proxy sockets. (Thatdirectory name was chosen to minimize differences with App Engineconnection strings.) If you change the directory name, however, keep the overalllength to a minimum; it is incorporated in a longer string that has a lengthlimit imposed by the operating system. It depends on the system, but it's usuallybetween 91-108 characters. On Linux, the length is usually defined as 108, andyou can use the following command to check:

cat/usr/include/linux/un.h|grep"define UNIX_PATH_MAX"

Use the Cloud SQL Auth Proxy to connect to multiple instances

You can use one local Cloud SQL Auth Proxy client to connect to multiple Cloud SQLinstances. The way you do this depends on whether you are using Unix socketsor TCP.

Unix sockets

To connect the Cloud SQL Auth Proxy to multiple instances, you provide each instance connection name as an argument to the Cloud SQL Auth Proxy, in a space-separated list. The Cloud SQL Auth Proxy connects to each instance when it starts.

You connect to each instance using its socket, in the specified directory.

For example:

./cloud-sql-proxy--unix-socket/cloudsql\myProject:us-central1:myInstancemyProject:us-central1:myInstance2&psql-UmyUser-h/cloudsql/myProject:us-central1:myInstance2

TCP sockets

When you connect using TCP, you specify a port on your machine for the Cloud SQL Auth Proxy to listen on for each Cloud SQL instance. When connecting to multiple Cloud SQL instances, each port specified must be unique and available for use on your machine.

For example:

# Start the Cloud SQL Auth Proxy to connect to two different Cloud SQL instances# Give the Cloud SQL Auth Proxy a unique port on your machine to use for each Cloud SQL instance../cloud-sql-proxy"myProject:us-central1:myInstance?port=5432"\"myProject:us-central1:myInstance2?port=1234"# Connect to "myInstance" using port 5432 on your machine:psql-UmyUser-h127.0.0.1--port5432# Connect to "myInstance2" using port 1234 on your machine:psql-UmyUser-h127.0.0.1--port1234

Troubleshoot Cloud SQL Auth Proxy connections

The Cloud SQL Auth Proxy Docker image is based on a specific version of the Cloud SQL Auth Proxy.When a new version of the Cloud SQL Auth Proxy becomes available, pull the newversion of the Cloud SQL Auth Proxy Docker image to keep your environment up to date. Youcan see the current version of the Cloud SQL Auth Proxy by checking theCloud SQL Auth Proxy GitHub releases page.

If you are having trouble connecting to your Cloud SQL instance usingthe Cloud SQL Auth Proxy, here are a few things to try to find what's causing theproblem.

What's next

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-07-16 UTC.