Connect Google Cloud Run with CloudSQL Postgres

Date: 2022-06-22 | google-cloud | cloud-sql | postgres | database | cloud-run |

So you've got a service up and running on Google Cloud Run and a Postgres database instance in CloudSQL. But how do you actually use that database from Cloud Run?

In this post, I'm going to share step-by-step instructions for configuring your Google Cloud Project and Cloud Run service so it can access CloudSQL.

Table of Contents

Pre-requisites

For this post, we're going to assume that you already have:

  • Cloud Run service created
  • Postgres CloudSQL database instance created

I have a post going over how to setup a CloudSQL Postgres database for <$10 per month if you still need to do that.

Configuring Google Cloud

The easiest way to connect Cloud Run and CloudSQL is through the CloudSQL Proxy. This requires your CloudSQL instance to be configured with a Public IP but makes it very simple to connect to your instance with minimal extra configuration required.

Cloud Run <> Cloud SQL Proxy Cloud Run <> Cloud SQL Proxy

To allow Cloud Run to connect to CloudSQL via the CloudSQL Proxy:

  • Go to Cloud Run
  • Select the service you want to connect to CloudSQL from
  • Click Edit & Deploy New Revision > Connections
  • Click Add Connection under Cloud SQL Connections
    • You may need to Enable the Cloud SQL Admin API
  • Select the CloudSQL instance you want to connect to

Once the new revision is deployed, you should be able to connect to CloudSQL from Cloud Run!

Connecting from Cloud Run

Now that our permissions / connections are configured, we now need to do the actual connection to CloudSQL from Cloud Run. How you actually create this connection will largely depend on your technologies of choice, but most connections require the same core parameters so we'll list those here.

Example connection parameters Example connection parameters

  • Host: /cloudsql/CONNECTIONNAME
    • CONNECTIONNAME - You can get this from your CloudSQL instance page
  • Database User: defaults to postgres
  • Database name: defaults to postgres
  • Database password: Created when you created your cloudSQL instance

Further Reading

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.