Tutorials Logic, IN info@tutorialslogic.com

Cloud Run: Deploy, Scale, Secure, and Release Containers

Cloud Run Service Model

Cloud Run is a managed platform for request-driven services, run-to-completion jobs, and worker pools. A service deployment creates an immutable revision and can shift traffic between revisions without changing the service URL.

The container must honor the runtime contract: listen on the injected port, start within the allowed window, handle termination, and keep durable state outside the instance filesystem.

Container Scaling Contract

Keep startup deterministic and avoid downloading large mutable dependencies on each cold start. Bind to 0.0.0.0 on the PORT value, emit structured logs to standard output, and stop accepting new work when termination begins.

Concurrency controls how many simultaneous requests one instance may handle. CPU, memory, thread safety, downstream connection pools, latency, and request shape determine a sensible value; a higher number is not automatically cheaper.

Invocation and Runtime IAM

Invoker IAM determines who may call an authenticated service. The attached service account determines which Google Cloud APIs the running container may call. Keeping those identities distinct prevents a public endpoint from inheriting broad cloud access.

Use Secret Manager integration or another managed secret path for sensitive values. Environment variables are convenient configuration, but anyone who can inspect revision settings may be able to read them.

Deploy a revision with a dedicated identity and secret

Deploy a revision with a dedicated identity and secret
IMAGE=us-central1-docker.pkg.dev/tl-cloud-lab/apps/orders-api:v1

gcloud run deploy orders-api \
  --image="$IMAGE" \
  --region=us-central1 \
  --service-account=orders-api@tl-cloud-lab.iam.gserviceaccount.com \
  --set-secrets=DB_PASSWORD=db-password:latest \
  --concurrency=40 \
  --max-instances=20 \
  --no-allow-unauthenticated
  • Pin production images to an immutable digest or versioned tag.
  • Maximum instances can protect cost but may turn excess demand into latency or rejected requests.

Traffic Releases and Rollback

Deploy a no-traffic revision, run smoke checks against its tagged URL, then move a small percentage of traffic while comparing errors, latency, saturation, and business outcomes. A configuration-only change still creates a revision and deserves the same review.

Rollback shifts traffic to a known revision; it does not reverse database migrations or external side effects. Keep application compatibility across the release window.

Container Runtime Contract

A Cloud Run service exposes an HTTPS endpoint backed by immutable revisions. The ingress container must listen on the injected `PORT` and on all interfaces, start within platform limits, and remain prepared for termination. The writable filesystem is instance-local and disposable, so durable state belongs in Cloud Storage, a database, or another managed service. Package application code and exact runtime dependencies into a tested image.

Cloud Run can also run jobs for finite work that does not serve requests. A service, job, worker pool, and function-style deployment have different invocation and completion contracts. Select from request handling, task duration, retry ownership, parallelism, networking, accelerator, and operational needs rather than treating every container as an HTTP service.

Environment variables are revision configuration and are visible to principals with sufficient service access. Use Secret Manager integration for secrets, pin a version when deterministic rollout matters, and plan rotation. Attach a dedicated service identity with only the APIs the code calls. Authentication to the service and the service identity used for outbound calls are separate policy decisions.

  • Build a small image with a non-root process where compatible.
  • Handle startup, readiness, cancellation, and termination explicitly.
  • Store durable sessions and files outside the container instance.
  • Keep deployment identity separate from runtime identity.

Concurrency and Scaling

Cloud Run can send concurrent requests to one instance. Higher concurrency improves utilization for I/O-bound services, while CPU-heavy, memory-heavy, single-threaded, or non-thread-safe code may need a lower value. Load test with realistic request duration and downstream calls; a setting that reduces instance count can increase tail latency or exhaust each instance's database pool.

Maximum instances protects downstream systems and cost but can cause requests to queue or fail when capacity is exhausted. Minimum instances reduce cold-start latency at an ongoing cost. CPU allocation, startup CPU boost, request timeout, memory, and autoscaling behavior should be configured as one performance contract. An autoscaler cannot create healthy capacity if regional quota, image startup, or a dependency is the bottleneck.

Calculate worst-case downstream pressure as instance count multiplied by per-instance concurrency and connection use. Apply admission control, bounded queues, circuit breakers, and idempotent retries before that pressure reaches a database or partner. For asynchronous work, place tasks or events behind a service that can absorb bursts instead of keeping an HTTP request open indefinitely.

  • Measure cold and warm latency separately.
  • Set maximum instances from downstream capacity evidence.
  • Bound connection pools below aggregate database limits.
  • Use backpressure before memory and request queues grow without limit.

Ingress, Egress, and Identity

