GcpIntermediate

Deploying Containerized Applications with Cloud Run

8 min read

TL;DR

Master serverless container deployment with Google Cloud Run. Learn how to build, deploy, and manage containerized applications with automatic scaling and zero infrastructure management.

Deploying Containerized Applications with Cloud Run

Executive Summary

Cloud Run runs stateless containers behind HTTPS endpoints and scales them from zero to as many instances as traffic demands, with no servers to patch or size. This guide covers the decisions that determine whether a Cloud Run service behaves well in production: how the request and concurrency model works, how to configure CPU, memory, and scaling bounds, how to handle secrets and private networking, and how to roll out changes safely with revisions and traffic splitting. After reading it, you should be able to deploy a container, secure it, and reason about its cost and cold-start behaviour before the first production request arrives.

Why This Matters

The failure modes of serverless containers are rarely exotic. They are a container that listens on the wrong port, an instance starved of CPU between requests, a secret pasted into an environment variable, or a service left publicly invocable because a tutorial said to add a flag. Each of these is cheap to prevent at deploy time and expensive to discover during an incident. Cloud Run removes infrastructure work, but it does not remove the need to understand the contract between your container and the platform: listen on the injected port, handle requests concurrently or say so, stay stateless, and shut down cleanly. Teams that internalise that contract get near-zero operations; teams that do not end up debugging behaviour that looks random but is documented.

Core Concepts

The Request and Scaling Model

Cloud Run services are built from revisions: immutable snapshots of a container image plus its configuration. Incoming requests are load-balanced across container instances, and the autoscaler adds or removes instances based on pending requests. When no requests arrive, instances scale to zero and you stop paying for CPU and memory, at the cost of a cold start on the next request. Each instance handles multiple requests concurrently; the default concurrency is 80, and it is the single most important tuning knob on the platform. CPU is allocated in full while a request is being processed; with the default CPU allocation setting, an instance receives almost no CPU outside of request handling, which breaks background threads, timers, and in-process queues unless you explicitly request always-allocated CPU.

Building a Compliant Container

The container must listen for HTTP requests on the port given by the PORT environment variable. A minimal Node.js example:

// app.js
const express = require('express');
const app = express();
const port = process.env.PORT || 8080;

app.get('/', (req, res) => {
  res.send('Hello from Cloud Run!');
});

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

# Dockerfile
FROM node:18-slim

WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .

ENV PORT=8080
EXPOSE 8080

CMD ["npm", "start"]

Build and deploy with Cloud Build and the gcloud CLI:

# Build the container image
gcloud builds submit --tag gcr.io/PROJECT_ID/my-app

# Deploy to Cloud Run
gcloud run deploy my-service \
  --image gcr.io/PROJECT_ID/my-app \
  --platform managed \
  --region us-central1 \
  --allow-unauthenticated

The --allow-unauthenticated flag makes the service public. Omit it for internal services and grant the roles/run.invoker role to the callers that need access instead.

Configuration as YAML

Every deploy flag has an equivalent in the Knative serving YAML, which is the better artefact to keep in version control:

# service.yaml
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
  name: my-service
spec:
  template:
    spec:
      containers:
        - image: gcr.io/PROJECT_ID/my-app
          env:
            - name: NODE_ENV
              value: "production"
          resources:
            limits:
              cpu: "1"
              memory: "256Mi"
          ports:
            - containerPort: 8080

Startup and liveness probes can be declared the same way, and they matter: a startup probe tells Cloud Run when a slow-booting container is ready to receive traffic instead of failing requests during boot.

# health-check.yaml
spec:
  template:
    spec:
      containers:
        - image: gcr.io/PROJECT_ID/my-app
          livenessProbe:
            httpGet:
              path: /health
              port: 8080
          readinessProbe:
            httpGet:
              path: /ready
              port: 8080

Secrets and Environment Variables

Plain environment variables are for configuration, not credentials. Store secrets in Secret Manager and mount them as environment variables or files:

# Set environment variables
gcloud run services update my-service \
  --set-env-vars KEY1=VALUE1,KEY2=VALUE2

