Connecting to Cloud SQL from external applications

This page describes how to establish a connection to Cloud SQL from an application running outside of Google Cloud Platform.

For information about the various options for connecting to Cloud SQL, see Connection options for external applications. For information about configuring public IP, see Configuring public IP.

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.

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.

You can connect to a Cloud SQL instance using the following methods:

Connecting from an external application using the proxy

If you are setting up the Cloud SQL Proxy for a local test environment (not for production), you can use the Proxy Quickstart instead of these instructions.

If you are using the Java or Go programming languages, you have some alternatives to using the Cloud SQL Proxy. Learn more.

1. Enable the API

Enable the Cloud SQL Admin API.

Enable the API

2. Install the proxy client on your local machine

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.
If your operating system isn't included here, you can also compile the proxy from source.

3. Determine how you will authenticate the proxy

Learn more about proxy authentication options.

4. If required by your authentication method, create a service account

  1. Go to the Service accounts page of the Google Cloud Platform 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

    Alternatively, you can use the primitive Editor role by selecting Project > Editor, but the Editor role includes permissions across Google Cloud Platform.

    If you do not see these roles, your Google Cloud Platform user might not have the resourcemanager.projects.setIamPolicy permission. You can check your permissions by going to the IAM page in the Google Cloud Platform Console and searching for your user id.

  6. Change the Service account ID to a unique, easily 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.

5. Determine how you will specify your instances for the proxy

Learn more about proxy instance specification options.

6. Start the proxy

The options you pass to the proxy depend on the authentication and instance specification options you chose previously.

Depending on your language and environment, you can start the proxy using either TCP sockets or Unix sockets.

TCP sockets

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

    For example: myproject:us-central1:myinstance.

  2. 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.
  3. Start the proxy.

    Some possible proxy invocation strings:

    • Using Cloud SDK authentication:
      ./cloud_sql_proxy -instances=<INSTANCE_CONNECTION_NAME>=tcp:3306
      
      The specified port must not already be in use, for example, by a local database server.
    • Using a service account and explicit instance specification (recommended for production environments):
      ./cloud_sql_proxy -instances=<INSTANCE_CONNECTION_NAME>=tcp:3306 \
                        -credential_file=<PATH_TO_KEY_FILE> &
      

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

Unix sockets

  1. If you are using explicit instance specification, copy your instance connection name from the Instance details page.
  2. Create the directory where the proxy sockets will live:
    sudo mkdir /cloudsql; sudo chmod 777 /cloudsql
  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. Open a new terminal window and start the proxy.

    Some possible proxy invocation strings:

    • Using a service account and explicit instance specification (recommended for production environments):
      ./cloud_sql_proxy -dir=/cloudsql -instances=<INSTANCE_CONNECTION_NAME> \
                        -credential_file=<PATH_TO_KEY_FILE> &
    • Using Cloud SDK authentication and automatic instance discovery:
      ./cloud_sql_proxy -dir=/cloudsql &

    It is best to start the proxy in its own terminal so you can monitor its output without it mixing with the output from other programs.

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

7. Update your application to connect to Cloud SQL using the proxy

The exact code statement required to use the proxy to connect to your Cloud SQL instance depends on the language and framework you are using.

You connect to the proxy the same way you would to a TCP or Unix socket (depending on how you invoked the proxy):

TCP sockets

With TCP sockets, the proxy is available as local host:

127.0.0.1:3306

Unix sockets

With Unix sockets, the proxy is available using the following path:

PROXY_PATH/INSTANCE_CONNECTION_NAME;
Where PROXY_PATH is the path to the directory you set with the -dir option when you started the proxy. The examples in this documentation use /cloudsql. You can find the connection name of your instance on its Instance details page in the Google Cloud Platform Console, or use PROJECT-ID:REGION:INSTANCE_NAME.

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 Unix or TCP socket. Below are a few sample proxy invocation and connection statements to help you understand how they work together in your application.

Go

You can use the Cloud SQL Proxy with the Go programming language in two ways:

  1. Using the Go Proxy library
  2. Running the proxy as a companion process

Go Proxy library

The library provides the easiest way to connect to Cloud SQL from a Go program, because you do not need to explicitly start the proxy as its own process.

