spring-bootgoogle-cloud-platformjdbcgoogle-cloud-sqlunix-socket

How to get a connection between Google Cloud Run and Google Cloud SQL?


What I have: A Java11 Spring Boot application (embedded tomcat 9) with Hikari Pool (Grails 4) in a Docker Container based on eclipse-temurin:11-jre. What I need: My application needs a connection to a mysql database, I want to use google cloud sql mysql database. What my problem is: My application cannot establish a connection to the database when deployed to Google Cloud Run.

The base assumption that by defining Cloud SQL connections for my cloud run revision it magically adds a unix socket to my docker container disturbs me though as it's the only thing I don't understand.

Has anyone an idea on what to try or what to do? Maybe an explanation on how the socket connection is being created? My next and last try would be to add cloud-sql-proxy plus iam credentials to my docker container but this seems to be against everything being recommended by the documentation. There must be something I oversee.

I followed the guide (https://cloud.google.com/sql/docs/mysql/connect-run) and red everything I could get my hands on. What I understand from the docs is that somehow Google Cloud Run injects a unixsocket /cloudsql/PROJECT-ID:REGION:INSTANCE-ID to my container to provide connection to the cloudsql database and I can access that socket using jdbc:mysql:///DB_NAME?unixSocketPath=/cloudsql/PROJECT-ID:REGION:INSTANCE-ID. I also tried defining socketFactory=com.google.cloud.sql.mysql.SocketFactory plus adding the mysql-socket-factory-connector-j-8 dependency and setting cloudSqlInstance=PROJECT-ID:REGION:INSTANCE-ID and ipTypes=PUBLIC.


Solution

  • Datasource properties seem not to work with grails 4 Connection Pool Config. I had to add all the necessary info like socket, cloudSqlInstance and unixSocketPath in the right order to the jdbc-url and things just work.

    jdbc:mysql:///${DBNAME}?unixSocketPath=/cloudsql/${CLOUDSQL_INSTANCE}&cloudSqlInstance=${CLOUDSQL_INSTANCE}&socketFactory=com.google.cloud.sql.mysql.SocketFactory
    

    did the trick for me. Having the socketFactory or cloudSqlInstance parameter first did not work. Don't know why, but this solves my issue.