Skip to Content
gentlemans-stack
ReferencePlatforms

platforms/gcp/cloud-run

Deploy a stack service to Google Cloud Run. Bash scripts around gcloud, run from a checkout; this is not an Nx project and not a pnpm package (no package.json), so it has no build, no tests and nothing imports it. The core stays cloud-free: images are built by the core docker:build Nx target (scripts/build-docker-image.mjs), and these scripts only log in to Artifact Registry, push, and deploy.

FilePurpose
deploy-cloud-run.shBuild, push and deploy one service; sync its secrets into Secret Manager
deploy-gcp.shOne entry point over the deploy targets (today Cloud Run only)
cleanup-gcp.shAudit, and with explicit flags apply, Artifact Registry and Secret Manager cleanup
artifact-registry-cleanup-policy.jsonPolicy applied on each deploy: delete untagged images older than seven days
lib.shLogging, required-setting checks, the --dry-run wrappers (sourced by the three scripts)

Settings

Nothing is defaulted to a project, region or service. Set these in the environment (or a .env; see below) and run from anywhere.

VariableUsed byMeaning
PROJECT_IDallGoogle Cloud project (required)
REGIONallCloud Run and Artifact Registry region (required)
REPOSITORYallArtifact Registry Docker repository; images are <REGION>-docker.pkg.dev/<PROJECT_ID>/<REPOSITORY>/<service> (required)
SERVICEdeployService name, or the positional argument / --service (required)
RUNTIME_SERVICE_ACCOUNTdeployRuntime identity (default <service>-runtime@<PROJECT_ID>.iam.gserviceaccount.com, created if missing)
SERVICE_CONFIGdeployPath to the service config (default services/<service>/cloud-run.config.sh, then apps/<service>/...)
ENV_FILEdeployLocal file with secret sources (default <repo>/.env)
REPO_ROOTdeployWorkspace root (default three levels above the script)
SECRET_NAMEScleanupSpace-separated secrets to inspect (or repeat --secret); none means secret versions are skipped
DRY_RUNalltrue is the same as --dry-run

cleanup-gcp.sh also takes --project, --region, --repository.

Usage

export PROJECT_ID=my-project REGION=us-central1 REPOSITORY=main-registry
platforms/gcp/cloud-run/deploy-cloud-run.sh --dry-run todo-service   # print the gcloud/docker/pnpm commands
platforms/gcp/cloud-run/deploy-cloud-run.sh todo-service             # build, push, deploy
platforms/gcp/cloud-run/deploy-gcp.sh --all --service todo-service
platforms/gcp/cloud-run/cleanup-gcp.sh                               # report only
platforms/gcp/cloud-run/cleanup-gcp.sh --apply --delete-untagged-images

--dry-run prints every mutating gcloud command and the pnpm nx docker:build call prefixed with [dry-run], and skips read-only queries (secret existence, tag bindings); it assumes configured secrets already exist. In cleanup-gcp.sh the audit queries still run for real (the script is an audit) and only the mutating commands are printed.

Prerequisites: gcloud signed in to the project, Docker running, node, pnpm, and python3 for the cleanup script. After adding a runtime import to a service, run pnpm sync:deploy-deps <service> first: the bundle keeps npm packages external, and a missing one crashes the container with MODULE_NOT_FOUND.

What a deploy does

  1. Enables the Run, Artifact Registry and Secret Manager APIs and ensures the runtime service account exists.
  2. Applies the Artifact Registry cleanup policy to REPOSITORY (the repository must already exist).
  3. Syncs secrets (skipped with --skip-secret-sync): adds a version from each local source, creates missing secrets, applies labels and tags, and grants the runtime account roles/secretmanager.secretAccessor on every referenced secret.
  4. Logs Docker in to Artifact Registry and runs pnpm nx docker:build <service> with DOCKER_IMAGE_NAME, DOCKER_PLATFORMS=linux/amd64 and DOCKER_PUSH=true; the image is tagged latest and the package version.
  5. Runs gcloud run deploy. A revision that fails to start never gets traffic, so the old one keeps serving.

Service config

Each service owns cloud-run.config.sh, a bash file sourced by the deploy script. It sets only non-secret values:

