Connect Cloud Run and Cloud SQL PostgreSQL

While developing an application that is deployed in Google Cloud Run and uses a PostgreSQL database provided by Google Cloud SQL, I faced several issues. Here are my learnings from connecting a Cloud Run application and Cloud SQL.

Notes: I’m developing a NodeJS backend application. I’m using Prisma to access and migrate a database. Furthermore, as vcs I’m using github and corresponding for deploying from github to Google Cloud, github actions are used.

Creating a database in Cloud SQL requires first an instance. After creating the instance, one can create a database. For the database creation, you can choose any name you want. The relevant data you need to connect Cloud Run to Cloud SQL is the Connection name.

While deploying the application to Cloud Run, one have to set the –add-cloudsql-instances=“<Connection name>“ flag. Furthermore, I’ve had to create the .env file within the github-actions to not leak any secrets.

The .env file holds the DATABASE_URL that is required by Prisma to connect to the database. The DATABASE_URL needs to have the following structure postgresql://<database_user>:<database_password>@localhost/<database_name>?schema=public&host=/cloudsql/<Connection name> Every bold attribute needs to be exchanged with the corresponding information.

After deploying the application successfully, we have to look for the following log-line

db=cloudsqladmin,user=cloudsqladmin LOG: connection authorized: user=cloudsqladmin database=cloudsqladmin application_name=cloudsqlagent

This indicates that the Cloud Run application connected successfully to the Cloud SQL database.

Share this content:

No responses yet

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Latest Comments