Deployment Recipe: Google Cloud Run (Container / Serverless Target)
Support Tier: Tier 1 — Officially Tested & Supported Adapter
Target Platform: Google Cloud Run (Fully managed serverless container runtime) deploying immutable GitHub Container Registry (ghcr.io) OCI digests with GCP Secret Manager and Cloud SQL PostgreSQL (or external managed PostgreSQL).
Overview
Google Cloud Run provides a managed, serverless execution environment for containerized Next.js applications. It automatically scales containers from zero to handle incoming traffic, integrates natively with GCP Secret Manager, and connects securely to Cloud SQL via unix domain sockets or TCP.
1. Database Provisioning & Connection
Provisioning Options
- Google Cloud SQL (PostgreSQL 15+): Create a Cloud SQL instance in the same GCP region:bash
gcloud sql instances create wedding-db \ --database-version=POSTGRES_15 \ --tier=db-f1-micro \ --region=us-central1 gcloud sql databases create wedding_db --instance=wedding-db gcloud sql users create wedding_user --instance=wedding-db --password="STRONG_PASSWORD" - External Managed Database (Neon / Supabase): Create a database instance on Neon or Supabase and enable connection pooling.
Connection String Format
- Cloud SQL Unix Socket Connection (include
localhostas the authority host so Prisma CLI and runtime validation resolve the?host=/cloudsql/...socket path cleanly; legacy empty-host@/socket URIs are automatically normalized to@localhostat runtime and inprisma.config.ts):envDATABASE_URL="postgresql://wedding_user:STRONG_PASSWORD@localhost/wedding_db?host=/cloudsql/YOUR_PROJECT_ID:us-central1:wedding-db" - Direct TCP Connection (Neon / Supabase):env
DATABASE_URL="postgresql://wedding_user:STRONG_PASSWORD@ep-example.us-east-1.aws.neon.tech/wedding_db?sslmode=require"
2. Cloud Run Secrets & Service Configuration
For the complete environment variable matrix, defaults, and persisted prisma/schema.prisma entity rules, refer to the Application Runtime Contract. On Cloud Run, attach sensitive values from GCP Secret Manager (--set-secrets) and pass non-secret routing flags via --set-env-vars:
- GCP Secret Manager Secrets (
--set-secrets):- Core Credentials:
DATABASE_URL(Cloud SQL socket or external PostgreSQL URL bound todatasource.urlinprisma.config.ts),ADMIN_PASSWORD(scrypt:[saltBase64]:[keyBase64]),GUEST_PASSCODE, andGUEST_SESSION_SECRET(32+ characters, distinct fromGUEST_PASSCODE). IfDATABASE_URLroutes through PgBouncer, store a direct PostgreSQL URL (DATABASE_URL_DIRECTorPOSTGRES_URL_NON_POOLINGperprisma.config.ts) to pass as an explicitDATABASE_URLoverride duringprisma migrate deploy. - Object Storage (Required for Uploads): Because Cloud Run container filesystems are ephemeral and read-only, configure
S3_BUCKET,S3_REGION,S3_ACCESS_KEY_ID, andS3_SECRET_ACCESS_KEY(plus optionalS3_ENDPOINTandS3_PUBLIC_URLfor Cloudflare R2 or GCS S3 Interop). - Optional Integrations:
STRIPE_SECRET_KEYandSTRIPE_WEBHOOK_SECRET(when enabling card checkout), andCRON_SECRET(when scheduling/api/cron/broadcastsvia Cloud Scheduler).
- Core Credentials:
- Cloud Run Service Environment Variables (
--set-env-vars):- Set
NODE_ENV=production,ALLOWED_HOSTS(including your custom domain and*.run.app; read-onlyGETandHEADprobes to/api/live,/api/health, and/api/readyenforce syntacticHostvalidation only, so internal Cloud Run pod-IP probes require no extraALLOWED_HOSTSentries),TRUST_PROXY=2(so rate limiting resolves client IPs across Google Cloud external load balancer and Cloud Run ingress hops), and optionalNEXT_PUBLIC_STRIPE_PUBLISHABLE_KEYwhen paired withSTRIPE_SECRET_KEY.
- Set
3. Migration Mechanism
Automated schema migrations are performed before traffic is shifted to new Cloud Run container revisions.
Primary Migration Path: Automated GitHub Actions CI/CD Pipeline
In the release pipeline (.github/workflows/deploy.yml), preflight checks (ci-gate, schema-compatibility) and container publication (publish-artifact) run without acquiring environment locks, and each environment stage is delegated to the reusable stage workflow (.github/workflows/deploy-stage.yml). deploy-stage.yml holds a unified per-environment concurrency lock (deploy-env-${{ inputs.environment }} with cancel-in-progress: false and queue: max) across database migration (.github/workflows/db-migrate.yml), provider rollout (.github/workflows/deploy-provider.yml), /api/health and /api/ready verification, and conditional rollback (.github/workflows/rollback.yml):
- Staging Tier (
staging->deploy-stage.yml): Acquiresdeploy-env-staging(queue: max) automatically after release artifacts are published (publish-artifact) and pre-deployment schema compatibility checks pass (schema-compatibility), without waiting on pendingproductionreviewer approvals. Insidedeploy-stage.yml,database-migration(caller_holds_lock: true) applies pending schema migrations to the isolated staging database beforedeploy-providerupdates the staging Cloud Run container revision andverify-deploymentruns automated/api/healthand/api/readyprobes (.github/workflows/deploy-stage.yml). - Production Tier (
production->deploy-stage.yml): Acquiresdeploy-env-production(queue: max) and pauses at the mandatory GitHub Environment reviewer approval gate (environment: productionin.github/workflows/db-migrate.yml) while queuing up to 100 subsequent runs in FIFO order without canceling superseded runs. Before approval, maintainers review the offlinegit diffSQL DDL summary generated byschema-compatibility(NOT QUERIED) and the live staging migration/health check results; once approved,db-migrate.yml(caller_holds_lock: true) queries live productionDATABASE_URLvianpx tsx scripts/preflight-migration-summary.ts --require-db(npx prisma migrate status) and executesnpx prisma migrate deploybeforedeploy-providershifts live traffic to the new Cloud Run revision (.github/workflows/deploy-stage.yml). - Unified Standalone & Rollback Serialization: Standalone dispatches of
db-migrate.yml,deploy-provider.yml, androllback.yml(caller_holds_lock: false) acquire the samedeploy-env-<environment>lock (queue: max) keyed on targetenvironmentrather thanrollback_environment, ensuring manualproduction-rollbackruns serialize against activeproductiondeployments while passingcaller_holds_lock: trueto nested workflows to avoid nested lock contention.
For full architectural diagrams and operational guidance, refer to the canonical release documentation in DEPLOYMENT.md: Continuous Delivery Pipeline Architecture and DEPLOYMENT.md: Staging Promotion & Approval Workflow.
# .github/workflows/deploy.yml — Stage caller jobs (preflight jobs run unlocked)
staging:
name: Staging Deployment Stage
permissions:
actions: read
contents: read
packages: read
attestations: read
deployments: write
id-token: write
needs: [ci-gate, publish-artifact, schema-compatibility]
if: |
!cancelled() &&
(
(
github.event_name == 'workflow_run' &&
github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.event == 'push' &&
github.event.workflow_run.head_repository.full_name == github.repository
) ||
(
(github.event_name == 'workflow_dispatch' || github.event_name == 'workflow_call') &&
(inputs.environment == 'all' || inputs.environment == 'staging' || inputs.environment == '')
)
) &&
(needs.ci-gate.result == 'success') &&
(needs.schema-compatibility.result == 'success') &&
(needs.publish-artifact.result == 'success' || ((inputs.image_digest != '' || inputs.image_tag != '' || inputs.release_ref != '') && needs.publish-artifact.result == 'skipped'))
uses: ./.github/workflows/deploy-stage.yml
with:
environment: 'staging'
commit_sha: ${{ needs.ci-gate.outputs.target_sha }}
image_digest: ${{ inputs.image_digest || needs.publish-artifact.outputs.image_digest }}
image_tag: ${{ inputs.image_tag || needs.publish-artifact.outputs.image_tag || needs.ci-gate.outputs.target_sha }}
previous_tag: ${{ inputs.previous_tag || '' }}
provider: ${{ inputs.provider || 'google-cloud-run' }}
cloud_run_service: ${{ inputs.cloud_run_service || '' }}
cloud_run_region: ${{ inputs.cloud_run_region || '' }}
rollback_environment: ${{ (github.event_name == 'workflow_call' && inputs.rollback_environment) || vars.STAGING_ROLLBACK_ENVIRONMENT || '' }}
dry_run: ${{ inputs.dry_run || false }}
secrets:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
POSTGRES_URL_NON_POOLING: ${{ secrets.POSTGRES_URL_NON_POOLING }}
GCP_SA_KEY: ${{ secrets.GCP_SA_KEY }}
GCP_PROJECT_ID: ${{ secrets.GCP_PROJECT_ID }}
DEPLOY_WEBHOOK_URL: ${{ secrets.DEPLOY_WEBHOOK_URL }}
DEPLOY_WEBHOOK_SECRET: ${{ secrets.DEPLOY_WEBHOOK_SECRET }}
SERVICE_URL: ${{ secrets.SERVICE_URL }}
production:
name: Production Deployment Stage
permissions:
actions: read
contents: read
packages: read
attestations: read
deployments: write
id-token: write
needs: [ci-gate, publish-artifact, schema-compatibility, staging]
if: |
!cancelled() &&
(
(
github.event_name == 'workflow_run' &&
github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.event == 'push' &&
github.event.workflow_run.head_repository.full_name == github.repository
) ||
(
(github.event_name == 'workflow_dispatch' || github.event_name == 'workflow_call') &&
(inputs.environment == 'all' || inputs.environment == 'production' || inputs.environment == '')
)
) &&
(needs.ci-gate.result == 'success') &&
(needs.schema-compatibility.result == 'success') &&
(needs.publish-artifact.result == 'success' || ((inputs.image_digest != '' || inputs.image_tag != '' || inputs.release_ref != '') && needs.publish-artifact.result == 'skipped')) &&
(inputs.environment == 'production' || needs.staging.result == 'success')
uses: ./.github/workflows/deploy-stage.yml
with:
environment: 'production'
commit_sha: ${{ needs.ci-gate.outputs.target_sha }}
image_digest: ${{ inputs.image_digest || needs.publish-artifact.outputs.image_digest }}
image_tag: ${{ inputs.image_tag || needs.publish-artifact.outputs.image_tag || needs.ci-gate.outputs.target_sha }}
previous_tag: ${{ inputs.previous_tag || '' }}
provider: ${{ inputs.provider || 'google-cloud-run' }}
cloud_run_service: ${{ inputs.cloud_run_service || '' }}
cloud_run_region: ${{ inputs.cloud_run_region || '' }}
rollback_environment: ${{ (github.event_name == 'workflow_call' && inputs.rollback_environment) || vars.PRODUCTION_ROLLBACK_ENVIRONMENT || '' }}
dry_run: ${{ inputs.dry_run || false }}
secrets:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
POSTGRES_URL_NON_POOLING: ${{ secrets.POSTGRES_URL_NON_POOLING }}
GCP_SA_KEY: ${{ secrets.GCP_SA_KEY }}
GCP_PROJECT_ID: ${{ secrets.GCP_PROJECT_ID }}
DEPLOY_WEBHOOK_URL: ${{ secrets.DEPLOY_WEBHOOK_URL }}
DEPLOY_WEBHOOK_SECRET: ${{ secrets.DEPLOY_WEBHOOK_SECRET }}
SERVICE_URL: ${{ secrets.SERVICE_URL }}
# .github/workflows/deploy-stage.yml — Reusable per-environment lock & sequential jobs
concurrency:
group: deploy-env-${{ inputs.environment }}
cancel-in-progress: false
queue: max
jobs:
database-migration:
uses: ./.github/workflows/db-migrate.yml
with:
environment: ${{ inputs.environment }}
commit_sha: ${{ inputs.commit_sha }}
confirm: true
caller_holds_lock: true
secrets:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
POSTGRES_URL_NON_POOLING: ${{ secrets.POSTGRES_URL_NON_POOLING }}
deploy-provider:
permissions:
actions: read
contents: read
packages: read
attestations: read
deployments: write
id-token: write
needs: [database-migration]
if: "!cancelled() && needs.database-migration.result == 'success'"
uses: ./.github/workflows/deploy-provider.yml
with:
environment: ${{ inputs.environment }}
commit_sha: ${{ inputs.commit_sha }}
image_digest: ${{ inputs.image_digest }}
image_tag: ${{ inputs.image_tag || inputs.commit_sha }}
provider: ${{ inputs.provider || 'google-cloud-run' }}
cloud_run_service: ${{ inputs.cloud_run_service || '' }}
cloud_run_region: ${{ inputs.cloud_run_region || '' }}
dry_run: ${{ inputs.dry_run || false }}
caller_holds_lock: true
secrets:
GCP_SA_KEY: ${{ secrets.GCP_SA_KEY }}
GCP_PROJECT_ID: ${{ secrets.GCP_PROJECT_ID }}
DEPLOY_WEBHOOK_URL: ${{ secrets.DEPLOY_WEBHOOK_URL }}
DEPLOY_WEBHOOK_SECRET: ${{ secrets.DEPLOY_WEBHOOK_SECRET }}
SERVICE_URL: ${{ secrets.SERVICE_URL }}Production Reviewer Approval Gate & Promotion
To safeguard live user traffic and database integrity, production database migrations and container deployments are gated by GitHub Environment protection rules, isolated Cloud Run targets, per-environment FIFO concurrency locks, and cryptographic OIDC provenance verification:
- Automated Staging Delivery & Preflight Gate: Merging to
maintriggers schema backwards compatibility validation (npm run lint:migrations) and generates an offlinegit diffPre-Flight Schema Migration Status & SQL DDL Summary (NOT QUERIED) fromprisma/migrations/againstHEAD^1in$GITHUB_STEP_SUMMARY(schema-compatibilityrunsnode --experimental-strip-types scripts/preflight-migration-summary.ts --offlineon Node.js 22 withoutnpm ciorDATABASE_URL).publish-artifactbuilds and signs the multi-arch container image onghcr.io(queue: max), and thestagingstage (deploy-stage.ymlholdingdeploy-env-staging) runsdatabase-migrationagainst stagingDATABASE_URLanddeploy-provider(verifying OIDC provenance viagh attestation verifyagainst.github/workflows/publish-artifact.ymlbefore deploying the immutableghcr.io/<owner>/<repo>@sha256:<hex>digest to the isolated staging Cloud Run servicewedding-website-stagingby default, orvars.CLOUD_RUN_SERVICEinvars.CLOUD_RUN_REGION). - Mandatory Human Sign-Off: The
productionstage invokes.github/workflows/deploy-stage.yml(deploy-env-production,queue: max), whosedatabase-migrationjob delegates to.github/workflows/db-migrate.ymlconfigured withenvironment: production. GitHub Actions pauses the job before exposing production secrets without preventing subsequent merges from building or deploying tostaging. Maintainers review the offline preflight DDL diff summary and live staging health check outcome before approving the deployment; after approval,db-migrate.ymlaudits live productionDATABASE_URL(npx tsx scripts/preflight-migration-summary.ts --require-dbrunningnpx prisma migrate status), fails closed on connectivity errors, schema drift, or failed migrations, emits the live pending DDL summary, and runsnpx prisma migrate deploy, after whichdeploy-providerre-verifies OIDC provenance for the exactimage_digestvalidated in staging before updating the production Cloud Run service (wedding-websiteby default, orvars.CLOUD_RUN_SERVICEinvars.CLOUD_RUN_REGION). - Automated Rollback Guarantee:
.github/workflows/deploy.ymland.github/workflows/deploy-stage.ymlpropagatecommit_sha(needs.ci-gate.outputs.target_sha),caller_holds_lock: true, minimal explicit provider secrets (isolatingDATABASE_URLandPOSTGRES_URL_NON_POOLINGstrictly todb-migrate.yml), and job-scopedactions: readanddeployments: writepermissions to.github/workflows/deploy-provider.ymland.github/workflows/rollback.yml. Before updating the Cloud Run service,.github/workflows/deploy-provider.ymlruns a read-onlypreflightjob (fetch-depth: 0, OIDC provenance verification viascripts/resolve-oci-provenance.sh, passingci.ymlcheck for the signedsource_revision, standalone liveorigin/mainancestry anddb-migrate.ymlverification, andnpm run lint:migrationsvia.nvmrc) followed by a checkout-freedeployjob (timeout-minutes: 20with bounded step timeouts on forward rollouts and/api/health+/api/readyprobes) that inspects the currently serving Cloud Run revision image in the resolved service and region (capturingprevious_image_digestand extractingprevious_image_tagfrom@sha256:revision OIDC provenance attestations and attested OCIorg.opencontainers.image.revisionmetadata, Cloud Runcommit-shalabels, environment-isolated GitHub Deployments withsuccessstatus, completed non-dry_runtarget-environmentdeploy.ymlnesteddeploy-stage.yml/ legacy jobs anddeploy-provider.ymlruns, or GHCR-published releases verified viadocker buildx imagetools inspectandHEAD^1/ commit parents relative tocommit_shawhile skipping unpublishedHEAD^1commits).deploy-provider.ymlcreates each GitHub Deployment (refandpayload.commit_shaset tosource_revision/target_sha) withstate: "in_progress"(auto_inactive: false) before polling${TARGET_URL}/api/healthand${TARGET_URL}/api/ready(curl --connect-timeout 5 --max-time 10,timeout-minutes: 4, resolvingvars.SERVICE_URL, Cloud Run URL, and legacysecrets.SERVICE_URLin memory without leaking secrets to$GITHUB_OUTPUT), transitioning tostate: "success"(auto_inactive: true) only after/api/healthreturnsHTTP 200with.data.status == "ok"and.data.database == "connected"and/api/readyreturnsHTTP 200withstatus == "ready"anddatabase == "connected"(orstate: "failure"viaif: always()on failure/cancellation). Whenrollback_environmentis unset (auto_rollback_on_failure: true),deploy-provider.ymlrestores the prior attested image directly inside the approved 20-minutedeployjob budget (afterpreflightalready verifiednpm run lint:migrations: priorsuccessdeployment check,gh attestation verifyresolving OCIorg.opencontainers.image.revisionand SLSAinputs.commit_shaahead of OIDCGITHUB_SHAdigests,/api/healthand/api/readyprobes,inline_rollback_completed=true, andexit 1) without a second reviewer gate anddeploy-stage.ymlskipsrollback.yml. When an unguardedrollback_environment(e.g.,production-rollback, configured without Required Reviewers, settingSERVICE_URL,CLOUD_RUN_SERVICE,CLOUD_RUN_REGION, and Workload Identity Federation variablesGCP_WORKLOAD_IDENTITY_PROVIDER/GCP_SERVICE_ACCOUNTviavars.*, or holding fallbackGCP_SA_KEY,GCP_PROJECT_ID,DEPLOY_WEBHOOK_URL, andDEPLOY_WEBHOOK_SECRET) is configured orinline_rollback_completedis nottrue(such as after cancellation),.github/workflows/deploy-stage.ymltriggers.github/workflows/rollback.yml(caller_holds_lock: true) while continuing to holddeploy-env-<environment>.rollback.ymlevaluatesif: always()with upstream job and step outcome guards acrosspreflight,redeploy,verify, andreport, scopescommit_shastrictly topreflight(rejecting mutablelatestor self-rollback againstcommit_shavia attested OCIorg.opencontainers.image.revision/ SLSA provenance, verifying a priorsuccessdeployment intarget_environment, and runningnpm run lint:migrations), redeploys the previous image viadeploy-provider.yml(caller_holds_lock: true,is_rollback: true, stamping the restored image's attestedsource_revision) without requiring a second human approval gate, and consumeshealth_statusandhttp_statusfromdeploy-provider.yml(with fallback${SERVICE_URL}/api/healthpolling forHTTP 200,.data.status == "ok",.data.database == "connected"and${SERVICE_URL}/api/readypolling forHTTP 200,status == "ready",database == "connected", allowing extra forwardN+1migrations in_prisma_migrationsduringN-1rollbacks) without gatingverifyonproductionbefore reportingSUCCESS.
Workflow Parameters, Manual Dispatches & Preflight Checks
The release pipeline supports automated merges as well as manual triggers via GitHub Actions workflow_dispatch:
- Release Pipeline Manual Dispatches (
deploy.yml):environment: Target deployment scope:all(default): Executes staging migration and deployment (deploy-stage.ymlwithdeploy-env-staging), validates staging health, halts for the mandatory production reviewer approval gate (deploy-stage.ymlwithdeploy-env-production), and promotes the identicalsha256digest to production.staging: Dispatches only thestagingstage (deploy-stage.yml), validating changes in the staging environment without promoting to production.production: Directly targets theproductionstage (deploy-stage.yml), bypassing staging and immediately routing to the mandatory production approval gate.
image_digest: Optional immutable OCI image digest (sha256:<64-hex>) allowing production-only or manual runs to pin an existing attested artifact without rebuildingmainHEAD.ci-gateverifies the digest's OIDC build provenance attestation (gh attestation verify --format jsonsigned by.github/workflows/publish-artifact.yml, falling back toorg.opencontainers.image.revisionmetadata) to resolvetarget_shaand checks out that exact release commit inschema-compatibilityanddb-migrate.yml.image_tag: Optional immutable release tag (v*, resolved to itsorigin/mainor OIDC-attestedN-1release/*maintenancetarget_shacommit for CI,schema-compatibility, anddb-migrate.ymlverification) or commit SHA allowing manual runs to promote an existing attested release tag without rebuildingHEAD.release_ref: Optional immutablev*release tag (e.g.,v0.1.0) or 40-character commit SHA to promote after newer commits have landed onmain(mutablelatestand arbitrary branch names are rejected; reusableworkflow_callcallers may also passcommit_sha).ci-gateresolvesrelease_refto its 40-charactertarget_shavia the GitHub Commits API / git tags and verifies viascripts/verify-release-target.shthattarget_shadescends fromorigin/main(or matches an OIDC-attestedrefs/tags/v*maintenance release signed bypublish-artifact.yml) with a passingci.ymlrun, whilestagingandproductionforwardrelease_refas theimage_tagfallback wheninputs.image_tagis empty soci-gate,schema-compatibility,db-migrate.yml, anddeploy-provider.ymlexecute against the exact tag commit rather thanmainHEAD.provider: Hosting provider adapter (defaults togoogle-cloud-run).cloud_run_service/cloud_run_region: Optional Cloud Run service and region overrides forwarded acrossdeploy-provider.ymlandrollback.yml.previous_tag: Optional immutable container image tag override for automated rollback if health checks fail (defaults toprevious_image_digest/previous_image_tagcaptured before rollout bydeploy-provider.yml; mutablelatestand the failingcommit_sha/github.shaare rejected outside explicit dry-run mode).rollback_environment(workflow_callonly ondeploy.ymlanddeploy-provider.yml; configured for automated/manual promotions via repository variablesPRODUCTION_ROLLBACK_ENVIRONMENT/STAGING_ROLLBACK_ENVIRONMENTand accepted onrollback.ymlworkflow_dispatch): Optional unguarded GitHub Environment name (e.g.,production-rollback) used byrollback.ymlanddeploy-provider.ymlduringworkflow_callrollbacks to resolve provider secrets andvars.SERVICE_URL(secrets.SERVICE_URLlegacy fallback) without pausing onproductionreviewer gates.
- Standalone Provider & Rollback Dispatches (
deploy-provider.yml&rollback.yml):- Accepts
image_digest(sha256:<64-hex>) or an immutable release/commitimage_tag(unpinnedlatestdefaults are rejected), optionalsource_ref(refs/heads/mainorrefs/tags/v*), optional 40-character hexadecimalcommit_sha(aligned automatically tosteps.provenance.outputs.source_revisionon non-rollback runs when omitted), optionalcloud_run_service,cloud_run_region, and explicitdry_run(falseby default; missing credentials fail closed rather than entering dry-run mode), with job-scopedactions: readanddeployments: writepermissions on deployment and caller jobs. Tag-only dispatches are resolved to an immutablesha256digest viadocker buildx imagetools inspect, validated against^sha256:[a-f0-9]{64}$, and verified withgh attestation verify(--owner,--signer-workflow, and--source-ref) plusscripts/verify-release-target.sh(origin/mainancestry or OIDC-attestedrefs/tags/v*maintenance provenance, paginated trustedci.ymllatest-runsuccessstatus via--ci-only, and detachedHEADparent history forcapture-previous) andstandalone-gatetarget-environmentdb-migrate.yml/deploy.ymlverification (exclude_pull_requests: true, non-nullhead_repository, omittinghead_shafilters onworkflow_dispatchruns and requiringExecute Database Migrationsto succeed onVerify Manual Migration Confirmation,Record Target Environment (<env>), andRecord Migrated Commit (<target_sha>)) prior to Cloud Run rollout (rollback.ymlpreflightalso verifies thatprevious_digest/previous_tagdoes not matchCURRENT_SHAand succeeded earlier intarget_environmentGitHub Deployments beforeredeploystarts, andinline-rollbackenforces paginated trustedci.ymlchecks). - Exports
service_url,is_dry_run,previous_image_tag,previous_image_digest,image_digest,image_uri,attestation_status,cloud_run_service, andcloud_run_regionoutputs and records them in$GITHUB_STEP_SUMMARYand GitHub Deployments.
- Accepts
- Standalone Database Migration Dispatches (
db-migrate.yml):- Operators can also invoke the reusable migration workflow directly if an out-of-band schema migration is required. Manual
workflow_dispatchruns defaultconfirmtofalseand run a read-onlypreflightgate (scripts/verify-release-target.sh) beforemigrate(npm ci --ignore-scripts), aborting before unlockingsecrets.DATABASE_URLor touching PostgreSQL unlessconfirm: trueis set and the target commit is a verifiedorigin/mainancestor (or OIDC-attestedrefs/tags/v*maintenance release) with a passing trustedci.ymlrun, and recordingRecord Migrated Commit (<target_sha>)afternpx prisma migrate deploysostandalone-gateindeploy-provider.ymlmatches exact migrated commits even aftermainadvances.
- Operators can also invoke the reusable migration workflow directly if an out-of-band schema migration is required. Manual
- Workflow Secrets:
DATABASE_URL(Required bydb-migrate.yml): Mandatory PostgreSQL connection string scoped to the respective GitHub Environment (stagingorproduction). Must start withpostgres://orpostgresql://. Becauseprisma.config.tsbindsdatasource.urltoDATABASE_URL,npx prisma migrate deployalways readsDATABASE_URL; when runtime traffic uses PgBouncer or Neon/Supabase transaction pooling, set the GitHub EnvironmentDATABASE_URLsecret to the direct, non-pooled PostgreSQL URL as an explicitDATABASE_URLoverride.
- Preflight Schema Compatibility Linting: Executes
npm run lint:migrationsprior to running migrations. The linter validates all migration SQL inprisma/migrations/to prevent unannotated destructive operations (such asDROP TABLEorDROP COLUMN). Destructive DDL statements must be explicitly annotated with-- allow-destructive: <reason>. - Database Status & Schema Drift Detection: Runs
npx tsx scripts/preflight-migration-summary.ts --require-db(npx prisma migrate status) against the target database after manual confirmation to check for unapplied migrations and fail closed with redacted diagnostics on connectivity errors (P1001), diverged history / schema drift, or failed migration records before applying new changes. - Execution Timeouts: Executes
npx prisma migrate deploywith guarded session options (PGOPTIONS: "-c lock_timeout=5000ms -c statement_timeout=30000ms") to prevent long lock acquisition or stalled transactions from blocking deployment pipelines.
Migration Failure Diagnostic & Recovery Procedures
If the migration step fails during preflight linting or DDL execution, the deployment pipeline halts immediately to prevent deploying application code against an inconsistent database schema.
Diagnostic Steps:
- Preflight Linter Failure (
lint:migrations): Inspect workflow logs for destructive schema changes. If the schema change is intentional, annotate the migration SQL file inprisma/migrations/with-- allow-destructive: <reason>. - Database Connectivity & Status Failure: Check target database network connectivity, verify that
DATABASE_URLmatches the requiredpostgres(ql)://URI scheme, and checknpx prisma migrate statusoutput for schema drift or failed migration records. - Deploy & Timeout Failures: Review execution logs for Prisma error codes, PostgreSQL statement timeout (
30000ms), or table lock timeout (5000ms) failures caused by concurrent database traffic.
Remediation & Rollback Commands: When a migration fails midway or becomes marked as failed in the database:
- Inspect the
_prisma_migrationstable in your target PostgreSQL database to identify the failed migration record. - Resolve the migration state using the Prisma CLI from your administrative environment:bashNote: The migration name must match the exact directory name recorded in the
# Mark a failed migration as rolled back: npx prisma migrate resolve --rolled-back "<failed_migration_name>" # OR mark a migration as applied if changes were manually verified: npx prisma migrate resolve --applied "<failed_migration_name>"_prisma_migrationstracking table (e.g.20260101000000_init). - Re-run the database migration workflow or deployment pipeline only after confirming that the database state is healthy.
- Do not bypass migration errors or force-deploy the Cloud Run service revision while the schema is in a failed state.
Secondary Migration Path: Cloud Run Job
Alternatively, execute a single-use Cloud Run Job pinned to an immutable ghcr.io image digest before updating the wedding-website service revision:
IMAGE_DIGEST="sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
gcloud run jobs create wedding-migrate \
--image="ghcr.io/fderuiter/wedding_website@${IMAGE_DIGEST}" \
--args="./node_modules/.bin/prisma,migrate,deploy" \
--set-cloudsql-instances=YOUR_PROJECT_ID:us-central1:wedding-db \
--set-secrets="DATABASE_URL=DATABASE_URL_DIRECT:latest" \
--region=us-central1
gcloud run jobs execute wedding-migrate --region=us-central1 --waitNote: Omitting --command preserves the container ENTRYPOINT (/usr/bin/tini -s -- docker-entrypoint.sh), which validates DATABASE_URL, normalizes and preserves non-empty POSTGRES_URL_NON_POOLING (unsetting blank values), and invokes ./node_modules/.bin/prisma migrate deploy (/usr/local/bin/prisma) offline without npx or npm registry traffic. Attach --set-cloudsql-instances when connecting via Cloud SQL Auth Proxy Unix sockets (omit if using an external TCP PostgreSQL host), and bind DATABASE_URL in the Cloud Run Job to a direct, non-pooling PostgreSQL secret (DATABASE_URL_DIRECT or DATABASE_URL if already unpooled) as an explicit DATABASE_URL override to bypass PgBouncer.
4. Asset Storage
Cloud Run containers have ephemeral, read-only root filesystems. Persistent asset storage must use S3-compatible object storage (Cloudflare R2, AWS S3, or Google Cloud Storage with S3 Interoperability enabled):
- Create a Google Cloud Storage bucket, Cloudflare R2 bucket, or AWS S3 bucket.
- Enable Cloud Storage S3 Interoperability (HMAC keys) or generate Cloudflare R2 / AWS S3 API credentials.
- Configure the six
S3_*variables (S3_BUCKET,S3_REGION,S3_ACCESS_KEY_ID,S3_SECRET_ACCESS_KEY,S3_ENDPOINT, andS3_PUBLIC_URL) in GCP Secret Manager / Cloud Run environment settings:- Google Cloud Storage (S3 Interoperability): Set
S3_BUCKET,S3_REGION=us-central1(matching your bucket region),S3_ACCESS_KEY_ID,S3_SECRET_ACCESS_KEY,S3_ENDPOINT=https://storage.googleapis.com, and optionalS3_PUBLIC_URL. - Cloudflare R2: Set
S3_BUCKET,S3_REGION=auto,S3_ACCESS_KEY_ID,S3_SECRET_ACCESS_KEY,S3_ENDPOINT=https://<ACCOUNT_ID>.r2.cloudflarestorage.com, andS3_PUBLIC_URL=https://assets.wedding.mydomain.com(an R2 Custom Domain or publichttps://pub-<id>.r2.devURL; private*.r2.cloudflarestorage.comendpoints requireS3_PUBLIC_URL). - AWS S3: Set
S3_BUCKET,S3_REGION,S3_ACCESS_KEY_ID, andS3_SECRET_ACCESS_KEY(withS3_ENDPOINTomitted andS3_PUBLIC_URLoptional for CloudFront).
- Google Cloud Storage (S3 Interoperability): Set
5. Custom Domain & TLS
Google Cloud Run provides free, automatically managed TLS certificates for custom domains.
Step-by-step Domain Setup
- Navigate to Cloud Run > Domain Mappings in Google Cloud Console.
- Click Add Mapping, select your Cloud Run service (
wedding-website), and enter your domain (e.g.wedding.mydomain.com). - Add the generated
CNAMEorA/AAAADNS records at your domain registrar. - Google automatically provisions and renews an SSL/TLS certificate via Let's Encrypt / Google Trust Services.
6. Build & Deploy Commands
Automated Deployment via GitHub Actions
The repository includes .github/workflows/deploy.yml, .github/workflows/deploy-stage.yml, .github/workflows/publish-artifact.yml, .github/workflows/db-migrate.yml, .github/workflows/deploy-provider.yml, and .github/workflows/rollback.yml. Automated staging-to-production releases (deploy.yml) trigger via workflow_run after CI succeeds on main pushes (or via workflow_dispatch with optional image_tag, release_ref, or image_digest, resolving target_sha from the artifact's signed source revision or tag commit, diffing offline pre-approval SQL migrations in schema-compatibility against the active environment GitHub Deployment BASE_SHA via deployments: read with push activity fallback, and aligning CI verification, schema-compatibility, and db-migrate.yml to that exact revision); .github/workflows/ci.yml runs on pull requests, merge_group, workflow_dispatch, and pushes to main and release/** without v* tag triggers, while pushing a v* tag triggers publish-artifact.yml directly without re-running ci.yml (publish-artifact.yml fetches origin/main, origin/release/*, and refs/tags/v*, verifies origin/main ancestry or N-1 origin/release/* maintenance tag lineage descending from a matching vMAJOR.MINOR.* tag on an advanced origin/main, polls active trusted ci.yml runs and requires the latest completed trusted CI run to succeed via scripts/verify-release-target.sh, promotes the already-attested ghcr.io/<owner>/<repo>:<sha> multi-platform digests directly when verified—falling back to native matrix builds if absent—before publishing ghcr.io/<owner>/<repo>:<GITHUB_REF_NAME> such as :v0.1.0 alongside ghcr.io/<owner>/<repo>:<sha>, recording org.opencontainers.image.revision in the multi-platform OCI index before signing provenance, and updating :latest only when an origin/main stable SemVer tag equals or exceeds every stable repository version tag while forcing PUBLISH_LATEST=false outside origin/main and omitting :latest on manual dispatches, main commit builds, pre-release tags, and N-1 maintenance patches) without automatically invoking deploy.yml. Tagged artifacts can then be promoted via deploy.yml (image_tag: v0.1.0, release_ref: v0.1.0, or image_digest, resolving target_sha to the tag commit and running schema-compatibility and db-migrate.yml first before deploy-provider.yml), deploy-provider.yml (image_tag: v0.1.0 after db-migrate.yml records Record Migrated Commit (<target_sha>)), or manual CLI deployment below:
- GitHub Environment Variables (
staging,production, and optionalproduction-rollback):SERVICE_URL: Public base URL of the Cloud Run service for post-deploy and post-rollback/api/healthand/api/readyverification (vars.SERVICE_URLprimary so job outputs and deployment summaries remain unmasked;secrets.SERVICE_URLis supported as a legacy fallback during migration).CLOUD_RUN_SERVICE: Target Cloud Run service name for the environment (defaults towedding-website-staginginstagingandwedding-websiteinproduction, allowing isolated staging and production services within a single shared GCP project).CLOUD_RUN_REGION: Target Cloud Run region for revision capture and deployment (defaults tous-central1).GCP_WORKLOAD_IDENTITY_PROVIDER: Primary keyless OIDC Workload Identity Federation provider resource (projects/<project-number>/locations/global/workloadIdentityPools/<pool>/providers/<provider>), used bygoogle-github-actions/authwith job-scopedid-token: write.GCP_SERVICE_ACCOUNT: Google Cloud Service Account email (<sa>@<project-id>.iam.gserviceaccount.com) impersonated via Workload Identity Federation.
- GitHub Environment Secrets (
staging,production, and optionalproduction-rollbackwithoutDATABASE_URL):GCP_SA_KEY: Optional legacy Google Cloud Service Account JSON Key fallback (credentials_json) whenGCP_WORKLOAD_IDENTITY_PROVIDERandGCP_SERVICE_ACCOUNTare not configured. Live runs fail closed when neither Workload Identity Federation norGCP_SA_KEYis present.GCP_PROJECT_ID: Optional Google Cloud Project ID override fordeploy-provider.yml(automatically inferred from Workload Identity /GCP_SERVICE_ACCOUNTorGCP_SA_KEYwhen omitted).DATABASE_URL: Direct (non-pooled) PostgreSQL connection string required bydb-migrate.ymlinstagingandproduction.
- GCP Secret Manager Runtime Secrets (mounted onto the
wedding-website-stagingandwedding-websiteCloud Run services, not stored in GitHub Actions):DATABASE_URL,ADMIN_PASSWORD(scrypt:[saltBase64]:[keyBase64]),GUEST_PASSCODE(unique non-default passcode), andGUEST_SESSION_SECRET(at least 32 characters and distinct fromGUEST_PASSCODEpersrc/env.ts).
Manual CLI Deployment
.github/workflows/publish-artifact.yml publishes multi-arch OCI images and OIDC build provenance attestations to ghcr.io (and docker.io when Docker Hub secrets are configured), and .github/workflows/deploy-provider.yml rejects mutable :latest tags while enforcing --source-ref, ci.yml, and db-migrate.yml status. Always deploy wedding-website-staging (staging) and wedding-website (production) using a verified immutable ghcr.io @sha256: digest and mount GUEST_SESSION_SECRET alongside the other production secrets:
# 1. Authenticate with GCP via interactive gcloud login (or service account key fallback GCP_SA_KEY)
gcloud auth activate-service-account --key-file="$GCP_SA_KEY"
gcloud config set project YOUR_PROJECT_ID
# 2. Resolve and verify the immutable ghcr.io OCI digest and OIDC source-ref for a release tag
RELEASE_TAG="v0.1.0"
IMAGE_DIGEST=$(docker buildx imagetools inspect --format '{{.Manifest.Digest}}' "ghcr.io/fderuiter/wedding_website:${RELEASE_TAG}")
gh attestation verify "oci://ghcr.io/fderuiter/wedding_website@${IMAGE_DIGEST}" \
--owner fderuiter \
--signer-workflow fderuiter/wedding_website/.github/workflows/publish-artifact.yml \
--source-ref "refs/tags/${RELEASE_TAG}"
# 3a. Deploy digest-pinned container revision to isolated staging Cloud Run service wedding-website-staging
# Use gcloud custom delimiter syntax (`^|^`) so commas inside ALLOWED_HOSTS are not parsed as new env var keys
gcloud run deploy wedding-website-staging \
--image="ghcr.io/fderuiter/wedding_website@${IMAGE_DIGEST}" \
--platform=managed \
--region=us-central1 \
--allow-unauthenticated \
--add-cloudsql-instances=YOUR_PROJECT_ID:us-central1:wedding-staging-db \
--set-env-vars="^|^NODE_ENV=production|TRUST_PROXY=2|ALLOWED_HOSTS=staging.wedding.mydomain.com,*.run.app" \
--set-secrets="DATABASE_URL=STAGING_DATABASE_URL:latest,ADMIN_PASSWORD=ADMIN_PASSWORD:latest,GUEST_PASSCODE=GUEST_PASSCODE:latest,GUEST_SESSION_SECRET=GUEST_SESSION_SECRET:latest" \
--port=3000
# 3b. Promote verified digest-pinned container revision to production Cloud Run service wedding-website
gcloud run deploy wedding-website \
--image="ghcr.io/fderuiter/wedding_website@${IMAGE_DIGEST}" \
--platform=managed \
--region=us-central1 \
--allow-unauthenticated \
--add-cloudsql-instances=YOUR_PROJECT_ID:us-central1:wedding-db \
--set-env-vars="^|^NODE_ENV=production|TRUST_PROXY=2|ALLOWED_HOSTS=wedding.mydomain.com,*.run.app" \
--set-secrets="DATABASE_URL=DATABASE_URL:latest,ADMIN_PASSWORD=ADMIN_PASSWORD:latest,GUEST_PASSCODE=GUEST_PASSCODE:latest,GUEST_SESSION_SECRET=GUEST_SESSION_SECRET:latest" \
--port=30007. Health Checks
Cloud Run separates startup readiness from ongoing process liveness so brief Cloud SQL blips do not restart warm instances.
Cloud Run Probes Configuration
Configure the liveness probe via gcloud using the composite --liveness-probe flag targeting /api/live on port 3000:
gcloud run services update wedding-website \
--region=us-central1 \
--liveness-probe=httpGet.path=/api/live,httpGet.port=3000,periodSeconds=30To configure both the HTTP startupProbe (/api/health, verifying PostgreSQL connectivity before serving traffic) and livenessProbe (/api/live, process liveness decoupled from PostgreSQL) together, export and apply a Knative Service manifest (service.yaml) with gcloud run services replace:
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
name: wedding-website
spec:
template:
spec:
containers:
- image: ghcr.io/fderuiter/wedding_website@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
ports:
- containerPort: 3000
startupProbe:
httpGet:
path: /api/health
port: 3000
initialDelaySeconds: 5
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
livenessProbe:
httpGet:
path: /api/live
port: 3000
periodSeconds: 30
timeoutSeconds: 5
failureThreshold: 3gcloud run services replace service.yaml --region=us-central1Read-only (GET and HEAD) probe requests to /api/live, /api/health, and /api/ready enforce syntactic Host validation only in src/middleware.ts, so Cloud Run's internal pod/link-local Host headers (e.g., 169.254.1.1:3000) succeed without adding internal probe IPs to ALLOWED_HOSTS. The startup probe verifies database query capability via /api/health, .github/workflows/deploy-stage.yml and .github/workflows/rollback.yml verify both /api/health and full 16-table / 47-migration schema readiness via /api/ready before declaring rollouts or N-1 rollbacks healthy, and /api/live returns HTTP 200 { "status": "alive", "timestamp": "..." } without querying PostgreSQL so transient database blips do not trigger container restart loops.
8. Rollback Strategy
Cloud Run maintains an immutable history of service revisions.
Instant Traffic Rollback
To immediately revert 100% of traffic on wedding-website to a previous healthy container revision:
# List all revisions
gcloud run revisions list --service=wedding-website --region=us-central1
# Route 100% traffic back to previous revision
gcloud run services update-traffic wedding-website \
--to-revisions=wedding-website-00012-abc=100 \
--region=us-central1Rollbacks execute in under 2 seconds without rebuilding images.
9. Webhooks & Scheduled Background Jobs
Stripe payment_intent.succeeded Webhook
- Store
STRIPE_SECRET_KEYandSTRIPE_WEBHOOK_SECRET(whsec_...) in GCP Secret Manager and setNEXT_PUBLIC_STRIPE_PUBLISHABLE_KEYon the Cloud Run service revision. - In Stripe Dashboard > Developers > Webhooks, add endpoint
https://wedding.mydomain.com/api/registry/webhook/stripe(matchingALLOWED_HOSTS) subscribed topayment_intent.succeeded. src/middleware.tsexempts/api/registry/webhook/stripefrom session cookies while enforcingALLOWED_HOSTS, and the route handler verifiesstripe-signatureagainstSTRIPE_WEBHOOK_SECRET.
Cloud Scheduler Broadcast Cron (CRON_SECRET)
- Store
CRON_SECRETin GCP Secret Manager and mount--set-secrets="CRON_SECRET=CRON_SECRET:latest"onwedding-website. - Create a Google Cloud Scheduler HTTP job that calls
/api/cron/broadcastswithAuthorization: Bearer <CRON_SECRET>:bashgcloud scheduler jobs create http wedding-broadcasts \ --location=us-central1 \ --schedule="*/5 * * * *" \ --uri="https://wedding.mydomain.com/api/cron/broadcasts" \ --http-method=POST \ --headers="Authorization=Bearer YOUR_CRON_SECRET"
10. Provider-Specific Limitations
- Cold Starts: Initial HTTP requests to a scaled-to-zero instance incur 1.5–3.0s latency while container initializes. Remedy: Set
--min-instances=1. - Stateless Filesystem: Disk writes to
/tmpare kept in container RAM and cleared when instances terminate. All persistent uploads must use S3/R2. - Database Connections: High concurrency auto-scaling can exceed PostgreSQL connection limits (
max_connections). Remedy: Enable Cloud SQL Auth Proxy connection pooling or use PgBouncer / Neon connection pooling. - Request Timeout: Default Cloud Run request timeout is 5 minutes (configurable up to 60 minutes for bulk export/import tasks).