VariableMeaning
SERVICE_PORTContainer port (default 3000)
SERVICE_ALLOW_UNAUTHENTICATEDtrue to pass --allow-unauthenticated (default false)
SERVICE_ENV_VARSArray of NAME=value plain env vars
SERVICE_SECRET_REFSArray of TARGET=SECRET:VERSION for --update-secrets; TARGET is an env var name, or a path (/secrets/key.json=SECRET:latest) to mount a file
SERVICE_ENV_SECRET_VALUESArray of ENV_NAME|SECRET_NAME: a new version of SECRET_NAME is added from $ENV_NAME in the environment or .env
SERVICE_FILE_SECRETSArray of SECRET_NAME|relative/path: a new version is added from that file in the repo (gitignored)
SERVICE_SECRET_LABELSArray of SECRET_NAME|key=value,key=value
SERVICE_SECRET_TAGSArray of SECRET_NAME|tagValues/123,tagValues/456
SERVICE_PORT=3000
SERVICE_ALLOW_UNAUTHENTICATED=true
SERVICE_ENV_VARS=("NODE_ENV=production" "LOG_LEVEL=info")
SERVICE_SECRET_REFS=("DATABASE_URI=DATABASE_URI:latest")
SERVICE_ENV_SECRET_VALUES=("DATABASE_URI|DATABASE_URI")

pnpm nx g @gentlemans-stack/nx-plugin:deployable-service <name> --platform=gcp --deploy=cloud-run writes this file for the service (port 3000, not public, NODE_ENV/LOG_LEVEL, and the Mongo URI as a secret when the service has a database) and adds a deploy target, so PROJECT_ID=... REGION=... REPOSITORY=... pnpm nx deploy <name> [--dry-run] runs deploy-cloud-run.sh. Without --deploy=cloud-run the generator writes nothing (the core assumes no cloud host); copy the shape above into the service. Secret values never go in the config; a secret you do not want a deploy to rotate (an encryption key, say) stays out of SERVICE_ENV_SECRET_VALUES and is pinned by version in SERVICE_SECRET_REFS (KEY=KEY:1), created once by hand:

openssl rand -base64 32 | gcloud secrets create BROKER_SECRET_KEY --project="$PROJECT_ID" --replication-policy=automatic --data-file=-

Keep an offline copy of such a key, never destroy a Secret Manager version that data was encrypted with, and give only project owners secretmanager.versions.destroy; the runtime account gets secretAccessor only, which the deploy script grants.

To check production secrets match your local files without printing values, compare hashes:

bash -c 'set -a; source .env; set +a; for s in DATABASE_URI; do [ "$(gcloud secrets versions access latest --secret=$s | shasum -a 256)" = "$(printf "%s" "${!s}" | shasum -a 256)" ] && echo "$s match" || echo "$s DIFFERENT"; done'

Cleanup

cleanup-gcp.sh without flags only reports: untagged images older than seven days, empty gcf-artifacts repositories, and old enabled versions of the named secrets. Destructive actions need --apply plus the specific flag (--delete-untagged-images, --delete-empty-repositories, --destroy-old-secret-versions). The newest enabled secret version and tagged images are never touched. The registry policy itself is asynchronous; --delete-untagged-images --apply deletes eligible images immediately.

Firebase Hosting in front (optional)

Cloud Run domain mappings are unavailable in some regions (they did not work in europe-west3). The workaround is Firebase Hosting sites that rewrite every request to the Cloud Run service, with the custom domain on the Hosting site. The Hosting config names only the service, so a Cloud Run redeploy needs no Hosting deploy; run firebase deploy --only hosting only when the hosting block of firebase.json changes. Keep the Hosting public directory empty so no static file shadows a route. Limits of the hop: requests time out after 60 seconds (Hosting's limit, not Cloud Run's); headers such as Authorization pass through but cookies other than __session are stripped; the CDN caches only responses with a public Cache-Control. A server calling another service server to server can use the run.app URL and skip the hop. Hosting is not scripted here.

Firebase credentials for the backend

For platforms/gcp/auth-firebase/admin, the service account key for the Firebase project lives gitignored at the repository root (path overridable in the service's own config) and is mounted from Secret Manager as a file via SERVICE_FILE_SECRETS and a path-style entry in SERVICE_SECRET_REFS. Never commit it. The /jwks provider needs no key.

Porting to .mjs later

The repo prefers plain-Node scripts (see the script-writer skill). A port would: replace lib.sh's run/query with one runCommand(argv) over execFileSync; replace the cloud-run.config.sh bash arrays with an exported object in a cloud-run.config.mjs (the one real change for services); replace the python3 JSON filtering in cleanup-gcp.sh with JSON.parse; and use scripts/lib/help.mjs for --help. The gcloud argument lists carry over unchanged.

On this page