# Use secrets from Secret Manager
gcloud run services update my-service \
  --set-secrets="MY_SECRET=my-secret:latest"

Pin a specific secret version in production rather than latest if an unreviewed secret rotation should not silently change a running service's behaviour.

Revisions and Traffic Splitting

Every configuration change creates a new revision, and traffic can be split between revisions by percentage or pinned to a specific revision for canary releases:

# Split traffic between revisions
gcloud run services update-traffic my-service \
  --to-revisions=v1=50,v2=50

This is the safe way to ship: send a small share of traffic to the new revision, watch error rates and latency in Cloud Monitoring, then shift the remainder. Rolling back is a traffic change, not a redeploy.

Networking and Identity

By default a service can call the public internet and be called from it (subject to IAM). To reach resources inside a VPC — a Cloud SQL private IP, a Memorystore instance, an internal load balancer — attach a Serverless VPC Access connector or use Direct VPC egress, and control which traffic is forced through it:

# Configure VPC connector
gcloud run services update my-service \
  --vpc-connector my-connector

# Configure egress settings
gcloud run services update my-service \
  --vpc-egress all-traffic

For service-to-service calls, prefer IAM authentication with ID tokens over shared secrets, and give each service its own service account with only the permissions it needs.

Decision Framework

SituationRecommendation
Public web API or webhook receiverCloud Run service, unauthenticated at the edge only if the app does its own auth
Internal service called by other GCP servicesCloud Run with --no-allow-unauthenticated and roles/run.invoker grants
Bursty traffic, long idle periodsScale to zero; accept cold starts or set a small minimum instance count
Steady latency-sensitive trafficMinimum instances above zero and concurrency tuned to the runtime
Background work triggered by eventsCloud Run jobs or a service driven by Pub/Sub, not a request handler that outlives its request
Long-lived connections or streamingCloud Run with always-allocated CPU and adjusted timeouts, or GKE if control is insufficient

Implementation Checklist

  • [ ] Container listens on the PORT environment variable and handles SIGTERM gracefully
  • [ ] Concurrency set deliberately for the runtime instead of left at the default by accident
  • [ ] CPU and memory right-sized from load-test results, not guesses
  • [ ] Secrets referenced from Secret Manager; no credentials in plain environment variables or the image
  • [ ] Service runs as a dedicated service account with least-privilege roles
  • [ ] Public access is an explicit decision; internal services require roles/run.invoker
  • [ ] Startup probe configured for slow-booting containers
  • [ ] New revisions rolled out with traffic splitting and a documented rollback step
  • [ ] Request latency, error rate, instance count, and billable time visible on a dashboard with alerts
  • Trade-offs

    Scale to zero means cold starts; minimum instances remove them but reintroduce a fixed cost and idle capacity. The request timeout and per-instance model fit request-response workloads well and long-running or stateful work badly — anything held in instance memory disappears when the instance is replaced. CPU throttling outside requests is a common source of "works locally, stalls in production" bugs for frameworks that do background processing. You also give up control over the underlying machines entirely: no SSH, no host agents, no persistent local disk beyond an in-memory filesystem.

    When Not to Use

  • Stateful or leader-elected workloads: use GKE or Compute Engine, where instance identity and local state are stable.
  • Work that runs longer than the maximum request timeout or needs raw sockets and inbound protocols other than HTTP/gRPC: use Cloud Run jobs for batch work, or GKE/Compute Engine for arbitrary networking.
  • GPU-dependent inference or training: use Vertex AI or GKE with GPU node pools rather than forcing the workload into a CPU-only container service.
  • A simple static site: Cloud Storage with a load balancer or a hosting product is cheaper and simpler than a container.
  • Conclusion

    Cloud Run is the right default for stateless HTTP workloads on Google Cloud: the operational surface is small, scaling is automatic, and revisions plus traffic splitting make releases boring. The platform rewards teams that respect its contract — stateless containers, deliberate concurrency, secrets in Secret Manager, IAM in front of anything private. Get those four things right and most production surprises disappear.

    References

  • Cloud Run documentation
  • 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.