I have created an SQL instance. It is working. Then, I have uploaded the docker image for my Spring Boot app on Container Registry.
My goal is to run the app on Google Cloud Run, but in order for it to work, it has to connect to the database. Thus, when creating the service I give it the image and pass the env variables:
- spring.datasource.url (here I pass as value – jdbc:mysql://(public ip address for the sql instance)/(database name)?useSSL=false
- spring.datasource.username …
- spring.datasource.password …
Also, I make the connection to the cloud SQL instance in the advanced settings.
However, when I deploy it, it fails. The spring app is starting but then I get an communications link failure. I suppose it doesn’t find the database or it has to do something with the persmissions.
I am new to Google Cloud and I want some help, please. How could I solve this? Or maybe I am doing something wrong?
Advertisement
Answer
A MySQL instance of Cloud SQL can have a Public IP and a Private IP.
For connecting the Cloud Run application from an instance using the Public IP one needs to use the Cloud SQL Auth Proxy through the Unix sockets. You can follow this document to know the steps.
For connecting the Cloud Run application from an instance using the Private IP one needs to use the Serverless VPC Access connector. You follow this document to know the steps.
You have created an image for the Spring Boot Application and deployed it in Cloud Run and passed the environment variables. In the spring.datasource.url you have used the Public IP directly which will not work as the recommended way to connect using the Public IP is using the CloudSQL Auth Proxy through Unix socket path.
I would suggest you to use the jdbcUrl mentioned here as the spring.datasource.url
which looks like this-
jdbc:mysql:///<DATABASE_NAME>?cloudSqlInstance=<INSTANCE_CONNECTION_NAME>&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=<MYSQL_USER_NAME>&password=<MYSQL_USER_PASSWORD>&useSSL=false
Where,
<DATABASE_NAME> = Your database name in the MySQL instance <INSTANCE_CONNECTION_NAME> = Connection name of the MySQL instance of Cloud SQL (can be found in the instance overview page in the Cloud Console) which follows a certain pattern i.e. <project-id : region : instance-id>. <MYSQL_USER_NAME> = Username for the MySQL instance <MYSQL_USER_PASSWORD> = Password for the above username
While using the above spring.datasource.url
you don’t have to specify the spring.database.username
and spring.datasource.password
property separately as both are mentioned in the URL.