GcpIntermediate

How to Deploy a Web Application on Google Cloud Run

Admin
8 min read

TL;DR

A step-by-step guide to deploying and managing web applications using Google Cloud Run, including best practices and optimization tips.

How to Deploy a Web Application on Google Cloud Run

Executive Summary

Cloud Run runs your container on Google's infrastructure and bills you for the CPU and memory your instances consume while handling requests. You bring any container that listens on a port; Cloud Run supplies HTTPS, load balancing, autoscaling from zero to as many instances as you allow, and per-revision traffic splitting. This guide walks the full path: the contract your container must honour, building and deploying with the gcloud CLI, the settings that actually matter (concurrency, memory, CPU, minimum and maximum instances), connecting to Cloud SQL and Secret Manager, and the production practices for revisions, monitoring, and cost control. After reading it, you should be able to deploy a web application and reason about every flag you set.

Why This Matters

Cloud Run's simplicity hides three decisions that determine whether a deployment behaves. The first is concurrency: one instance handling many simultaneous requests is efficient only if your application is genuinely concurrent-safe and not CPU-bound per request. The second is statelessness: instances are created and destroyed by the autoscaler, so anything stored on local disk or in memory is temporary by design, and designs that ignore this corrupt data under scale. The third is cold starts: scaling from zero is free when idle and slow on the first request, so the minimum-instances setting is a direct trade between latency and cost. Teams that understand these three enjoy a platform that mostly runs itself; teams that do not debug phantom data loss and mysterious latency.

Core Concepts

The Cloud Run Contract

A Cloud Run service is a container image plus configuration. The container must listen for HTTP requests on the port given by the PORT environment variable (8080 by default), start quickly enough to pass startup probes, and handle requests statelessly. It should shut down cleanly on SIGTERM, because instances receive a brief grace period before termination. In return, Cloud Run terminates TLS for you, gives the service a stable URL, and routes each request to a healthy instance.

The toolchain is small: a Google Cloud project with billing enabled, the gcloud CLI authenticated, and Docker or Cloud Build to produce images. Source code lives in a repository; images live in Artifact Registry, which is where Cloud Run pulls them from.

Building and Deploying

Build the image with the same discipline as any production Dockerfile: multi-stage build, minimal base, non-root user. Then push it to Artifact Registry and deploy:

# Build and push the image with Cloud Build
gcloud builds submit --tag REGION-docker.pkg.dev/PROJECT_ID/REPO/myapp

# Deploy to Cloud Run
gcloud run deploy myapp \
  --image REGION-docker.pkg.dev/PROJECT_ID/REPO/myapp \
  --region REGION \
  --platform managed

Every deployment creates an immutable revision. New revisions receive no traffic until you route it to them, which enables the standard safe-release pattern: deploy, verify the revision on its tagged URL, then shift traffic gradually. Rolling back is routing traffic back to the previous revision, not redeploying old code.

The Settings That Matter

