agentleFS
ai-enhanced-engineerai-enhanced-engineer/aiee-skills/skills/gcp-cloud-run/SKILL.md

gcp-cloud-run

Skill4 starsChanged 5 months agoMITView on GitHub

Cloud Run deployment patterns for stateless, scalable Python services. Use when deploying to Cloud Run, configuring health checks, optimizing cold starts, or troubleshooting container issues.

6 other projects use a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

1 rule. 0 are common, 1 is distinctive, and 0 are very specific to this project.

  • 0

    Common

    Most of the 6 edited versions we read keep these.

  • 1

    Distinctive

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Run BEFORE building/pushing Docker images (saves 5-10 min):

    line 68

“Common” is measured: kept by at least 6 in 10 of the 6 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Cloud Run Deployment Patterns

Stateless, scalable, cost-effective serverless containers on Google Cloud Run.

Core Constraints

ConstraintValueImplication
Port8080 (or PORT env)Must bind to this port
StatelessNo local file persistenceUse GCS/Redis for state
Request timeout60s default, 3600s maxLong-running tasks need async patterns
Cold starts2-30s depending on imageOptimize image size, preload configs
Concurrency1-1000 requests/instanceConfigure based on resource usage

Quick Reference

Port Binding

import os
import uvicorn

port = int(os.environ.get("PORT", 8080))
uvicorn.run(app, host="0.0.0.0", port=port)

Health Checks

EndpointPurposeCheck Dependencies?
/health/livenessProcess aliveNo - restart if fails
/health/readinessCan serve trafficYes - remove from LB if fails

Environment Variables

VariablePurposeExample
PORTContainer port8080
K_SERVICEService namemy-service
K_REVISIONRevision namemy-service-00001
K_CONFIGURATIONConfig namemy-service

Common Anti-Patterns

Anti-PatternProblemFix
Hardcoded port 8000Deployment failsUse os.environ.get("PORT", 8080)
DB check in livenessOutage restarts all containersOnly check in readiness
Large container imageSlow cold startsMulti-stage builds, slim base
Global ThreadPoolExecutorResource exhaustionRequest-scoped or asyncio
Placeholder env vars with PydanticContainer crashes at startupInject real values before deploy

Pydantic Settings and Cloud Run Deployment

Pydantic validates env vars at container startup (import time). A placeholder like "PLACEHOLDER_SET_BY_DEPLOY_SCRIPT" in an HttpUrl field crashes the container before any deploy script runs. Solution: deploy dependency services first, capture URLs, inject real values via sed/envsubst, then deploy. For self-referential WS_URL: deploy with placeholder, capture URL, update with gcloud run services update --set-env-vars. See reference.md § Pydantic Settings — Pre-Deployment Injection.

Pre-Deployment Validation Checklist

Run BEFORE building/pushing Docker images (saves 5-10 min):

  • Code quality: just validate-branch (format, lint, type-check, tests)
  • Dockerfile lint: hadolint/hadolint-action@v3.1.0
  • YAML validation: python -c "import yaml; yaml.safe_load(open('.cloudrun/staging.yaml'))"
  • Secrets verification: gcloud secrets describe <secret-name> --project=PROJECT_ID
  • Connection pool capacity: max_instances × (pool_size + pool_overflow) ≤ database_max_connections. Tier limits: db-f1-micro = 25, db-g1-small = 100, db-standard-1 = 200+.

Docker Multi-Stage Build Pattern

3-stage Dockerfile with uv + BuildKit caching: fetch uv → install deps in builder → copy .venv + src into a minimal runtime image with a non-root user. Yields 50-70% faster rebuilds and ~200MB runtime image (vs 1GB+ with build tools). See reference.md § Docker Multi-Stage Build (uv) for the full Dockerfile.

Service Account Verification for CI/CD

CI/CD secrets (e.g., GCP_SA_KEY) may contain a different service account than expected, causing silent permission failures. Debug by extracting the SA email from the key JSON (jq -r .client_email key.json), then confirm its IAM bindings on the target resource (gcloud run services get-iam-policy <svc> / gcloud projects get-iam-policy <project>) match what the deploy expects before assuming a code fault.

VPC Egress Configuration

Egress SettingUse CaseCost Impact
all-trafficGateway services needing external APIsHigher (all traffic through VPC)
private-ranges-onlyInternal services (DB, Redis only)Lower (only private IPs via VPC)

Entrypoint Shell Injection Prevention

Interpolating env vars into JSON via heredoc in entrypoint.sh is vulnerable to shell injection. jq provides safe JSON construction:

# BAD — shell injection via env var value
cat <<EOF > /app/config.json
{"apiUrl": "$API_URL"}
EOF

# GOOD — jq escapes values safely
jq -n --arg url "$API_URL" '{"apiUrl": $url}' > /app/config.json

Runtime config pipeline for Angular SPAs: runtime-config.model.ts → config.service.ts → config.initializer.ts → entrypoint.sh → .cloudrun/staging.yaml

See reference.md for connection pool settings, Redis configuration, and graceful shutdown patterns. See examples.md for thread-safe caching and complete health check implementations.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.