import (
    "github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/dialers/mysql"
)
...
cfg := mysql.Cfg(INSTANCE_CONNECTION_NAME, DATABASE_USER, PASSWORD)
cfg.DBName = DATABASE_NAME
db, err := mysql.DialCfg(cfg)

For more information, see the Cloud SQL Proxy GitHub page.

Companion process

You can also run the proxy as a companion process, and connect to it from your application.

The proxy invocation statements below use local Cloud SDK authentication for brevity; your invocation statement might vary, depending on how you are authenticating and how you are specifying your instances. See Options for authenticating the Cloud SQL Proxy.

TCP Sockets

Proxy invocation statement:

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

Connection statement:

import (
       "database/sql"
        _ "github.com/go-sql-driver/mysql"
)

dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s",
       DATABASE_USER,
       PASSWORD,
       "127.0.0.1:3306",
       DATABASE_NAME)
db, err := sql.Open("mysql", dsn)

Unix sockets

Proxy invocation statement:

./cloud_sql_proxy -instances=[INSTANCE_CONNECTION_NAME] -dir=/cloudsql &

Connection statement:

import (
       "database/sql"
        _ "github.com/go-sql-driver/mysql"
)

dsn := fmt.Sprintf("%s:%s@unix(/cloudsql/%s)/%s",
       DATABASE_USER,
       PASSWORD,
       INSTANCE_CONNECTION_NAME,
       DATABASE_NAME)
db, err := sql.Open("mysql", dsn)

Java

The Java programming language does not provide native support for Unix sockets. You can use TCP sockets or a library that provides Unix socket support with the Cloud SQL Proxy, but the easiest way to connect to a Second Generation instance without whitelisting IP addresses is to use the JDBC socket factory.

The JDBC socket factory provides an alternative to the client-side proxy software, and requires you to enable the Cloud SQL API, just as the Cloud SQL Proxy does. The socket factory provides the same level of encryption as the proxy, and authenticates with Cloud SDK credentials. You must install and authenticate the Cloud SDK before using the socket factory.

See Cloud SQL Socket Factory for JDBC drivers for code examples. Review the README for instructions.

PHP

PDO & TCP

Invoke the proxy:

./cloud_sql_proxy -instances=INSTANCE_CONNECTION_NAME=tcp:3306 &

The following examples connect to Cloud SQL using PHP Data Objects (PDO):

// Use a Data source name (DSN) to connect to Cloud SQL through the proxy
$dsn = 'mysql:host=127.0.0.1;port=3306;dbname=DATABASE_NAME';
// Instantiate your DB using the DSN, username, and password
$dbUser = 'DATABASE_USER';
$dbPass = 'PASSWORD';
$db = new PDO($dsn, $dbUser, $dbPass);

PDO & Unix sockets

Invoke the proxy:

./cloud_sql_proxy -instances=INSTANCE_CONNECTION_NAME -dir=/cloudsql &

The following examples connect to Cloud SQL using PDO:

// Use a Data source name (DSN) to connect to Cloud SQL through the proxy
$dsn = sprintf('mysql:unix_socket=/cloudsql/INSTANCE_CONNECTION_NAME;dbname=DATABASE_NAME';
// Instantiate your DB using the DSN, username, and password
$dbUser = 'DATABASE_USER';
$dbPass = 'PASSWORD';
$db = new PDO($dsn, $dbUser, $dbPass);

mysqli & TCP

Invoke the proxy:

./cloud_sql_proxy -instances=INSTANCE_CONNECTION_NAME=tcp:3306 &

The following examples connect to Cloud SQL using mysqli:

// Instantiate your DB using the database host, port, name, username, and password
$dbName = 'DATABASE_NAME';
$dbUser = 'DATABASE_USER';
$dbPass = 'PASSWORD';
$mysqli = new mysqli('127.0.0.1', $dbUser, $dbPass, $dbName, 3306);

mysqli & Unix Sockets

Invoke the proxy:

./cloud_sql_proxy -instances=INSTANCE_CONNECTION_NAME -dir=/cloudsql &

The following examples connect to Cloud SQL using mysqli:

// Instantiate your DB using the database name, socket, username, and password
$dbName = 'DATABASE_NAME';
$dbUser = 'DATABASE_USER';
$dbPass = 'PASSWORD';
$dbSocket = '/cloudsql/INSTANCE_CONNECTION_NAME';
$mysqli = new mysqli(null, $dbUser, $dbPass, $dbName, null, $dbSocket);

Python

The proxy invocation statements below use local Cloud SDK authentication for brevity; your invocation statement might vary, depending on how you are authenticating and how you are specifying your instances. Learn more.

PyMySQL & TCP

Invoke the proxy:

./cloud_sql_proxy -instances=INSTANCE_CONNECTION_NAME=tcp:3306 &

Connection statement:

import pymysql
connection = pymysql.connect(host='127.0.0.1',
                             user='DATABASE_USER',
                             password='PASSWORD',
                             db='DATABASE_NAME')

PyMySQL & Unix

Invoke the proxy:

./cloud_sql_proxy -instances=INSTANCE_CONNECTION_NAME -dir=/cloudsql &

Connection statement:

import pymysql
connection = pymysql.connect(unix_socket='/cloudsql/' + INSTANCE_CONNECTION_NAME,
                             user='DATABASE_USER',
                             password='PASSWORD',
                             db='DATABASE_NAME')

SQLAlchemy & TCP

Invoke the proxy:

./cloud_sql_proxy -instances=INSTANCE_CONNECTION_NAME=tcp:3306 &

Connection statement:

from sqlalchemy import create_engine
  engine = create_engine('mysql+pymysql://DATABASE_USER:PASSWORD@127.0.0.1/DATABASE_NAME')

SQLAlchemy & Unix

Invoke the proxy:

./cloud_sql_proxy -instances=INSTANCE_CONNECTION_NAME -dir=/cloudsql &

Connection statement:

from sqlalchemy import create_engine
engine = create_engine('mysql+pymysql://DATABASE_USER:PASSWORD@/DATABASE_NAME?unix_socket=/cloudsql/INSTANCE_CONNECTION_NAME')

Ruby

mysql2 & TCP

Invoke the proxy:

./cloud_sql_proxy -instances=INSTANCE_CONNECTION_NAME=tcp:3306 &

The following examples connect to Cloud SQL using the mysql2 RubyGem:

require "mysql2"
client = Mysql2::Client.new host: "127.0.0.1", port: 3306,
    database: "DATABASE_NAME", username: "DATABASE_USER",
    password: "PASSWORD"

mysql2 & Unix Sockets

Invoke the proxy:

./cloud_sql_proxy -instances=INSTANCE_CONNECTION_NAME -dir=/cloudsql &

The following examples connect to Cloud SQL using the mysql2 RubyGem:

require "mysql2"
client = Mysql2::Client.new socket: "/cloudsql/CONNECTION_NAME",
    database: "DATABASE_NAME", username: "DATABASE_USER",
    password: "PASSWORD"

Rails & TCP

Invoke the proxy:

./cloud_sql_proxy -instances=INSTANCE_CONNECTION_NAME=tcp:3306 &

In config/databases.yml, use the following configuration:

mysql_settings: &mysql_settings
  adapter: mysql2
  encoding: utf8
  pool: 5
  username: DATABASE_USER
  password: PASSWORD
  database: DATABASE_NAME
  host: 127.0.0.1:3306

Rails & Unix Sockets

Invoke the proxy:

./cloud_sql_proxy -instances=INSTANCE_CONNECTION_NAME -dir=/cloudsql &

In config/databases.yml, use the following configuration:

mysql_settings: &mysql_settings
  adapter: mysql2
  encoding: utf8
  pool: 5
  username: DATABASE_USER
  password: PASSWORD
  database: DATABASE_NAME
  socket: /cloudsql/INSTANCE_CONNECTION_NAME

Configuring access for public IP connections

You can grant any application access to a Cloud SQL instance by authorizing the public IP addresses that the application uses to connect.

You can not specify a private network (for example, 10.x.x.x) as an authorized network.

Public IP addresses for Second Generation instances:

  • IPv6: Second Generation instances do not support IPv6.
  • IPv4: Second Generation instances have a static IPv4 address automatically assigned. There is a small charge for the IP address any time your instance is off (deactivated).

Public IP addresses for First Generation instances:

For First Generation instances, Cloud SQL supports public IP connections over both IPv4 and IPv6 addresses. You can connect using either protocol, or both. However, you cannot mix the IP address versions in a single connection.

  • IPv6: Each First Generation instance has a static IPv6 address automatically assigned to it; you do not need to assign an IPv6 address to your instance.
  • IPv4: If you are connecting to your First Generation instance over IPv4, you must update your instance to have a public IPv4 address assigned to it. This IP address is static. There is a small charge for the IPv4 address any time your instance is off (stopped).

To configure access over IP connections:

Console

  1. Determine the IP address of your application. Learn more.
  2. Authorize your application's IP address to connect to your instance.

    For more information, see Adding an authorized address.

  3. If you are connecting to a First Generation instance over IPv4, assign an IPv4 address to the instance if you haven't done so already:
    1. Go to the Cloud SQL Instances page in the Google Cloud Platform Console.

      Go to the Cloud SQL Instances page

    2. Click the instance name to open its Overview page.
    3. Select the IP address tab.
    4. Click Request IPv4 address.

      Note that you are charged for an IPv4 address when the instance is off. For more information, see the pricing page.

  4. You can find the IP address assigned to your instance in its Instance details page. This is the value you need for your application's connection string.

gcloud

  1. Determine the IP address of your client machine. Learn more.
  2. Authorize your application's IP address to connect to your instance.

    For more information, see Adding an authorized address.

  3. If you are connecting to a First Generation instance, and you want to use IPv4, you must assign an IPv4 address to the instance:
    gcloud sql instances patch [INSTANCE_NAME] --assign-ip
    
  4. Retrieve the IP address for the instance:
    gcloud sql instances describe [INSTANCE_NAME]
    

    In the output, find the ipAddress field. This is the value you need for your application's connection string.

cURL

  1. Determine the IP address of your application. Learn more.
  2. Authorize your application's IP address to connect to your instance.

    For more information, see Adding an authorized address.

  3. If you are connecting to a First Generation instance, and you want to use IPv4, you must assign an IPv4 address to the instance:
    curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
           --header 'Content-Type: application/json' \
           --data '{"settings" : {"ipConfiguration" :
                                  {"ipv4Enabled" : "true"}}}' \
           -X PATCH \
           https://www.googleapis.com/sql/v1beta4/projects/[PROJECT-ID]/instances/[INSTANCE_NAME]
    
  4. Retrieve the IP address for the instance:
    gcloud auth login
    ACCESS_TOKEN="$(gcloud auth print-access-token)"
    curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
           -X GET \
           https://www.googleapis.com/sql/v1beta4/projects/[PROJECT-ID]/instances/[INSTANCE_NAME]
    

    Note the value for ipv6Address (First Generation instances only), or ipAddresses.ipAddress for IPv4. This is the value you need for your application's connection string.

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

Configuring access for applications with dynamically assigned IP addresses

Some applications need to connect to your Cloud SQL instance using a dynamically assigned, or ephemeral, IP address. This is the case for Platform as a Service (Paas) applications, among others.

The best solution for these applications is to use a Cloud SQL Second Generation instance, and connect by using the Cloud SQL Proxy. This solution provides the best access control for your instance.

If you cannot use a Second Generation instance, then you can either install your own proxy, or open up your firewall and apply SSL. But neither of these methods provide the security and control of the connectivity solutions provided by Second Generation instances.

Testing your connection

You can use the mysql client to test your ability to connect from your local environment. For more information, see Connecting the mysql client using IP addresses and Connecting the mysql client using the Cloud SQL Proxy.

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

Determining the IP address for your application

To determine the IP address of a computer running your application so you can authorize access to your Cloud SQL instance from that address, use one of the following options:

  • If the computer is not behind a proxy, log in to the computer and use this link to determine its IP address.
  • If the computer is behind a proxy, log in to the computer and use a tool or service like whatismyipaddress.com to determine its true IP address.

What's next

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

Send feedback about...

Cloud SQL for MySQL