Ingress settings restrict which paths may reach a service, while IAM controls who may invoke it. A service can be internet-reachable yet require authenticated invocation, or be limited to internal and load-balancing paths. For public applications, place appropriate load balancing, Cloud Armor, domain, certificate, and authentication controls in front of the service rather than making application code infer trust from an IP header.

Outbound traffic to a VPC can use Direct VPC egress or a Serverless VPC Access connector depending on requirements and support. Decide whether all traffic or only private ranges use that path, then account for DNS, routes, firewall policy, NAT, connector capacity, and source ranges. Private connectivity does not grant IAM permission to the destination service.

Service-to-service requests should use identity tokens with the correct audience for authenticated Cloud Run invocation. Access tokens authorize Google API calls and are not interchangeable with identity tokens. Validate caller identity at the platform boundary, propagate end-user context only through an explicit application authorization design, and never reuse the runtime service account as proof of the original user.

  • Test allowed and denied ingress paths independently.
  • Use the exact service URL or configured audience for identity tokens.
  • Monitor VPC egress errors and connector saturation where applicable.
  • Authorize the end user separately from the calling workload.

Revision Release and Recovery

Every deployment or configuration change creates an immutable revision. Deploy a revision with no production traffic, verify it through a tag where appropriate, then migrate a small percentage and compare latency, errors, resource use, and business outcomes. Traffic can be split between revisions and rolled back quickly, but rollback does not reverse a destructive schema or external side effect.

Keep database changes backward compatible across every revision that may receive traffic. Use expand, migrate, and contract phases; deploy readers that tolerate both forms before writers depend on the new one. A canary needs enough representative traffic to expose risk, and sticky client behavior or low-volume endpoints can hide failures in a percentage-based split.

A production runbook should cover a revision that cannot start, returns errors, leaks connections, reaches maximum instances, loses VPC access, uses the wrong secret, or exceeds timeout. Preserve logs and revision configuration, stop traffic or roll back, reconcile in-flight work, and verify that the old revision still works with current data. Delete or retain old revisions according to rollback and evidence needs rather than manually pruning during an incident.

  • Name revisions or annotate releases with artifact identity.
  • Compare canary and baseline by user-facing indicators.
  • Keep schema changes compatible with rollback.
  • Practice traffic rollback and post-rollback verification.

Deadlines and Cancellation

A Cloud Run request timeout bounds the platform request, but application calls need shorter nested deadlines so code can return or cancel before the outer limit. Propagate cancellation to database queries, HTTP clients, and background work. Continuing expensive work after the client and platform have abandoned the request wastes capacity and can produce an unobserved side effect.

For mutations, use a stable operation key and store progress so a caller can safely retry after a timeout. Return an asynchronous operation or enqueue a task when work cannot reliably finish within an interactive deadline. Do not start untracked background threads after sending a response; instance CPU and lifetime behavior may not match that assumption.

Load test slow dependencies and client disconnects. Confirm sockets close, transactions roll back or reconcile, logs carry the operation ID, and retries do not duplicate results. Set timeout dashboards by endpoint because one long export should not dictate the deadline for every ordinary request.

  • Derive inner deadlines from the remaining request budget.
  • Move long durable work to an owned asynchronous workflow.
  • Reconcile ambiguous writes before retry.
  • Verify client-visible timeout responses are actionable.

Cloud Run Release Examples

Abort a Faulty Revision Rollout

A new Cloud Run revision has slower startup and a higher 5xx rate.

Abort a Faulty Revision Rollout
Constraints: Traffic splitting is available and the previous revision is still deployed.
Decision: Send a small percentage to the revision, compare revision-labelled latency and errors, then return traffic to the prior revision.
Verification: Error rate returns to baseline and logs identify the failing revision without a rebuild.
Failure test: Set minimum instances to zero in a test service and verify the cold-start probe exposes the regression.
Output
Expected evidence: Error rate returns to baseline and logs identify the failing revision without a rebuild.
  • This is a worked engineering decision, so the result is operational evidence rather than terminal output.
Before you move on

Cloud Run: Deploy, Scale, Secure, and Release Containers Mastery Check

5 checks
  • The image is reproducible, scanned, versioned, and starts on the required port.
  • Invocation IAM and runtime service-account IAM are reviewed separately.
  • Concurrency, min instances, max instances, timeout, CPU, and memory are load-tested.
  • Downstream connections and quotas can tolerate scale-out.
  • Canary, rollback, migration compatibility, logs, metrics, and alerts are exercised.

Google Cloud Questions Learners Ask

A service can scale to zero when no minimum instance setting or other condition keeps capacity warm. Jobs and worker pools use different execution models.

No. Writable instance storage is disposable and not shared. Store durable or shared data in an external service designed for it.

Next Step
Next Practice

Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.