0
0
GcpHow-ToBeginner · 3 min read

How to Use Cloud SQL Proxy for Secure Database Connections

Use cloud_sql_proxy to securely connect to your Google Cloud SQL instance by running it with your instance connection name and authentication credentials. It creates a local socket or port that your application can use to connect as if the database was local.
📐

Syntax

The basic command to start Cloud SQL Proxy is:

  • ./cloud_sql_proxy -instances=<INSTANCE_CONNECTION_NAME>=tcp:<PORT>
  • INSTANCE_CONNECTION_NAME is your Cloud SQL instance's connection name, found in the Google Cloud Console.
  • PORT is the local port number where the proxy listens for connections.
  • You can also use Unix sockets instead of TCP ports by specifying =unix:<PATH>.
bash
./cloud_sql_proxy -instances=project:region:instance=tcp:5432
💻

Example

This example shows how to start Cloud SQL Proxy for a PostgreSQL instance and connect using psql client locally.

bash
./cloud_sql_proxy -instances=my-project:us-central1:my-instance=tcp:5432

# In another terminal, connect using psql
psql "host=127.0.0.1 port=5432 user=myuser dbname=mydb sslmode=disable"
Output
2024/06/01 12:00:00 Listening on 127.0.0.1:5432 for my-project:us-central1:my-instance psql (14.5) Type "help" for help. mydb=>
⚠️

Common Pitfalls

  • Not providing the correct instance connection name causes connection failure.
  • Forgetting to authenticate with Google Cloud (e.g., missing gcloud auth login) prevents proxy from starting.
  • Using a port already in use will cause the proxy to fail to bind.
  • Not disabling SSL in the client when connecting through proxy can cause errors; proxy handles encryption.
bash
# Wrong: missing instance name
./cloud_sql_proxy -instances=tcp:5432

# Right: include full instance connection name
./cloud_sql_proxy -instances=my-project:us-central1:my-instance=tcp:5432
📊

Quick Reference

OptionDescription
-instancesSpecify instance connection name and local endpoint (tcp or unix socket)
-dirDirectory for Unix socket files
-credential_filePath to service account JSON for authentication
-verboseEnable detailed logs
-helpShow help information

Key Takeaways

Always use the full instance connection name in the format project:region:instance.
Authenticate with Google Cloud before running the proxy using gcloud or service account keys.
Connect your application to the local port or socket created by the proxy as if the database is local.
Avoid port conflicts by choosing an unused local port for the proxy.
Cloud SQL Proxy handles secure connections, so disable SSL in your client when connecting through it.