Connecting using the Cloud SQL Proxy

For information about connecting a sqlcmd client to a Cloud SQL instance using public IP, see Connecting sqlcmd Client Using IP Addresses.

For more information about how the proxy works, see About the Cloud SQL Proxy.

Before you begin

Before you can connect a sqlcmd to a Cloud SQL instance, you must have:

Install the Cloud SQL Proxy

Linux 64-bit

  1. Download the proxy:
    wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O cloud_sql_proxy
    
  2. Make the proxy executable:
    chmod +x cloud_sql_proxy
    

Linux 32-bit

  1. Download the proxy:
    wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.386 -O cloud_sql_proxy
    
  2. Make the proxy executable:
    chmod +x cloud_sql_proxy
    

macOS 64-bit

  1. Download the proxy:
    curl -o cloud_sql_proxy https://dl.google.com/cloudsql/cloud_sql_proxy.darwin.amd64
    
  2. Make the proxy executable:
    chmod +x cloud_sql_proxy
    

macOS 32-bit

  1. Download the proxy:
    curl -o cloud_sql_proxy https://dl.google.com/cloudsql/cloud_sql_proxy.darwin.386
    
  2. Make the proxy executable:
    chmod +x cloud_sql_proxy
    

Windows 64-bit

Right-click https://dl.google.com/cloudsql/cloud_sql_proxy_x64.exe and select Save Link As to download the proxy. Rename the file to cloud_sql_proxy.exe.

Windows 32-bit

Right-click https://dl.google.com/cloudsql/cloud_sql_proxy_x86.exe and select Save Link As to download the proxy. Rename the file to cloud_sql_proxy.exe.

Docker proxy image

For convenience, the Cloud SQL team maintains several container images that contain the Cloud SQL Proxy for use by our customers. For more information about these images, see the Cloud SQL Proxy repo on GitHub. You can pull the latest image to your local machine using Docker with the following command:
docker pull gcr.io/cloudsql-docker/gce-proxy:1.19.1

Other OS

For other operating systems not included here, you can compile the proxy from source.

Create a Service Account

  1. Go to the Service accounts page of the Google Cloud Console.

    Go to the Service accounts page

  2. Select the project that contains your Cloud SQL instance.
  3. Click Create service account.
  4. In the Create service account dialog, provide a descriptive name for the service account.
  5. For Role, select one of the following roles:
    • Cloud SQL > Cloud SQL Client
    • Cloud SQL > Cloud SQL Editor
    • Cloud SQL > Cloud SQL Admin
  6. Change the Service account ID to a unique, recognizable value.
  7. Click Furnish a new private key and confirm that the key type is JSON.
  8. Click Create.

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

Start the Cloud SQL Proxy

You can start the proxy using TCP sockets or the Docker proxy image.

TCP sockets

  1. Copy your instance connection name from the Instance details page.

    For example: myproject:myregion:myinstance.

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

    Some possible proxy invocation strings:

    • Using Cloud SDK authentication:
      ./cloud_sql_proxy -instances=<INSTANCE_CONNECTION_NAME>=tcp:1433
      
      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 -instances=<INSTANCE_CONNECTION_NAME>=tcp:1433 \
                        -credential_file=<PATH_TO_KEY_FILE> &
      

    For more information about proxy options, see Options for authenticating the proxy and Options for specifying instances.

Docker proxy image

To run the Cloud SQL Proxy in a Docker container, use the Proxy Docker image available from the Google Container Registry.

You can start the proxy using either TCP sockets or Unix sockets, with the commands shown below.

Depending on your language and environment, you can start the 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

docker run -d \\
  -v PATH_TO_KEY_FILE:/config \\
  -p 127.0.0.1:1433:1433 \\
  gcr.io/cloudsql-docker/gce-proxy:1.19.1 /cloud_sql_proxy \\
  -instances=INSTANCE_CONNECTION_NAME=tcp:0.0.0.0:1433 -credential_file=/config

If you are using the credentials provided by your Compute Engine instance, do not include the credential_file parameter and the -v PATH_TO_KEY_FILE:/config line.

Always specify 127.0.0.1 prefix in -p so that the 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

docker run -d -v /cloudsql:/cloudsql \\
  -v PATH_TO_KEY_FILE:/config \\
  gcr.io/cloudsql-docker/gce-proxy:1.19.1 /cloud_sql_proxy -dir=/cloudsql \\
  -instances=INSTANCE_CONNECTION_NAME -credential_file=/config

If you are using the credentials provided by your Compute Engine instance, do not include the credential_file parameter and the -v PATH_TO_KEY_FILE:/config 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 use Compute Engine metadata to dynamically determine the instances to connect to. Learn more about the proxy parameters.

Connect to the Cloud SQL Proxy

The connection string you use depends on whether you started the proxy using a TCP socket or or Docker.

TCP sockets

  1. Start the sqlcmd client:
    sqlcmd -S tcp:127.0.0.1,1433 -U <USER_NAME> -P <PASSWORD>
    

    When you connect using TCP sockets, the proxy is accessed through 127.0.0.1.

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

Need help? For help troubleshooting the proxy, see Troubleshooting Cloud SQL Proxy connections. Or, see our Cloud SQL Support page.

Language-specific information and examples

You can connect to the proxy from any language that enables you to connect to a TCP socket. Below are a few sample proxy invocation and connection statements to help you understand how they work together in your application.

Connecting with TCP

Proxy invocation statement:

./cloud_sql_proxy -instances=[INSTANCE_CONNECTION_NAME]=tcp:1433 &

Python

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

