简体   繁体   中英

Cloud Run: Connecting to Cloud SQL instances

I am unable to connect to a Cloud SQL instance when running an image on Cloud Run. Is this feature working yet?

I have successfully connected to the same SQL instance with Compute Engine.

Tried to connect to the Cloud SQL instance using a simple shell command:

mysql --host=$MYSQL_IP --user=$MYSQL_ROOT --password=$MYSQL_PASS -e "SHOW DATABASES"

Result is logged as such:

ERROR 2003 (HY000): Can't connect to MySQL server on ' .* . . ' (110)

This question was asked several months before Cloud Run reached GA (General Availability).

Cloud Run (fully-managed) now supports connecting to Cloud SQL instances (both MySQL and PostgreSQL) using the public IP address of the database.

gcloud run services update run-mysql \
    --add-cloudsql-instances [INSTANCE_CONNECTION_NAME] \
    --set-env-vars CLOUD_SQL_CONNECTION_NAME=[INSTANCE_CONNECTION_NAME],\
      DB_NAME=[MY_DB],DB_USER=[MY_DB_USER],DB_PASS=[MY_DB_PASS]

...where INSTANCE_CONNECTION_NAME is of the form PROJECT_ID:REGION:INSTANCE_ID (as returned by gcloud sql instances describe <INSTANCE-ID> | grep connectionName or available in the Overview section of the Cloud SQL instance in Cloud Console).

Note that the service account used by Cloud Run to authorize your connections to Cloud SQL must have the correct IAM permissions which is will require some configuration if the DB instance and the Cloud Run services are not part of the same project.


The above takes care of connectivity between Cloud Run and Cloud SQL. Having your application actually talk to the Cloud SQL instance requires connecting from your Cloud Run service using the Unix domain socket located at /cloudsql/INSTANCE_CONNECTION_NAME (these connections are automatically encrypted btw).

Different languages and different database drivers will use different ways to connect to the Cloud SQL instance. This link has more details.

See also How to securely connect to Cloud SQL from Cloud Run?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM