0
0
GcpHow-ToBeginner · 4 min read

How to Connect Cloud Function to Cloud SQL in GCP

To connect a Cloud Function to Cloud SQL, use the Cloud SQL Auth proxy by specifying the instance connection name in the function's environment variables and configure the function to use the proxy socket. This allows secure, authorized access without exposing database credentials directly.
📐

Syntax

To connect a Cloud Function to Cloud SQL, you need to set the INSTANCE_CONNECTION_NAME environment variable with your Cloud SQL instance's connection name. Then, in your function code, connect to the database using a Unix socket path that includes this connection name.

Example connection string parts:

  • INSTANCE_CONNECTION_NAME: Your Cloud SQL instance connection name (project:region:instance)
  • Unix socket path: /cloudsql/INSTANCE_CONNECTION_NAME
  • Database user and password: Use Cloud Secret Manager or environment variables securely
bash and javascript
export INSTANCE_CONNECTION_NAME="project:region:instance"

# In your Cloud Function environment variables, set INSTANCE_CONNECTION_NAME

# In code (Node.js example):
const socketPath = `/cloudsql/${process.env.INSTANCE_CONNECTION_NAME}`;
const connection = mysql.createConnection({
  user: 'db_user',
  password: 'db_password',
  database: 'db_name',
  socketPath: socketPath
});
💻

Example

This example shows a Node.js Cloud Function connecting to a MySQL Cloud SQL instance using the Cloud SQL Auth proxy socket.

javascript
const mysql = require('mysql');

const connection = mysql.createConnection({
  user: process.env.DB_USER,
  password: process.env.DB_PASS,
  database: process.env.DB_NAME,
  socketPath: `/cloudsql/${process.env.INSTANCE_CONNECTION_NAME}`
});

exports.helloCloudSQL = (req, res) => {
  connection.query('SELECT NOW() AS now', (err, results) => {
    if (err) {
      res.status(500).send('Database error: ' + err.message);
      return;
    }
    res.status(200).send('Current time from Cloud SQL: ' + results[0].now);
  });
};
Output
Current time from Cloud SQL: 2024-06-01 12:34:56
⚠️

Common Pitfalls

  • Not setting the INSTANCE_CONNECTION_NAME environment variable correctly causes connection failures.
  • Forgetting to enable the Cloud SQL Admin API or assign the correct IAM roles to the Cloud Function service account blocks access.
  • Using public IP instead of the Cloud SQL Auth proxy socket reduces security and may require additional network setup.
  • Hardcoding database credentials in code instead of using environment variables or Secret Manager risks security leaks.
javascript
/* Wrong way: Hardcoding credentials and using IP address */
const connection = mysql.createConnection({
  host: '34.123.45.67', // Public IP
  user: 'root',
  password: 'password123',
  database: 'mydb'
});

/* Right way: Using socket and environment variables */
const connection = mysql.createConnection({
  user: process.env.DB_USER,
  password: process.env.DB_PASS,
  database: process.env.DB_NAME,
  socketPath: `/cloudsql/${process.env.INSTANCE_CONNECTION_NAME}`
});
📊

Quick Reference

  • Set INSTANCE_CONNECTION_NAME in Cloud Function environment variables.
  • Use Unix socket path /cloudsql/INSTANCE_CONNECTION_NAME in your code.
  • Securely manage DB credentials with environment variables or Secret Manager.
  • Ensure Cloud SQL Admin API is enabled and Cloud Function has proper IAM roles.
  • Deploy Cloud Function with the Cloud SQL instance in the same region for best performance.

Key Takeaways

Always use the Cloud SQL Auth proxy socket path to connect Cloud Functions securely to Cloud SQL.
Set the INSTANCE_CONNECTION_NAME environment variable with your Cloud SQL instance connection name.
Manage database credentials securely using environment variables or Secret Manager, never hardcode them.
Enable Cloud SQL Admin API and assign correct IAM roles to your Cloud Function service account.
Keep Cloud Function and Cloud SQL instance in the same region to reduce latency.