# Remember - storing secrets in plaintext is potentially unsafe. Consider using
# something like https://cloud.google.com/secret-manager/docs/overview to help keep
# secrets secret.
db_user = os.environ["DB_USER"]
db_pass = os.environ["DB_PASS"]
db_name = os.environ["DB_NAME"]
db_host = os.environ["DB_HOST"]

# Extract host and port from environment variable DB_HOST
host_args = db_host.split(":")
db_hostname, db_port = host_args[0], int(host_args[1])

# SQL Server drivers don't account for this
if db_hostname == "localhost":
    db_hostname = "127.0.0.1"

# The SQLAlchemy engine will help manage interactions, including automatically
# managing a pool of connections to your database
pool = sqlalchemy.create_engine(
    # Equivalent URL:
    # mssql+pyodbc://<db_user>:<db_pass>@/<host>:<port>/<db_name>?driver=ODBC+Driver+17+for+SQL+Server
    sqlalchemy.engine.url.URL(
        "mssql+pyodbc",
        username=db_user,
        password=db_pass,
        database=db_name,
        host=db_hostname,
        port=db_port,
        query={"driver": "ODBC Driver 17 for SQL Server"},
    ),
    **db_config
)

Java

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

// The configuration object specifies behaviors for the connection pool.
HikariConfig config = new HikariConfig();

// The following is equivalent to setting the config options below:
// jdbc:sqlserver://;user=<DB_USER>;password=<DB_PASS>;databaseName=<DB_NAME>;
// socketFactoryClass=com.google.cloud.sql.sqlserver.SocketFactory;
// socketFactoryConstructorArg=<CLOUD_SQL_CONNECTION_NAME>

// 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
    .setDataSourceClassName("com.microsoft.sqlserver.jdbc.SQLServerDataSource");
config.setUsername(DB_USER); // e.g. "root", "sqlserver"
config.setPassword(DB_PASS); // e.g. "my-password"
config.addDataSourceProperty("databaseName", DB_NAME);

// 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("socketFactoryClass",
    "com.google.cloud.sql.sqlserver.SocketFactory");
config.addDataSourceProperty("socketFactoryConstructorArg", CLOUD_SQL_CONNECTION_NAME);

// ... Specify additional connection properties here.

// ...

// Initialize the connection pool using the configuration object.
DataSource pool = new HikariDataSource(config);

Node.js

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

const createPool = async () => {
  const config = {pool: {}};
  config.user = process.env.DB_USER; // e.g. 'my-db-user'
  config.password = process.env.DB_PASS; // e.g. 'my-db-password'
  config.database = process.env.DB_NAME; // e.g. 'my-database'
  // set the server to '172.17.0.1' when connecting from App Engine Flex
  config.server = process.env.DEPLOYED ? '172.17.0.1' : '127.0.0.1';
  config.port = 1433;

  // ...
  return await mssql.connect(config);
};

Go

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

var (
	dbUser    = mustGetenv("DB_USER")     // e.g. 'my-db-user'
	dbPwd     = mustGetenv("DB_PASS")     // e.g. 'my-db-password'
	dbTcpHost = mustGetenv("DB_TCP_HOST") // e.g. '127.0.0.1' ('172.17.0.1' if deployed to GAE Flex)
	dbPort    = mustGetenv("DB_PORT")     // e.g. '1433'
	dbName    = mustGetenv("DB_NAME")     // e.g. 'my-database'
)

var dbURI string
dbURI = fmt.Sprintf("server=%s;user id=%s;password=%s;port=%s;database=%s;", dbTcpHost, dbUser, dbPwd, dbPort, dbName)

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

// ...

return dbPool, nil

C#

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

            // Equivalent connection string:
            // "User Id=<DB_USER>;Password=<DB_PASS>;Server=<DB_HOST>;Database=<DB_NAME>;"
            var connectionString = new SqlConnectionStringBuilder()
            {
                // Remember - storing secrets in plaintext is potentially unsafe. Consider using
                // something like https://cloud.google.com/secret-manager/docs/overview to help keep
                // secrets secret.
                DataSource = Environment.GetEnvironmentVariable("DB_HOST"),     // e.g. '127.0.0.1'
                // Set Host to 'cloudsql' when deploying to App Engine Flexible environment
                UserID = Environment.GetEnvironmentVariable("DB_USER"),         // e.g. 'my-db-user'
                Password = Environment.GetEnvironmentVariable("DB_PASS"),       // e.g. 'my-db-password'
                InitialCatalog = Environment.GetEnvironmentVariable("DB_NAME"), // e.g. 'my-database'

                // The Cloud SQL proxy provides encryption between the proxy and instance
                Encrypt = false,
            };
            connectionString.Pooling = true;
            // ...
            DbConnection connection =
                new SqlConnection(connectionString.ConnectionString);

Ruby

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

development:
  adapter: sqlserver
  # Configure additional properties here.
  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("DB_HOST") { "127.0.0.1" }%> # '172.17.0.1' if deployed to GAE Flex
  port: <%= ENV.fetch("DB_PORT") { 1433 }%> 

PHP

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

// $username = 'your_db_user';
// $password = 'yoursupersecretpassword';
// $db_name = 'your_db_name';
// $host = "127.0.0.1";

$dsn = sprintf('sqlsrv:server=%s;Database=%s', $host, $db_name);

// Connect to the database.
// Here we set the connection timeout to five seconds and ask PDO to
// throw an exception if any errors occur.
$conn = new PDO($dsn, $username, $password, [
    PDO::ATTR_TIMEOUT => 5,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);

What's next