SexyMF
SexyMF

Reputation: 11155

Connecting from google cloud run to google cloud (mysql) using .net core

I have a .net core app installed as a docker on google cloud run, this app that needs to be connected to cloud sql (mysql).

When using the private ip address it, it's not working.
When using public IP, it's working, but It's not a good solution for production.

this is my connection string:

"ConnectionString": "server=10.4.16.6;database=mydb;user=root;pwd=mypwd"

When I create the app, Im able to select the database i need to connect to:

enter image description here

But this is not helping to connect.
The relevant docs are explaining how to do it for python and java explictly.

Upvotes: 1

Views: 1545

Answers (2)

Peter Scriven
Peter Scriven

Reputation: 11

You can create the Cloud Run app from the console (and select the Cloud SQL Connection) or from the gcloud command line and specify

--add-cloudsql-instances <INSTANCE-NAME> --set-env-vars INSTANCE-CONNECTION-NAME="INSTANCE_CONNECTION_NAME"

These settings automatically enable and configures the Cloud SQL proxy. You can connect to the proxy, from your asp.net Core app, using the unix domain socket using the format: /cloudsql/INSTANCE_CONNECTION_NAME.

I used the following connection string in my appsettings.json and it worked for me:

"Server=/cloudsql/INSTANCE_CONNECTION_NAME;Database=DB_NAME;Uid=USER_NAME;Pwd=PASSWORD;Protocol=unix"

NB. Make sure you have given the service account that your Cloud Run app is running under Cloud SQL Client role in IAM

Upvotes: 1

Kunal Deo
Kunal Deo

Reputation: 2298

If you do not want to use public IP then you would need to rely on service account to connect to Cloud SQL. However, .net MySQL driver has no understanding of GCP IAM and Service accounts. So you will need to use a proxy called Cloud SQL Proxy. Cloud SQL Proxy understands IAM and Service accounts.

The flow will basically look like this:

Your app -> Regular MySQL Port -> Cloud SQL Proxy(Installed in the app's network or locally) -> CloudSQL

You will need to do the following:

  1. Create a service account
  2. Assign the role of Cloud SQL Client to the created service account
  3. Download the service account key in the json format
  4. Set env variable GOOGLE_APPLICATION_CREDENTIALS=C:\Downloaded.json
  5. Download Cloud SQL Proxy
  6. Run it `cloud_sql_proxy -instances=projectname:regioname:instanceid=tcp:3306
  7. At this point you MySQL proxy ready to accept connections at 3306, modify the connection string to take localhost or wherever you installed the Cloud SQL Proxy.

Learn more at About the Cloud SQL Proxy

Upvotes: 1

Related Questions