Connect to Google Cloud SQL from Java

blog-post-img

Recently, I migrated my application to Google Cloud Run and Cloud SQL, and I struggled with connecting to the database. So, I’d like to share one way to achieve the connection.

URL and SockeFactory

First, you need to use the correct JDBC URL:

jdbc:postgresql:///<database_name>?cloudSqlInstance=<instance_name>&socketFactory=com.google.cloud.sql.postgres.SocketFactory&user=<user_name>&password=<password>

As you can see, you have to provide the name of the database instead of the hostname in the URL, and then the parameter

  • cloudSqlInstance
  • socketFactory
  • user
  • password

Everything can be found in the configuration of your Cloud SQL instance. But what about the socketFactory? This one depends on the DB product, for example, PostgreSQL and requires an additional dependency:

<dependency>
    <groupId>com.google.cloud.sql</groupId>
    <artifactId>postgres-socket-factory</artifactId>
    <version>1.19.0</version>
</dependency>

That’s it from the Java side.

Finally, you must configure your Cloud Run service to connect to Cloud SQL. A detailed description can be found here: https://cloud.google.com/sql/docs/postgres/connect-run

Simon Martinelli
Follow Me