Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 45 ยท Projects

Project: Deploy a Containerized API on Cloud Run

Package a small API in a container, push it to Artifact Registry, deploy it to Cloud Run, connect to Cloud SQL and keep the password in Secret Manager.

This project takes a small HTTP API from source code to a public HTTPS URL on Cloud Run. You will write a Dockerfile, store the image in Artifact Registry, deploy it with its own service account, connect it to a Cloud SQL database, and keep the database password in Secret Manager instead of in the image.

The commands need a Google Cloud project, so they are read-only here. To make the lesson runnable anyway, the second half builds a Node stand-in of the same API: it reads its settings from environment variables exactly like the container will, and it uses the built-in SQLite module in place of Cloud SQL. Read the real parts as a recipe; run the stand-in to see the logic.

From code to URL

Code A small HTTP API.
Image Built from a Dockerfile.
Registry Stored in Artifact Registry.
Cloud Run Runs it at a public URL.

Database and secrets are attached at deploy time.

1 / 2

Step 0: Set up

Choose a project and region, and enable the services you need. Review Cloud Run, containers and Artifact Registry and Cloud SQL if any of these are new.

Terminal
export PROJECT_ID=my-project-id
export REGION=us-central1

gcloud config set project $PROJECT_ID
gcloud services enable run.googleapis.com artifactregistry.googleapis.com \
  sqladmin.googleapis.com secretmanager.googleapis.com cloudbuild.googleapis.com

Step 1: The API

The service has two routes: /healthz and /notes, where GET lists notes and POST adds one. This version is read-only; a runnable cousin appears later. It follows the Cloud Run contract: listen on PORT, on all interfaces, and log to standard output. It uses the pg package for PostgreSQL, which is installed with npm in the image build.

JavaScript
// server.js
import http from "node:http";
import pg from "pg";

const pool = new pg.Pool({
  host: process.env.DB_HOST,            // /cloudsql/PROJECT:REGION:INSTANCE
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,    // injected from Secret Manager
  database: process.env.DB_NAME,
  max: 5
});

const server = http.createServer(async (req, res) => {
  try {
    if (req.url === "/healthz") {
      res.writeHead(200).end("ok");
    } else if (req.url === "/notes" && req.method === "GET") {
      const { rows } = await pool.query("SELECT id, text FROM notes ORDER BY id");
      res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(rows));
    } else if (req.url === "/notes" && req.method === "POST") {
      let body = "";
      for await (const chunk of req) body += chunk;
      const { text } = JSON.parse(body);
      const { rows } = await pool.query(
        "INSERT INTO notes (text) VALUES ($1) RETURNING id, text", [text]);
      res.writeHead(201, { "content-type": "application/json" }).end(JSON.stringify(rows[0]));
    } else {
      res.writeHead(404).end("not found");
    }
  } catch (error) {
    console.error(JSON.stringify({ severity: "ERROR", message: String(error) }));
    res.writeHead(500).end("server error");
  }
});

server.listen(process.env.PORT || 8080, "0.0.0.0");
process.on("SIGTERM", () => server.close(() => pool.end()));

Note the max: 5 on the pool. Each Cloud Run instance opens its own connections, so with many instances the total can exceed the database limit. Keep pools small and set --max-instances on the service.

Step 2: The Dockerfile

DOCKERFILE
FROM node:24-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
USER node
CMD ["node", "server.js"]

Copying package*.json first lets Docker reuse the dependency layer when only your code changes. Add a .dockerignore listing node_modules, .git and .env so local files and secrets never enter the image.

Step 3: Create a repository and build the image

Terminal
gcloud artifacts repositories create apps \
  --repository-format=docker --location=$REGION

# Build in the cloud (no local Docker needed) and push
gcloud builds submit \
  --tag=$REGION-docker.pkg.dev/$PROJECT_ID/apps/notes-api:1

gcloud builds submit uploads your folder to Cloud Build, builds the Dockerfile and pushes the result to Artifact Registry. With local Docker you would run gcloud auth configure-docker $REGION-docker.pkg.dev, then docker build and docker push.

Step 4: Create the database

A small PostgreSQL instance is enough for practice. It starts billing as soon as it exists, so remember the cleanup step at the end.

Terminal
gcloud sql instances create notes-db \
  --database-version=POSTGRES_16 \
  --edition=ENTERPRISE \
  --tier=db-f1-micro \
  --region=$REGION

gcloud sql databases create notes --instance=notes-db
gcloud sql users create notes_app --instance=notes-db --password="CHANGE-ME-LONG-RANDOM"

