How to Connect to Cloud SQL on Google Cloud Platform
To connect to
Cloud SQL on Google Cloud, use the Cloud SQL Proxy or configure your client with the instance's IP and authorized networks. You can connect using standard database clients or programming libraries with the correct credentials and network access.Syntax
Connecting to Cloud SQL involves specifying the connection details such as the instance connection name, database user, password, and database name. You can connect using the Cloud SQL Proxy or directly via IP with authorized networks.
- Instance connection name: Unique identifier for your Cloud SQL instance.
- Database user: Username with access rights.
- Password: Password for the database user.
- Database name: The specific database to connect to.
- Connection method: Either
Cloud SQL Proxyor direct IP with authorized networks.
bash
./cloud_sql_proxy -instances="PROJECT_ID:REGION:INSTANCE_ID"=tcp:3306 mysql -u USERNAME -p -h 127.0.0.1 -P 3306 DATABASE_NAME
Example
This example shows how to connect to a Cloud SQL MySQL instance using the Cloud SQL Proxy and the MySQL client.
bash
# Start Cloud SQL Proxy ./cloud_sql_proxy -instances="my-project:us-central1:my-instance"=tcp:3306 & # Connect using MySQL client mysql -u myuser -p -h 127.0.0.1 -P 3306 mydatabase
Output
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 123
Server version: 8.0.28 MySQL Community Server - GPL
mysql>
Common Pitfalls
Common mistakes when connecting to Cloud SQL include:
- Not enabling the Cloud SQL Admin API.
- Failing to authorize your client IP in the instance's authorized networks.
- Using incorrect instance connection names or credentials.
- Not running the Cloud SQL Proxy when required.
- Firewall rules blocking the connection.
Always verify your network and credentials before connecting.
bash
## Wrong: Trying to connect directly without authorized network or proxy mysql -u myuser -p -h 35.123.45.67 mydatabase ## Right: Use Cloud SQL Proxy or add your IP to authorized networks ./cloud_sql_proxy -instances="my-project:us-central1:my-instance"=tcp:3306 & mysql -u myuser -p -h 127.0.0.1 -P 3306 mydatabase
Quick Reference
Tips for connecting to Cloud SQL:
- Use
Cloud SQL Proxyfor secure and easy connections. - Authorize your client IP in the Cloud SQL instance settings if connecting directly.
- Use correct instance connection name format:
project:region:instance. - Ensure your database user has proper permissions.
- Check firewall and network settings to allow traffic.
Key Takeaways
Use Cloud SQL Proxy for secure and simple connections to Cloud SQL instances.
Always authorize your client IP in Cloud SQL settings if connecting directly via IP.
Provide correct instance connection name and database credentials.
Enable Cloud SQL Admin API and check firewall rules before connecting.
Use standard database clients with the right host and port settings.