Four settings account for most production behaviour:

  • Concurrency: how many simultaneous requests one instance handles. The platform default suits I/O-bound web applications. Lower it toward 1 for CPU-bound work or applications with heavy per-request memory, because concurrent requests share the instance's memory.
  • Memory and CPU: set from measurement. Memory is a hard limit; exceeding it kills the instance mid-request. CPU is allocated proportionally and, by default, primarily while requests are being processed.
  • Minimum instances: instances kept warm. Zero is cheapest and incurs cold starts; one or more buys latency at a standing cost.
  • Maximum instances: your blast-radius control. It caps both cost and the load you can push onto downstream systems such as a database with finite connections.
  • A sensible starting point for a typical web application is one CPU, a memory allocation sized from load testing rather than guessing, default concurrency reviewed against the application's threading model, and a maximum instance count chosen with your database's connection budget in mind.

    Connecting to Data and Secrets

    Cloud Run reaches Cloud SQL through its built-in connector, which provides a Unix socket and handles authentication and encryption; combine it with a connection pool sized against your instance count, because autoscaling multiplies connections. Other Google services are called with the service's identity: assign the service a dedicated service account with only the roles it needs.

    Secrets belong in Secret Manager and are exposed to the container as environment variables or mounted files by reference, so rotating a secret does not require rebuilding the image. Reaching resources inside a VPC, such as a Memorystore instance or an internal service, uses a Serverless VPC Access connector or Direct VPC egress. Plain configuration goes in ordinary environment variables set on the service.

    Observability

    Cloud Run emits request logs and container logs to Cloud Logging and metrics to Cloud Monitoring without extra agents. The metrics that matter operationally are request latency (especially the tail), error rate by status code, instance count, and billable instance time. Alert on error rate and latency, and check container startup failures and out-of-memory kills after every deploy; both present as elevated 5xx responses and are visible in logs filtered to the service's revisions.

    Cost and Performance Levers

    You pay for allocated CPU and memory during request processing, plus a standing charge for minimum instances. The effective levers are therefore: raise concurrency where the application tolerates it, so fewer instance-seconds serve the same traffic; right-size memory, because CPU allocation follows memory choices in part; keep images small and startup fast so cold starts and scale-out are cheap; and reuse connections and clients across requests within an instance instead of paying setup costs per request. Startup CPU boost, where available, is worth enabling for slow-starting runtimes.

    Decision Framework

    SituationRecommendation
    Stateless web app or API with variable trafficCloud Run with scale-to-zero, default concurrency reviewed
    CPU-bound per-request workLower concurrency toward 1 and size CPU deliberately
    Latency-sensitive service that cannot tolerate cold startsSet minimum instances to 1 or more and accept the standing cost
    Service backed by Cloud SQLBuilt-in Cloud SQL connector plus a bounded connection pool
    Traffic spikes that could overwhelm a databaseCap maximum instances to protect the downstream system
    Long-running background workCloud Run jobs, not a Cloud Run service

    Implementation Checklist

  • [ ] Container listens on the PORT environment variable and shuts down cleanly on SIGTERM
  • [ ] Image is built with a multi-stage Dockerfile and runs as a non-root user
  • [ ] Concurrency, CPU, and memory are set from the application's threading model and load tests
  • [ ] Maximum instances are capped with downstream connection budgets in mind
  • [ ] The service runs as a dedicated least-privilege service account
  • [ ] Secrets are referenced from Secret Manager, not baked into the image or set as plain values
  • [ ] New revisions are verified on their tagged URL before traffic shifts
  • [ ] Alerts exist for error rate, tail latency, and out-of-memory kills
  • [ ] A rollback is one traffic command away and has been rehearsed
  • Trade-offs

    Cloud Run's request-driven model is a poor fit for workloads that are not request-driven: background daemons, work that runs longer than the request timeout allows, and anything needing a persistent local filesystem or a stable network identity. Scaling to zero trades cold-start latency for cost, and no setting removes that trade. Concurrency improves economics while coupling requests to each other's fate on a shared instance. You also accept Google's deployment model; the container is portable, but the service configuration, IAM wiring, and traffic management are Cloud Run concepts that must be rebuilt on another platform.

    When Not to Use

  • Long-running batch or streaming work: use Cloud Run jobs for finite tasks, and GKE or Compute Engine for continuous processing.
  • Workloads needing GPUs, kernel customisation, or exotic networking: those are GKE and Compute Engine territory.
  • Deeply stateful applications that cannot externalise state: a traditional VM or a managed service will fight you less than a stateless autoscaled platform.
  • Conclusion

    Cloud Run rewards applications that honour its contract: listen on the port, stay stateless, start fast, stop cleanly. Set concurrency, memory, and instance bounds from evidence rather than defaults, wire identity and secrets properly, and treat revisions as your release mechanism. Do that and deployment becomes the least interesting part of running the service, which is exactly what a platform should achieve.

    References

  • Cloud Run Documentation
  • Container Best Practices
  • Cloud Run Samples
  • Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.