Cloud and deployment · Intermediate · 22 min
Connect a Cloud Run service to Cloud SQL for PostgreSQL
By Padding · Updated 18 Nov 2026
Google Cloud · gcloud 594.0.1 · Cloud SQL for PostgreSQL 18 · Cloud SQL Auth Proxy 2.28.1 · Node.js 26
You will run a Node.js service on Cloud Run that reads and writes a Cloud SQL for PostgreSQL 18 database as its own service account, with IAM database authentication so no database password exists, and then delete the instance so it stops billing.
On this page
Most Cloud Run services need somewhere to keep data, and Cloud SQL for PostgreSQL is Google's managed answer: Google runs the server, patches it and takes backups, and you get a database you reach by name. The part that goes wrong in practice is the connection. Teams open the database to the internet, paste a password into an environment variable and forget about it until it leaks.
This tutorial takes a different route. The Cloud Run service gets its own service account, Cloud SQL trusts that account through IAM database authentication, and the Cloud SQL Node.js connector fetches a short-lived token and an encrypted connection for it. There is no database password anywhere: not in the code, not in an environment variable, not in Secret Manager. You will set up the database from your own computer through the Cloud SQL Auth Proxy, using your own Google identity, then deploy a small visit counter that writes to it.
All names in this tutorial (run-sql-demo, demo, the europe-west1 region) are examples. Replace PROJECT_ID with your project's ID wherever it appears.
This costs money from the moment the instance exists. Unlike Cloud Run, a Cloud SQL instance does not scale to zero: it bills by the second for as long as it is running, whether anyone uses it or not, plus its storage. On 26 November 2026 Google's list price for the smallest machine, db-f1-micro, was 0.0105 USD per hour in Iowa (us-central1), about 7.70 USD for a 30-day month, and SSD storage was about 0.17 USD per GiB per month, so the default 10 GiB adds about 1.70 USD. Prices differ by region and change, so check cloud.google.com/sql/pricing for your region before you start. The last step deletes the instance; do it the same day if you only want to learn.
Step 1 · Choose a region and enable the APIs
Pick one region for both Cloud Run and Cloud SQL. Keeping them together avoids cross-region latency and network charges. This tutorial uses europe-west1. If your users are in Africa, Johannesburg (africa-south1) is on Cloud SQL's price list; check the Cloud Run and Cloud SQL locations pages to confirm both are offered there for your project, and expect different prices from the Iowa figures above.
Set the project and region, and enable the services you need: Cloud SQL Admin for the database and the connector, plus Cloud Run, Cloud Build and Artifact Registry for the deploy:
gcloud config set project PROJECT_ID
gcloud config set run/region europe-west1
gcloud services enable sqladmin.googleapis.com run.googleapis.com \
cloudbuild.googleapis.com artifactregistry.googleapis.comMake a working folder for the demo, so nothing lands among your own projects:
mkdir -p ~/run-sql-demo
cd ~/run-sql-demoCheck it worked
gcloud services list --enabled --filter="name:sqladmin.googleapis.com" prints one line naming sqladmin.googleapis.com. gcloud config get run/region prints europe-west1.
Step 2 · Create the instance with IAM authentication on
Read this before you run the command. For PostgreSQL 16 and later, gcloud creates an Enterprise Plus instance unless you say otherwise, and Enterprise Plus has no small shared-core machines. Pass --edition=enterprise and --tier=db-f1-micro explicitly, or you will get a much larger and more expensive machine.
gcloud sql instances create run-sql-demo \
--database-version=POSTGRES_18 \
--edition=enterprise \
--tier=db-f1-micro \
--region=europe-west1 \
--database-flags=cloudsql.iam_authentication=on \
--connector-enforcement=REQUIRED \
--no-backupWhat each choice does:
cloudsql.iam_authentication=onlets Google identities (people and service accounts) log in to PostgreSQL with a short-lived IAM token instead of a password.--connector-enforcement=REQUIREDrefuses any connection that does not come through a Cloud SQL connector or the Auth Proxy. The instance has a public IP address, but no networks are authorised on it, and with this setting a plainpsqlto that address is refused. Every connection is therefore encrypted and checked against IAM first.--no-backupturns off daily backups to keep this demo cheap. Leave backups on (the default) for any database whose data you care about.- No
--root-password. The built-inpostgresuser cannot log in until someone sets a password for it, and in this tutorial nobody does.
There is also a private IP route, where the instance has no public address and Cloud Run reaches it through your VPC with Direct VPC egress or a Serverless VPC Access connector. It is a good choice for production, but it needs network setup that this tutorial leaves out. The connector code below works with either; you change one setting.
Creating the instance takes several minutes. Then read its instance connection name, which every later step uses. It has the form PROJECT_ID:europe-west1:run-sql-demo:
gcloud sql instances describe run-sql-demo --format='value(connectionName)'Check it worked
gcloud sql instances list shows run-sql-demo with POSTGRES_18, tier db-f1-micro and status RUNNABLE. Run gcloud sql instances describe run-sql-demo --format='value(settings.databaseFlags)' and look for cloudsql.iam_authentication with the value on. If you ever change flags later with gcloud sql instances patch --database-flags, list every flag you want, because that command resets the ones you leave out.
Step 3 · Add the database and its two users
Create the database:
gcloud sql databases create demo --instance=run-sql-demoNext, create the service account the Cloud Run service will run as, and give it two project roles. roles/cloudsql.client lets it open a connection to the instance, and roles/cloudsql.instanceUser lets it log in with IAM. Neither lets it change or delete the instance:
gcloud iam service-accounts create run-sql-demo \
--display-name="Cloud Run demo service for Cloud SQL"
SA=run-sql-demo@PROJECT_ID.iam.gserviceaccount.com
for ROLE in roles/cloudsql.client roles/cloudsql.instanceUser; do
gcloud projects add-iam-policy-binding PROJECT_ID \
--member="serviceAccount:$SA" --role="$ROLE" --condition=None
doneThese roles apply to every Cloud SQL instance in the project. In a shared project, narrow them with an IAM condition on the resource name; the IAM tutorial linked at the end shows how.
Now add two database users that authenticate with IAM. One is you, as the person who sets up the schema; give yourself the cloudsqlsuperuser database role. The other is the service account, with no database roles at all, since you will grant it exactly what it needs in the next step. Replace you@example.com with your Google account email, in lower case:
gcloud sql users create you@example.com \
--instance=run-sql-demo --type=cloud_iam_user --database-roles=cloudsqlsuperuser
gcloud sql users create run-sql-demo@PROJECT_ID.iam \
--instance=run-sql-demo --type=cloud_iam_service_accountNote the second username: for service accounts, Cloud SQL drops the .gserviceaccount.com ending, because PostgreSQL usernames are limited to 63 characters. The database user is run-sql-demo@PROJECT_ID.iam. That shortened form is what the app passes as its user later.
As the project owner you can already log in, but if someone else follows these steps, they need roles/cloudsql.instanceUser and roles/cloudsql.client granted to their own account too.
Check it worked
gcloud sql users list --instance=run-sql-demo shows your email with type CLOUD_IAM_USER and run-sql-demo@PROJECT_ID.iam with type CLOUD_IAM_SERVICE_ACCOUNT, next to the built-in postgres user. You never set a password for any of the three.
Step 4 · Connect from your computer through the Auth Proxy
The Cloud SQL Auth Proxy runs on your computer, listens on a local port, and forwards each connection to the instance over an encrypted tunnel after checking your IAM identity. With --auto-iam-authn it also logs you in with an IAM token, so psql never asks for a password.
Download version 2.28.1 for your system. The proxy is a single binary that gets no automatic updates; to upgrade, download a newer version the same way:
case "$(uname -s)-$(uname -m)" in
Linux-x86_64) BUILD=linux.amd64 ;;
Linux-aarch64) BUILD=linux.arm64 ;;
Darwin-arm64) BUILD=darwin.arm64 ;;
Darwin-x86_64) BUILD=darwin.amd64 ;;
*) echo "No proxy build listed here for $(uname -s) $(uname -m)"; false ;;
esac
curl -fsSL -o cloud-sql-proxy \
"https://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.28.1/cloud-sql-proxy.${BUILD}"
chmod +x cloud-sql-proxy
./cloud-sql-proxy --versionThe proxy finds your identity through Application Default Credentials. Sign in for those once; a browser window opens:
gcloud auth application-default loginStart the proxy in its own terminal. Port 6543 avoids clashing with any PostgreSQL already on your computer, and the proxy only listens on 127.0.0.1, so nothing else on your network can use it:
cd ~/run-sql-demo
./cloud-sql-proxy --auto-iam-authn --port 6543 PROJECT_ID:europe-west1:run-sql-demoLeave it running. In a second terminal, connect as yourself:
psql "host=127.0.0.1 port=6543 dbname=demo user=you@example.com"On a slow or metered connection, such as prepaid mobile data, the proxy and psql use very little: the traffic is your queries and their results, not a remote desktop.
Check it worked
psql opens a demo=> prompt without asking for a password. Type SELECT current_user; and it prints your email. If instead the proxy logs a 403 or a message about a missing permission, your account lacks one of the two roles from the previous step; IAM changes can take a minute or two to apply, so wait and retry. If it says the login failed for your user, check that the email in gcloud sql users list matches your account exactly, in lower case.
Step 5 · Create the table and grant the service its rights
A new IAM database user has no privileges at all. Still in psql as yourself, create the one table the app needs, then grant the service account permission to read it and add rows, and to use the sequence that numbers them. It gets no right to update, delete or drop anything. Replace PROJECT_ID in the username, and keep the double quotes, which PostgreSQL needs because the name contains @ and .:
CREATE TABLE visits (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
visited_at timestamptz NOT NULL DEFAULT now()
);
GRANT SELECT, INSERT ON visits TO "run-sql-demo@PROJECT_ID.iam";
GRANT USAGE ON SEQUENCE visits_id_seq TO "run-sql-demo@PROJECT_ID.iam";Type \q to leave psql, and stop the proxy with Ctrl+C. You will not need it again until you want to look at the data.
Check it worked
Before you quit, \dp visits lists the table's privileges. The line for run-sql-demo@PROJECT_ID.iam shows ar, which is PostgreSQL's shorthand for INSERT (a, append) and SELECT (r, read), and nothing else.
Step 6 · Write the service with the Node.js connector
The service counts visits. Each request to / adds a row and replies with the total and the database user it ran as, so you can see the IAM login working. It uses two packages, pinned to exact versions: pg (node-postgres) to run queries, and Google's @google-cloud/cloud-sql-connector, which opens the encrypted connection and supplies an IAM token in place of a password. In your demo folder:
cat > package.json <<'JSON'
{
"name": "run-sql-demo",
"private": true,
"type": "module",
"dependencies": {
"@google-cloud/cloud-sql-connector": "1.13.1",
"pg": "8.23.1"
}
}
JSONcat > server.js <<'JS'
import http from 'node:http'
import pg from 'pg'
import { Connector } from '@google-cloud/cloud-sql-connector'
const connector = new Connector()
const clientOpts = await connector.getOptions({
instanceConnectionName: process.env.INSTANCE_CONNECTION_NAME,
ipType: 'PUBLIC',
authType: 'IAM',
})
const pool = new pg.Pool({
...clientOpts,
user: process.env.DB_USER,
database: process.env.DB_NAME,
max: 5,
})
const server = http.createServer(async (req, res) => {
if (req.url !== '/') {
res.writeHead(404).end()
return
}
try {
await pool.query('INSERT INTO visits DEFAULT VALUES')
const { rows } = await pool.query(
'SELECT current_user AS db_user, count(*)::int AS visits FROM visits',
)
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(rows[0]) + '\n')
} catch (err) {
console.error(err)
res.writeHead(500, { 'Content-Type': 'application/json' })
res.end('{"error":"database request failed"}\n')
}
})
server.listen(process.env.PORT || 8080, '0.0.0.0')
process.on('SIGTERM', () => {
server.close(async () => {
await pool.end()
connector.close()
process.exit(0)
})
})
JSThere is no password in the pool settings; the connector handles login. All three settings come from environment variables, none of them secret. To use a private IP instead of the public one, change ipType to 'PRIVATE' and give the service a route into your VPC. The service also closes the pool and the connector when Cloud Run sends SIGTERM, so connections are not left hanging on the database.
Then the Dockerfile. It installs the exact versions in package.json; if you have Node.js locally, run npm install once to create a package-lock.json and switch the RUN line to npm ci --omit=dev for repeatable builds:
cat > Dockerfile <<'DOCKER'
FROM node:26-slim
WORKDIR /app
COPY package*.json ./
RUN npm install --omit=dev
COPY server.js ./
ENV NODE_ENV=production
USER node
CMD ["node", "server.js"]
DOCKERCheck it worked
ls ~/run-sql-demo shows Dockerfile, package.json, server.js and the cloud-sql-proxy binary. grep -n password server.js prints nothing.
Step 7 · Deploy to Cloud Run as the service account
Deploy from source. --service-account makes the service run as run-sql-demo instead of the Compute Engine default account, which in many projects has far broader rights. --no-allow-unauthenticated keeps the service private, because every request writes to your database, and --max-instances 2 caps how many instances, and so how many database connections, it can open. Each instance holds up to five connections (the pool's max), and a db-f1-micro instance does not take many:
gcloud run deploy run-sql-demo --source . --region europe-west1 \
--service-account run-sql-demo@PROJECT_ID.iam.gserviceaccount.com \
--set-env-vars INSTANCE_CONNECTION_NAME=PROJECT_ID:europe-west1:run-sql-demo,DB_USER=run-sql-demo@PROJECT_ID.iam,DB_NAME=demo \
--no-allow-unauthenticated \
--max-instances 2As project owner you can deploy as that service account. Someone with fewer rights also needs the Service Account User role (roles/iam.serviceAccountUser) on it.
Socket or connector
You may see guides that add --add-cloudsql-instances=PROJECT_ID:europe-west1:run-sql-demo to the deploy. That flag makes Cloud Run mount a Unix socket at /cloudsql/PROJECT_ID:europe-west1:run-sql-demo in each instance of the service, and the app connects to the socket path instead of loading a connector. It suits drivers and languages without a Cloud SQL connector. This service does not use the socket: the Node.js connector opens its own connection, so the flag is not needed here.
Check it worked
Call the private service with your identity token, twice:
URL=$(gcloud run services describe run-sql-demo --region europe-west1 --format='value(status.url)')
curl -s -H "Authorization: Bearer $(gcloud auth print-identity-token)" "$URL"
curl -s -H "Authorization: Bearer $(gcloud auth print-identity-token)" "$URL"The replies look like {"db_user":"run-sql-demo@PROJECT_ID.iam","visits":1} and then "visits":2. The db_user value proves the service logged in as its own service account with no password. If you get a 500, read the logs with gcloud run services logs read run-sql-demo --region europe-west1:
permission denied for table visitsorfor sequence visits_id_seq: aGRANTfrom the earlier step is missing or names the wrong user.- A message that the login failed for the user:
DB_USERmust be the shortened...@PROJECT_ID.iamform, and the service account must haveroles/cloudsql.instanceUser. - A
403namingcloudsql.instances.connector the Cloud SQL Admin API: the service account lacksroles/cloudsql.client, orsqladmin.googleapis.comis not enabled.
Step 8 · Delete the instance and everything else
Do this as soon as you are done: the instance bills every hour it exists. Deleting it destroys the database and all its data, and with backups off there is nothing to restore from, so copy out anything you want to keep first.
Delete the Cloud Run service, then the instance:
gcloud run services delete run-sql-demo --region europe-west1
gcloud sql instances delete run-sql-demoRemove the service account's project roles before deleting the account, so no orphaned bindings stay in the project's IAM policy, then delete the account:
SA=run-sql-demo@PROJECT_ID.iam.gserviceaccount.com
for ROLE in roles/cloudsql.client roles/cloudsql.instanceUser; do
gcloud projects remove-iam-policy-binding PROJECT_ID \
--member="serviceAccount:$SA" --role="$ROLE" --condition=None
done
gcloud iam service-accounts delete "$SA"The source deploy also created an Artifact Registry repository and a Cloud Storage bucket for the uploaded source. Delete them as described in the clean-up step of the Cloud Run tutorial linked below, after checking they hold nothing else you need.
Finally, on your computer, remove the local credentials and the proxy binary, then the demo folder:
gcloud auth application-default revoke
rm -r ~/run-sql-demoIf you use Application Default Credentials for other work, skip the revoke line.
Check it worked
gcloud sql instances list no longer shows run-sql-demo, gcloud run services list no longer shows the service, and gcloud iam service-accounts list no longer lists run-sql-demo@.... Check Billing reports the next day: Cloud SQL charges for the project should have stopped.
Next steps
- Narrow the service account's roles to one instance with IAM conditions, and review who has access: /tutorials/grant-least-privilege-access-in-google-cloud-iam
- Go back over the Cloud Run basics, including the full clean-up of source deploys: /tutorials/deploy-a-container-to-google-cloud-run
- Compare the same job on AWS, with a private database and TLS checks: /tutorials/run-a-managed-postgresql-database-on-amazon-rds
Related tutorials
- How to Deploy a Container to Google Cloud RunYou will package a small Node.js 26 web service with a Dockerfile, deploy it to Google Cloud Run with one gcloud command, cap how far it can scale, roll back to an earlier revision, and delete every resource the deploy created.
- Grant least-privilege access in Google Cloud with IAM roles and service accountsYou will give one Cloud Run service its own service account that can read exactly one Secret Manager secret, test that access by impersonation instead of a key, add a grant that expires on its own, and review who can reach the secret.
- Run a managed PostgreSQL database on Amazon RDSYou will have a PostgreSQL 18 database on Amazon RDS in private subnets, reachable only from your app servers over verified TLS, with its password held in Secrets Manager, a manual snapshot taken and a clean way to delete it all.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials