Python Labs · Lab 5 of 6
Deploy the API to Google Cloud Run
Push the catalog image to Artifact Registry and run it on Cloud Run: a managed, autoscaling container service with HTTPS, revisions and per-request billing. Then remove everything so nothing keeps costing money.
- Environment
- Google Cloud
- Level
- Intermediate
- Time
- About 40 min
- Cost
- Usually $0 within the free tier; check current pricing
You will build
The catalog API running on a public https://...run.app URL, built from the same image you ran locally, and a
clear picture of what a real deployment adds.
Before you start
- Lab: Containerise the API: Dockerfile, Compose and Postgres
A Google Cloud project with billing enabled
The gcloud CLI, signed in (
gcloud auth login)
Cloud commands depend on your project, region and account, so this lab shows what to check after each step instead of exact output. The local steps were run for real.
This deployment keeps SQLite in /tmp inside the container to stay free and simple. That data is lost
whenever Cloud Run replaces the instance: fine for a demo, never for real data (see In production).
Project structure
catalog/ ├── Dockerfile ├── compose.yaml ├── pyproject.toml ├── uv.lock ├── src/catalog/... └── tests/...
Steps
-
1Run the image the way Cloud Run will
Cloud Run gives the container a writable
/tmponly. The app runs as a non-root user who can't write to/app, so the SQLite file must live in/tmp. Try both:Run docker run --rm -e DATABASE_URL=sqlite:///./catalog.db catalog-api \ python -c "import sqlite3; sqlite3.connect('catalog.db').execute('create table t(x int)')" docker run -d --name catalog-cloudrun-check -p 8080:8000 \ -e DATABASE_URL=sqlite:////tmp/catalog.db catalog-api > /dev/null sleep 3 curl -s localhost:8080/healthz curl -s -X POST localhost:8080/products -H 'Content-Type: application/json' \ -d '{"name": "Cloud mug", "price_cents": 1500}' docker rm -f catalog-cloudrun-check > /dev/nullExpected output
... sqlite3.OperationalError: unable to open database file {"status":"ok"} {"name":"Cloud mug","price_cents":1500,"id":1}Check:The first command fails (read-only
/appfor the app user); the/tmpversion works. -
2Choose a project and region
Run export PROJECT_ID=your-project-id export REGION=europe-west1 gcloud config set project $PROJECT_ID gcloud services enable run.googleapis.com artifactregistry.googleapis.comCheck:gcloud config get projectprints your project ID; enabling the APIs finishes without errors. -
3Create a container registry
Run gcloud artifacts repositories create labs --repository-format=docker \ --location=$REGION --description="Lab images" gcloud auth configure-docker $REGION-docker.pkg.devCheck:gcloud artifacts repositories list --location=$REGIONshowslabs. -
4Build for Cloud Run's platform and push
Cloud Run runs
linux/amd64. On an Apple Silicon Mac,--platformmakes Docker build for that architecture instead of yours. Use a real version tag, neverlatest, so every deployment is traceable.Run export IMAGE=$REGION-docker.pkg.dev/$PROJECT_ID/labs/catalog:v1 docker build --platform linux/amd64 -t $IMAGE . docker push $IMAGECheck:The push ends with a
digest: sha256:...line, and the image appears in the Artifact Registry console. -
5Deploy
--port 8000matches the port uvicorn listens on.--max-instances 1caps cost while you experiment.--allow-unauthenticatedmakes the URL public: fine for this demo API.Run gcloud run deploy catalog --image=$IMAGE --region=$REGION --port=8000 \ --allow-unauthenticated --max-instances=1 --memory=512Mi \ --set-env-vars=DATABASE_URL=sqlite:////tmp/catalog.dbCheck:The command ends with
Service URL: https://catalog-...run.app. -
6Call the deployed API
Run export URL=$(gcloud run services describe catalog --region=$REGION --format='value(status.url)') curl -s $URL/healthz curl -s -X POST $URL/products -H 'Content-Type: application/json' \ -d '{"name": "Coffee mug", "price_cents": 1299}' curl -s $URL/productsCheck:The same JSON as on your laptop, now over HTTPS with a certificate Google manages for you.
-
7Read the logs
Run gcloud logging read 'resource.type="cloud_run_revision" AND resource.labels.service_name="catalog"' \ --limit=10 --format='value(textPayload)'Check:You see uvicorn's start-up lines and your requests. The Cloud Run console shows the same logs.
-
8Deploy a new revision and roll back
Every deployment creates an immutable revision. Rolling back is moving traffic, not rebuilding.
Run gcloud run deploy catalog --image=$IMAGE --region=$REGION --update-env-vars=LOG_LEVEL=DEBUG gcloud run revisions list --service=catalog --region=$REGION gcloud run services update-traffic catalog --region=$REGION --to-revisions=PREVIOUS_REVISION=100Check:revisions listshows two revisions; afterupdate-traffic, the older one serves 100%.Hint
Replace
PREVIOUS_REVISIONwith the older name fromrevisions list, e.g.catalog-00001-abc.
Clean up
Delete the service and the registry (its stored images are what can cost money):
gcloud run services delete catalog --region=$REGION --quiet
gcloud artifacts repositories delete labs --location=$REGION --quiet
Check with gcloud run services list and gcloud artifacts repositories list --location=$REGION: both should
be empty. If you created a project just for this lab, gcloud projects delete $PROJECT_ID removes everything.
In production
Cloud Run handles HTTPS, scaling and patching the servers. A production deployment adds a real database, secrets, identity and a pipeline.
What changes
| In this lab | In production |
|---|---|
SQLite in /tmp, lost on restart |
Cloud SQL for PostgreSQL, connected through the Cloud SQL connector or private IP, with backups |
| Environment variables on the command line | Secrets from Secret Manager (--set-secrets), and a runtime service account with only the roles it needs |
--allow-unauthenticated |
Public only if it must be; otherwise IAM authentication or an API gateway; a load balancer with Cloud Armor for public APIs |
You run docker push and gcloud run deploy |
CI builds, scans and pushes the image, then deploys with Workload Identity Federation (no stored keys) |
--max-instances 1 |
Min instances to avoid cold starts on latency-sensitive services, a max to protect the database, and concurrency tuned to your workload |
| Manual rollback | Gradual rollouts with --no-traffic and traffic splitting, automatic rollback on error-rate alerts |
| Logs in the console | Log-based metrics, uptime checks, alerting policies and a budget alert on the project |
Production checklist
- Real database (Cloud SQL) with backups; no state in the container
- Dedicated runtime service account with least privilege; secrets from Secret Manager
- Image tags are immutable versions or digests; images scanned before deploy
- CI deploys with Workload Identity Federation; humans don't deploy from laptops
- Min/max instances and concurrency set deliberately; database connections sized to max instances
- Uptime checks, alerts and a budget alert configured
- Every lab or test resource deleted when no longer needed
Learn the concepts
- Python Serverless on AWS Lambda · Course
- Docker from Basics to Production · Course