Using Cloud SQL

This page shows how to connect to a Cloud SQL instance from an App Engine application in the flexible environment, and how to read and write to Cloud SQL. Cloud SQL is a MySQL database that lives in Google's cloud.

To learn more about Google Cloud SQL, see the Google Cloud SQL documentation. For information on Cloud SQL billing plans and limits, see the Cloud SQL Pricing page. App Engine applications are also subject to the App Engine quotas.

Before you begin

  1. Select or create a Cloud Platform project.

    Go to the Projects page

  2. Enable the Cloud SQL Administration API.

    Enable the API

  3. Install and initialize the Cloud SDK.

Creating an instance and setting the password

To create an instance and set the password for the root user:

  1. Create a Cloud SQL Second Generation instance.

  2. If you haven't already, set the password for the MySQL root user on your Cloud SQL instance. For example, in the command line:

    gcloud sql instances set-root-password [YOUR_INSTANCE_NAME] --password [YOUR_INSTANCE_ROOT_PASSWORD]
    

Granting access to App Engine

If your App Engine application and Cloud SQL instance are in different Cloud Platform Console projects, you must use a service account to allow your App Engine application access to Cloud SQL.

This service account represents your App Engine application and is created by default when you create a Cloud Platform Console project.

  1. If your App Engine application is in the same Google Cloud Platform project as your Cloud SQL instance, proceed to Setting up your local environment. Otherwise, proceed to the next step.
  2. Identify the service account associated with your App Engine application. The default App Engine service account is named [PROJECT-ID]@appspot.gserviceaccount.com.

    You can verify the App Engine service account on the IAM Permissions page. Ensure that you select the Cloud Platform Console project for your App Engine application, not your Cloud SQL instance.

    Go to the IAM Permissions page

  3. Go to the IAM & Admin Projects page in the Google Cloud Platform Console.

    Go to the IAM & Admin Projects page

  4. Select the project that contains the Cloud SQL instance.
  5. Search for the service account name.
  6. If the service account is already there with the Editor role, you can proceed to Setting up your local environment.
  7. Otherwise, add the service account by clicking Add member.
  8. In the Add members dialog, provide the name of the service account and select Project > Editor for the role.
  9. Click Add.

    You should now see the service account listed with the Editor role.

Setting up your local environment

Once deployed, your application uses the Cloud SQL Proxy that is built in to the App Engine flexible environment to communicate with your Cloud SQL instance. However, to test your application locally, you must install and use a local copy of the Cloud SQL Proxy in your development environment.

To perform basic administrative tasks on your Cloud SQL instance, you can use the MySQL Client.

  1. Install the Cloud SQL proxy:

    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:
      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
      

    OS X 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, 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.

  2. Run the proxy:

    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.

  3. To use MySQL Client, you can install a local copy of MySQL Client and connect either by using the proxy or IP Addresses.

    For more information, see Connecting MySQL Client Using the Cloud SQL Proxy and Connecting MySQL Client Using IP Addresses.

Creating a user and managing user access

Use the MySQL Client command line tools or the MySQL Client built into Cloud Shell to create a user.

  1. Create a user:

    CREATE USER '[USER_NAME]'@'%' IDENTIFIED BY '[PASSWORD]';
    
  2. Grant the user access to the database:

    GRANT ALL ON *.* TO '[USER_NAME]'@'%';
    

Setting connection strings and adding a library

  1. To allow your app to connect to your Cloud SQL instance through the Cloud SQL Proxy for local testing, set the related connection string environment variable.

    For example, for the provided code sample:

    export MYSQL_USER=[YOUR_USER]
    export MYSQL_PASSWORD=[YOUR_PASSWORD]
    export MYSQL_DATABASE=[YOUR_DATABASE]
    export MYSQL_SOCKET_PATH=[YOUR_SOCKET_PATH]
    npm install
    

    These environment variables are used to create the connection:

    var config = {
      user: process.env.MYSQL_USER,
      password: process.env.MYSQL_PASSWORD,
      database: process.env.MYSQL_DATABASE
    };
    
    if (process.env.INSTANCE_CONNECTION_NAME) {
      config.socketPath = `/cloudsql/${process.env.INSTANCE_CONNECTION_NAME}`;
    }
    
    // Connect to the database
    const connection = mysql.createConnection(config);

  2. To allow your app to connect to your Cloud SQL instance when it is deployed, add the user, password, project id, region, and instance name variables from Cloud SQL to the related environment variables in the app.yaml file:

    env_variables:
      MYSQL_USER: YOUR_USER
      MYSQL_PASSWORD: YOUR_PASSWORD
      MYSQL_DATABASE: YOUR_DATABASE
      # e.g. my-awesome-project:us-central1:my-cloud-sql-instance
      INSTANCE_CONNECTION_NAME: YOUR_PROJECT_ID:YOUR_REGION:YOUR_INSTANCE_NAME
  3. Add a MySQL library to your application's package.json, for example:

    "dependencies": {
      "express": "^4.14.0",
      "mysql": "^2.11.1",
      "prompt": "^1.0.0"
    },