Then create the table once, for example by connecting with gcloud sql connect notes-db --user=notes_app --database=notes and running:

SQL
CREATE TABLE notes (
  id serial PRIMARY KEY,
  text text NOT NULL
);

Check the current machine tiers and editions in the documentation, because available choices change.

Step 5: Keep the password in Secret Manager

Terminal
printf '%s' "CHANGE-ME-LONG-RANDOM" | \
  gcloud secrets create notes-db-password --data-file=-

Create a dedicated service account for the API and give it only what it needs: permission to connect to Cloud SQL and to read that one secret (least privilege).

Terminal
gcloud iam service-accounts create notes-api

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:notes-api@$PROJECT_ID.iam.gserviceaccount.com" \
  --role=roles/cloudsql.client

gcloud secrets add-iam-policy-binding notes-db-password \
  --member="serviceAccount:notes-api@$PROJECT_ID.iam.gserviceaccount.com" \
  --role=roles/secretmanager.secretAccessor

See Secret Manager and KMS for versions and rotation.

Step 6: Deploy

Cloud Run connects to Cloud SQL through a built-in socket when you pass --add-cloudsql-instances; the database host is then a Unix socket path. The secret is exposed as an environment variable.

Terminal
gcloud run deploy notes-api \
  --image=$REGION-docker.pkg.dev/$PROJECT_ID/apps/notes-api:1 \
  --region=$REGION \
  --service-account=notes-api@$PROJECT_ID.iam.gserviceaccount.com \
  --add-cloudsql-instances=$PROJECT_ID:$REGION:notes-db \
  --set-env-vars=DB_HOST=/cloudsql/$PROJECT_ID:$REGION:notes-db,DB_USER=notes_app,DB_NAME=notes \
  --set-secrets=DB_PASSWORD=notes-db-password:latest \
  --max-instances=5 \
  --allow-unauthenticated

The command prints the service URL. Try it:

Terminal
URL=$(gcloud run services describe notes-api --region=$REGION --format="value(status.url)")
curl -X POST "$URL/notes" -H "content-type: application/json" -d '{"text":"first note"}'
curl "$URL/notes"

If the deploy fails, open the logs (gcloud run services logs read notes-api --region=$REGION). The usual causes are listening on the wrong port, a missing permission, or a password mismatch; the checklist in common mistakes applies.

Step 7: Ship a change safely

Build tag 2, deploy it without traffic, test it through its tag URL, then move traffic:

Terminal
gcloud run deploy notes-api --image=$REGION-docker.pkg.dev/$PROJECT_ID/apps/notes-api:2 \
  --region=$REGION --no-traffic --tag=candidate
gcloud run services update-traffic notes-api --region=$REGION --to-latest

Cleanup

Terminal
gcloud run services delete notes-api --region=$REGION
gcloud sql instances delete notes-db
gcloud secrets delete notes-db-password
gcloud artifacts repositories delete apps --location=$REGION

Stand-in: the same API, runnable

The program below is a real HTTP server running on Piston, with the same routes and the same environment-variable configuration. The differences are honest ones: the database is SQLite in memory (node:sqlite) instead of Cloud SQL, the "secret" is a plain variable with a default instead of a Secret Manager value, and the server calls itself with fetch. It shows request handling and configuration, not Google's infrastructure.

Node.js Stand-in: notes API with an in-memory database

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The empty note is rejected with 400 before it reaches the database, and logging only the password's length shows the habit of never printing secrets. In the real deployment the pg pool replaces the SQLite calls, and the Cloud SQL socket replaces the in-memory file; nothing else in the request handling changes, which is the point of keeping configuration in the environment.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should the database password live in this project?

    Secret Manager keeps the value out of source and images, and the service account only needs read access to that one secret.
  2. 2. Which role lets the service connect to Cloud SQL?

    Cloud SQL Client is the narrow role for connecting. Owner would be far broader than necessary.
  3. 3. Why set --max-instances and a small connection pool?

    Total connections are roughly instances times pool size, and databases have limits.
  4. 4. Why copy package.json before the rest of the code in the Dockerfile?

    Layers are cached in order. Dependencies change rarely, so installing them before copying code speeds up rebuilds.

Summary

  • Containerize the API, push the image to Artifact Registry, and deploy it to Cloud Run with a dedicated service account.
  • Connect to Cloud SQL with --add-cloudsql-instances and the roles/cloudsql.client role.
  • Store the password in Secret Manager and inject it with --set-secrets; never bake it into the image.
  • Limit instances and pool sizes, deploy new versions with --no-traffic and a tag, and delete the database when you finish.

Next: Project: Event-Driven Image or Data Pipeline