Connecting to Cloud SQL from External Applications

This page describes how to connect to Google Cloud SQL from an application running outside of the Google Cloud Platform using the standard MySQL protocol, and manage IP access to your instance.

For information about the various options for connecting to Cloud SQL, see Connection Options for External Applications.

Before you start

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

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

Connecting from an external application using the proxy

1. Enable the API

  • Enable the Cloud SQL Administration 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
      
    2. Rename the proxy to use the standard filename:
      mv cloud_sql_proxy.linux.amd64 cloud_sql_proxy
      
    3. 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
      
    2. Rename the proxy to use the standard filename:
      mv cloud_sql_proxy.linux.386 cloud_sql_proxy
      
    3. Make the proxy executable:
      chmod +x cloud_sql_proxy
      

    OS X 64-bit

    1. Download the proxy:
      wget https://dl.google.com/cloudsql/cloud_sql_proxy.darwin.amd64
      
    2. Rename the proxy to use the standard filename:
      mv cloud_sql_proxy.darwin.amd64 cloud_sql_proxy
      
    3. Make the proxy executable:
      chmod +x cloud_sql_proxy
      

    OS X 32-bit

    1. Download the proxy:
      wget https://dl.google.com/cloudsql/cloud_sql_proxy.darwin.386
      
    2. Rename the proxy to use the standard filename:
      mv cloud_sql_proxy.darwin.386 cloud_sql_proxy
      
    3. 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, renaming it 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, renaming it to cloud_sql_proxy.exe.
    If your operating system is not 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 Cloud SQL Service accounts page of the Google Cloud Platform Console.

      Go to the Service accounts page

    2. If needed, 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. Change the Service account ID to a shorter value if needed.
    6. Click Furnish a new private key.
    7. The default key type is JSON, the correct value.
    8. Click Create.

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

      By default, the new service account has Editor privileges in your project.

    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. Unix sockets are not supported for applications written in the Java programming language or for the Windows environment.

    TCP sockets

    1. Copy your instance connection name from the Instance details page.
    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
      • 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>.

    Language-specific information

    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. The invocation statements 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.

    Go:

    You can use the Cloud SQL Proxy as a library; in this case you do not need to explicitly start the proxy as its own process. For more information, see the Cloud SQL Proxy Github page.

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

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

    Connection statement:

    const dsn = "root@unix(/cloudsql/<INSTANCE_CONNECTION_NAME>)/"
    db, err := sql.Open("mysql", dsn)
    

    Python:

    MySQLdb & TCP

    Invoke the proxy:

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

    Connection statement:

    cnx = mysql.connector.connect(user='scott', password='tiger',
                                  host='127.0.0.1',
                                  database='employees')
    

    MySQLdb & Unix

    Invoke the proxy:

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

    Connection statement:

    db = MySQLdb.connect(unix_socket='/cloudsql/' + <INSTANCE_CONNECTION_NAME>, db='guestbook', user='root', charset='utf8')
    

    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://USER:PASSWORD@127.0.0.1/DATABASE')
    

    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://USER:PASSWORD@/DATABASE?unix_socket=/cloudsql/<INSTANCE_CONNECTION_NAME>')
    

    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 proxy, but the easiest way to connect to a Second Generation instance without whitelisting IP addresses is to use the MySQL socket factory.

    The MySQL socket factory provides an alternative to the client-side proxy software, and requires the Cloud SQL API to be enabled, just as the proxy does. It authenticates with Cloud SDK credentials, so the Cloud SDK must be installed and authenticated. For more information, see the MySQL socket factory GitHub page.

    Configuring access for IP connections

    You can grant any application access to a Google Cloud SQL instance by authorizing the 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.

    IP addresses for First Generation instances

    For First Generation instances, Google Cloud SQL supports 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 an 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 assign an IPv4 address to your instance. There is a small charge for the IP address any time your instance is off (deactivated).

    IP addresses for Second Generation instances:

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

    Console

    To grant access to IP addresses:

    1. Determine the IP address of your application. Learn more.
    2. Go to the Cloud SQL Instances page in the Google Cloud Platform Console.

      Go to the Cloud SQL Instances page

    3. Find the instance to which you want to grant access and click the instance name.
    4. 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. Select Access Control > IP address.
      2. Select Request IPv4 address.

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

    5. Authorize networks that can connect to the instance.
      1. Select Access Control > Authorization.
      2. In the Authorized networks section, click Add network and enter IP addresses to whitelist using CIDR notation.
      Screenshot of the add network button.
    6. Click Done when you have completed your entry.
    7. When you are done authorizing networks, click Save to update the instance.

    gcloud

    To grant access to IP addresses:

    1. Determine the IP address of your client machine. Learn more.
    2. Grant access to the IP address or a range that contains it:
      gcloud sql instances patch [INSTANCE_NAME] --authorized-networks [IP_ADDRESS_RANGE]
      
    3. If you haven't assigned the instance an IP address yet, do so now:
      gcloud sql instances patch [INSTANCE_NAME] --assign-ip
      
    4. Retrieve the IP address assigned:
      gcloud sql instances describe [INSTANCE_NAME]
      

      In the output, find the "ipAddress" field. This value is what you will use in your connection strings.

    cURL

    To grant access to IP addresses:

    1. Determine the IP address of your application. Learn more.
    2. List the existing authorized IP ranges.

      For more information the resources of an instance you can access with the API, see instance resource definition.

      ACCESS_TOKEN="$(gcloud beta auth application-default print-access-token)"
      curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
           --header 'Content-Type: application/json' \
           https://www.googleapis.com/sql/v1beta4/projects/[PROJECT-ID]/instances/[INSTANCE_NAME] \
           -X GET
      
    3. Assign a new IP range to the existing list of IP ranges.
      curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
           --header 'Content-Type: application/json' \
           https://www.googleapis.com/sql/v1beta4/projects/[PROJECT-ID]/instances/[INSTANCE_NAME] \
           --data '{"settings" : {"ipConfiguration" : {"ipv4Enabled" : true,  \
           "authorizedNetworks": [<EXISTING_IP_ENTRIES>, {"kind": "sql#aclEntry", "value": "<NEW_IP_ADDR>"} ] }}}' \
           -X PATCH
      

    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 App Engine applications running in the flexible environment, and 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 Cloud SQL Proxy provided by Second Generation instances.

    Testing your connection

    You can use the MySQL client to test your ability to connect from your local environment.

    1. Install the MySQL client, if you haven't already.
    2. Connect to your instance.

      If you are accessing Cloud SQL by using the proxy, use the following connection string:

      mysql -u [USER_NAME] -p -S /cloudsql/[INSTANCE_CONNECTION_NAME]
      
      

      If you are accessing Cloud SQL by using an IP address, use the following connection string:

      mysql --host=[INSTANCE-IP] --user=[USER_NAME] --password
      
    3. Run some SQL commands to test the proxy.
              CREATE DATABASE guestbook;
              USE guestbook;
      
              CREATE TABLE entries (guestName VARCHAR(255), content VARCHAR(255),
                  entryID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(entryID));
              INSERT INTO entries (guestName, content) values ("first guest", "hello world!");
      
              SELECT * FROM entries;
      

    Revoking IP access

    You can revoke the ability for an IP address to connect to your instance, or revoke all IP addresses.

    Console

    To revoke access for an IP address:

    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 Instance details page.
    3. Select Access Control > Authorization.
    4. In the Authorized networks section, click the delete icon Delete. next to each address that you want to remove.

    gcloud

    To revoke access for all IP addresses:

    gcloud sql instances patch [INSTANCE_NAME] --clear-authorized-networks

    You can revoke access for a specific address by listing the authorized addresses and patching the instance with all of the existing addresses except the one you want to remove.

    cURL

    To revoke access for all IP addresses:

    ACCESS_TOKEN="$(gcloud beta auth application-default print-access-token)"
    curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \
         --header 'Content-Type: application/json' \
         https://www.googleapis.com/sql/v1beta4/projects/[PROJECT-ID]/instances/[INSTANCE_NAME] \
         --data '{"settings" : {"ipConfiguration" : {"authorizedNetworks": [ ] }}}' \
         -X PATCH
    

    You can revoke access for a specific address by listing the authorized addresses and patching the instance with all of the existing addresses except the one you want to remove.

    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 determine its IP address. You can use a browser to determine your IP address (for example, search for What's My IP).
    • If the computer is behind a proxy, log in to the computer and use a tool or service like Proxy Test to determine its true IP address.

    What's next

    Send feedback about...

    Cloud SQL Documentation