Connecting Overview

This page provides a summary of options for connecting to your Cloud SQL instance.

Overview

To connect to your Cloud SQL instance, consider:

  • How to connect - which network path you use to reach your instance:
    • An internal, VPC-only (Private) IP address.
    • An external, internet-accessible (Public) IP address.

  • How to authorize - which connections are authorized and allowed to connect to your Cloud SQL instance:
    • Cloud SQL Proxy and Cloud SQL language connectors - these provide access based on IAM.
    • Self-managed SSL/TLS certificates - these only allow connections based on specific public keys.
    • Authorized networks - a list of IP addresses allowed to connect.

  • How to authenticate - the method to login to your database.
    • Native database authentication - login with a username/password set in the database engine.

Use the information below to decide which connection, authorization and authentication options work best for you.

Before you start

Granting access to an application does not automatically enable a database user account to connect to the instance. Before you can connect to an instance, you must have a database user account you can connect with. For new instances, this means you must have configured the default user account. Learn more.

Connection options

Private IP

A private IP is an IPv4 or IPv6 address that is accessible on a Virtual Private Cloud (VPC). You can use this address to connect from other resources with access to the VPC; connections over private IP typically provide lower latency and limited attack vectors, as they don't require traversing the internet.

Connections to a Cloud SQL instance using a private IP address are automatically authorized for RFC 1918 address ranges. This way, all private clients can access the database without going through the proxy. Non-RFC 1918 address ranges must be configured as authorized networks.

Optionally, it is possible to require all connections use either the Cloud SQL proxy or self-managed SSL certificates.

Configuring your instance with a private IP is preferred when connecting from a client on a resource with access to a VPC. For more information about what resources can use private IP, see Requirements for Private IP. For instructions on adding a private IP to your instance, see Configuring Private IP Connectivity.

Public IP

A public IP is an IPv4 or IPv6 address that is available externally on the public internet. This address can receive connections from devices both inside and outside of Google's network, including from locations like your home or office.

In order to help keep your instance secure, any connections to a Cloud SQL instance using a public IP must be authorized using either the Cloud SQL proxy or authorized networks.

Configuring your instance with a public IP is best when connecting from a client that doesn't meet the requirements for a VPC.

For instructions about adding a public IP to your instance, see Configuring Public IP Connectivity.

Authorization options

Cloud SQL proxy

The Cloud SQL proxy allows you to authorize and secure your connections using Identity and Access Management (IAM) permissions. The proxy validates connections using credentials for a user or service account, and wrapping the connection in a SSL/TLS layer that is authorized for a Cloud SQL instance. For more details about how the Cloud SQL proxy works, see About the Cloud SQL Proxy.

Using the Cloud SQL proxy is the recommended method for authenticating connections to a Cloud SQL instance, as it is the most secure method.

The client proxy is an open source library distributed as an executable binary. The client proxy acts as an intermediary server that listens for incoming connections, wraps them in SSL/TLS, and then passes them to a Cloud SQL instance.

Additionally, some languages have the option of using a client library. You can use these libraries directly from the language environment; they provide the same authentication as the proxy without requiring an external process. To get started, see the following pages:

Finally, some environments such as Cloud Run, Cloud Functions, and App Engine provide a mechanism that connects using the Cloud SQL Proxy. For instructions about connecting using these environments, see one of the following:

Self-managed SSL/TLS certificates

Instead of using the Cloud SQL Proxy to encrypt your connections, it is possible to set up client/server SSL/TLS certificates that are specific to a Cloud SQL instance. These certificates are used to both validate the client and server to each other and encrypt connections between them.

It is strongly recommended to use self-managed SSL/TLS certificates to provide encryption when not using the Cloud SQL Proxy. Failing to do so means your data is being transmitted insecurely, and may be intercepted or inspected by a third-party.

To get started with self-managed SSL/TLS certificates, see Authorizing with SSL/TLS certificates.

Authorized networks

Unless using the Cloud SQL proxy, connections to the public IP address of an instance are only allowed if the connection come from from an authorized network. Authorized networks are IP addresses or ranges that the user has specified as having permission to connect.

To get started with authorized networks, see Authorizing with Authorized Networks.

Managing database connections

Database connections consume resources on the server and the connecting application. Always use good connection management practices to minimize your application's footprint and reduce the likelihood of exceeding Cloud SQL connection limits. For more information, see Managing database connections.

Authentication options

Authentication provides access control by verifying the identity of a user. For end users, authentication is achieved when the user enters credentials (a username and password). For applications, authentication is achieved when a user's credentials are assigned to a service account.

Cloud SQL uses the database's built-in authentication that authenticates using a username and password. For more information, see creating and managing SQL Server users.

Tools for connecting

The following table contains some options for connecting to Cloud SQL:

Connection option More information
Cloud SQL Proxy
gcloud command-line tool
Cloud SQL language connectors
Cloud Shell
Apps Script
Connect using third-party database administration tools
SQL Server Management Studio
SMSS Object Explorer
Visual Studio

Code samples

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

Connecting with TCP

Cloud SQL 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+pytds://<db_user>:<db_pass>@/<host>:<port>/<db_name>?driver=ODBC+Driver+17+for+SQL+Server
    sqlalchemy.engine.url.URL(
        "mssql+pytds",
        username=db_user,
        password=db_pass,
        database=db_name,
        host=db_hostname,
        port=db_port,
    ),
    **db_config
)

Java

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

// Note: For Java users, the Cloud SQL JDBC Socket Factory can provide authenticated connections
// which is preferred to using the Cloud SQL Proxy with Unix sockets.
// See https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory for details.

// 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);

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_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 plain text 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;
            // ...
            return 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';
// $dbName = 'your_db_name';
// $dbHost = "127.0.0.1";

// Connect using TCP
$dsn = sprintf('sqlsrv:server=%s;Database=%s', $dbHost, $dbName);

// Connect to the database
$conn = new PDO($dsn, $username, $password, $connConfig);

Troubleshooting

See the Connectivity section in the Troubleshooting page.

What's next