On this page
article
Deploying Google Cloud Functions
Deploy Python Cloud Functions to production — CI/CD, custom domains, monitoring, and environment management on GCP.
Moving from gcloud functions deploy to a production pipeline requires CI/CD, environment separation, and monitoring.
Project Setup
gcloud projects create my-project-id
gcloud config set project my-project-id
gcloud services enable cloudfunctions.googleapis.com
gcloud services enable cloudbuild.googleapis.com
gcloud services enable run.googleapis.com
Environment Variables per Stage
# Development
gcloud functions deploy my-api-dev \
--gen2 --runtime=python312 --region=us-central1 \
--source=. --entry-point=handler \
--trigger-http --allow-unauthenticated \
--set-env-vars="ENV=dev,LOG_LEVEL=DEBUG"
# Production
gcloud functions deploy my-api-prod \
--gen2 --runtime=python312 --region=us-central1 \
--source=. --entry-point=handler \
--trigger-http \
--set-env-vars="ENV=prod,LOG_LEVEL=INFO" \
--set-secrets="API_KEY=prod-api-key:latest" \
--min-instances=1 \
--max-instances=50
CI/CD with Cloud Build
# cloudbuild.yaml
steps:
- name: 'python:3.12'
entrypoint: pip
args: ['install', '-r', 'requirements.txt', '-t', './package']
- name: 'python:3.12'
entrypoint: python
args: ['-m', 'pytest', 'tests/', '-v']
- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
entrypoint: gcloud
args:
- functions
- deploy
- my-api
- --gen2
- --runtime=python312
- --region=us-central1
- --source=.
- --entry-point=handler
- --trigger-http
Trigger on git push:
gcloud builds triggers create github \
--repo-name=my-repo --repo-owner=my-org \
--branch-pattern="^main$" \
--build-config=cloudbuild.yaml
Custom Domain & HTTPS
Map a custom domain via Cloud Run (Gen 2 functions run on Cloud Run):
gcloud run domain-mappings create \
--service=my-api \
--domain=api.example.com \
--region=us-central1
Add the DNS records shown in the output to your domain registrar.
Monitoring Dashboard
Key Cloud Monitoring metrics:
- Request count and latency (p50, p95, p99)
- Error rate (4xx, 5xx)
- Active instances and cold start frequency
- Memory and CPU utilization
Create an alert policy for error rate > 5% over 5 minutes.
Rollback
# List revisions
gcloud functions describe my-api --gen2 --region=us-central1
# Route 100% traffic to previous revision
gcloud run services update-traffic my-api \
--to-revisions=PREVIOUS_REVISION=100 \
--region=us-central1
Cost Management
| Strategy | Impact |
|---|---|
Set --max-instances |
Cap runaway scaling costs |
Use --min-instances=0 in dev |
No idle cost |
| Right-size memory | Faster = potentially cheaper |
| Use Cloud Scheduler + batch | Reduce invocation count |
Related Chapters
Production Cloud Functions on GCP leverage Cloud Run infrastructure for reliability and scale.