Running the sample code

The sample of server.js below creates a visitor log in a Cloud SQL instance.

Before running the sample, run createTables.js to create the tables you need and to ensure that the database is properly configured:

'use strict';

const mysql = require('mysql');
const prompt = require('prompt');

const SQL_STRING = `CREATE TABLE visits (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  timestamp DATETIME NULL,
  userIp VARCHAR(46) NULL,
  PRIMARY KEY (id)
);`;

/**
 * Create the "visits" table.
 *
 * @param {object} connection A mysql connection object.
 * @param {function} callback The callback function.
 */
function createTable (connection, callback) {
  connection.query(SQL_STRING, callback);
}

const FIELDS = ['user', 'password', 'database'];

/**
 * Ask the user for connection configuration and create a new connection.
 *
 * @param {function} callback The callback function.
 */
function getConnection (callback) {
  prompt.start();
  prompt.get(FIELDS, (err, config) => {
    if (err) {
      callback(err);
      return;
    }

    const user = encodeURIComponent(config.user);
    const password = encodeURIComponent(config.password);
    const database = encodeURIComponent(config.database);

    const uri = `mysql://${user}:${password}@127.0.0.1:3306/${database}`;
    callback(null, mysql.createConnection(uri));
  });
}

getConnection((err, connection) => {
  if (err) {
    console.error(err);
    return;
  }
  createTable(connection, (err, result) => {
    connection.end();
    if (err) {
      console.error(err);
      return;
    }
    console.log(result);
  });
});

The following sample writes visit information to Cloud SQL and then reads and returns the last ten visits:

'use strict';

const express = require('express');
const mysql = require('mysql');
const crypto = require('crypto');

const app = express();
app.enable('trust proxy');

var config = {
  user: process.env.MYSQL_USER,
  password: process.env.MYSQL_PASSWORD,
  database: process.env.MYSQL_DATABASE
};

if (process.env.INSTANCE_CONNECTION_NAME) {
  config.socketPath = `/cloudsql/${process.env.INSTANCE_CONNECTION_NAME}`;
}

// Connect to the database
const connection = mysql.createConnection(config);

/**
 * Insert a visit record into the database.
 *
 * @param {object} visit The visit record to insert.
 * @param {function} callback The callback function.
 */
function insertVisit (visit, callback) {
  connection.query('INSERT INTO `visits` SET ?', visit, (err) => {
    if (err) {
      callback(err);
      return;
    }
    callback();
  });
}

const SQL_STRING = `SELECT timestamp, userIp
FROM visits
ORDER BY timestamp DESC
LIMIT 10;`;

/**
 * Retrieve the latest 10 visit records from the database.
 *
 * @param {function} callback The callback function.
 */
function getVisits (callback) {
  connection.query(SQL_STRING, (err, results) => {
    if (err) {
      callback(err);
      return;
    }

    callback(null, results.map((visit) => `Time: ${visit.timestamp}, AddrHash: ${visit.userIp}`));
  });
}

app.get('/', (req, res, next) => {
  // Create a visit record to be stored in the database
  const visit = {
    timestamp: new Date(),
    // Store a hash of the visitor's ip address
    userIp: crypto.createHash('sha256').update(req.ip).digest('hex').substr(0, 7)
  };

  insertVisit(visit, (err, results) => {
    if (err) {
      next(err);
      return;
    }

    // Query the last 10 visits from the database.
    getVisits((err, visits) => {
      if (err) {
        next(err);
        return;
      }

      res
        .status(200)
        .set('Content-Type', 'text/plain')
        .send(`Last 10 visits:\n${visits.join('\n')}`);
    });
  });
});

const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl+C to quit.');
});

Testing and Deploying

  1. To test your application locally:

    npm start
    

  2. After you test your application, deploy your project to App Engine:

    gcloud app deploy
    

Send feedback about...

App Engine flexible environment for Node.js docs