Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 45 ยท Compute

Cloud Run

Learn Cloud Run: deploying containers, the PORT contract, request-based scaling, scale to zero, concurrency, revisions and traffic, with a runnable server.

Cloud Run runs a container for you and bills by use. You give it an image that listens for HTTP requests, and Google handles servers, scaling, TLS and a public URL. When no requests arrive, it can scale down to zero instances, so an idle service costs almost nothing. For most new web apps and APIs on Google Cloud, it is the first thing to try.

The deal is simple: your container must follow a small contract, and in return you get automatic scaling from zero to hundreds of instances. This lesson covers the contract, how scaling and concurrency work, and how revisions make releases safe.

What Cloud Run does for you

Runs containers Any language, any library.
Scales on requests More traffic, more instances.
Scales to zero No traffic, no instances, no bill.
HTTPS built in A secure URL on deploy.
1 / 2

The container contract

Cloud Run does not care what is inside the image, as long as:

  1. The process listens on the port in the PORT environment variable (8080 by default), on all interfaces (0.0.0.0), not just localhost.
  2. It starts quickly and serves HTTP, gRPC or WebSocket traffic.
  3. It is stateless: any instance can be stopped at any time, and its local disk is temporary.
  4. It writes logs to standard output and standard error, which land in Cloud Logging.

Here is a minimal Node server that keeps the contract (read-only; the TryIt below runs a similar program):

JavaScript
import http from "node:http";

const port = process.env.PORT || 8080;
http.createServer((req, res) => {
  res.end("Hello from Cloud Run\n");
}).listen(port, "0.0.0.0");

The most common first failure is an app that hard-codes a port or listens on 127.0.0.1. Cloud Run then reports that the container failed to start and listen on the expected port.

Deploying

You can deploy a prebuilt image from Artifact Registry, or deploy from source and let Google build the image with buildpacks. The commands are read-only here because they need a project:

Terminal
# From a prebuilt image
gcloud run deploy orders-api \
  --image=us-docker.pkg.dev/my-project-id/apps/orders:1 \
  --region=us-central1 \
  --service-account[email protected] \
  --allow-unauthenticated

# From source in the current folder
gcloud run deploy orders-api --source=. --region=us-central1

--allow-unauthenticated makes the service public. Without it, callers need the Cloud Run Invoker role, which is the right default for internal services. Give the service its own service account and keep passwords in Secret Manager, exposed as environment variables or mounted files.

Scaling, concurrency and cost

Cloud Run decides the number of instances from the incoming requests:

  • Concurrency is how many requests one instance handles at once. The default is 80; you can set anything from 1 up to a documented maximum. A single-threaded, CPU-heavy app may want a low value; an I/O-bound API can take many.
  • Min instances (default 0) keeps some instances warm to avoid cold starts. It costs money while idle.
  • Max instances puts a ceiling on scaling, which also protects a database from being overwhelmed and your bill from a traffic flood.
  • A cold start is the delay when a request arrives and no instance is ready, because one must be created and your app must boot. Small images and fast startup keep it short.
Terminal
gcloud run services update orders-api \
  --concurrency=40 \
  --min-instances=1 \
  --max-instances=20 \
  --timeout=60

With request-based billing, you pay for the time instances spend handling requests (rounded up in small increments) plus a small request fee; there is also an option to keep CPU always allocated for background work. Prices change, so check the current page rather than memorizing numbers.

Instances needed, as arithmetic

If requests arrive at a certain rate and each takes some time, then the number of requests in flight equals rate times duration (Little's law). Dividing by concurrency gives a rough instance count. This stand-in only does that arithmetic; real autoscaling also watches CPU and has its own timing.

JS Stand-in: how many instances for this traffic?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first column is the nice part: zero traffic needs zero instances. The table also shows why concurrency matters so much: the same load needs 200 instances at concurrency 1 but only 3 at concurrency 80, if your code can truly handle that many requests in parallel.

Revisions and traffic

Every deploy that changes the configuration creates a new immutable revision. A service is a stable name and URL that routes traffic to one or more revisions, like versions in App Engine:

Terminal
# Deploy a new revision but keep traffic on the old one
gcloud run deploy orders-api --image=us-docker.pkg.dev/my-project-id/apps/orders:2 --no-traffic --tag=candidate

# Send 10% to it, then all of it
gcloud run services update-traffic orders-api --to-revisions=orders-api-00002-abc=10
gcloud run services update-traffic orders-api --to-latest

# Roll back by routing to a known good revision
gcloud run services update-traffic orders-api --to-revisions=orders-api-00001-xyz=100

A tag gives a revision its own test URL before it receives public traffic.

A server that obeys the PORT contract

This program runs on Piston, so it is a real Node HTTP server. It reads PORT like a Cloud Run container would (falling back to a free port here), counts requests, and calls itself with fetch. Cloud Run itself, scaling and the URL are not part of it.

Node.js Stand-in: a server that listens on PORT

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

K_REVISION is one of several environment variables Cloud Run sets in real containers; here it just has a fallback. Handling SIGTERM matters because instances are stopped when traffic drops, and you want in-flight requests to complete.

Deploying a Django site (and Django-based CMSs)

Cloud Run suits Django well, because a Django app is a stateless web process once its files and database are moved out of the container. A typical setup:

  • Container: a Dockerfile that installs requirements and runs Gunicorn on the PORT Cloud Run provides.
  • Database: Cloud SQL for PostgreSQL, reached through the built-in Cloud SQL connection (a unix socket) and credentials from Secret Manager.
  • Static and media files: collectstatic to a Cloud Storage bucket (behind Cloud CDN), with media uploads going to a bucket too, because the container filesystem is temporary.
  • Settings: read SECRET_KEY, DATABASE_URL and ALLOWED_HOSTS from environment variables. Add your service URL to CSRF_TRUSTED_ORIGINS.
  • Migrations: run python manage.py migrate as a Cloud Run job or a build step, not at container start, so many instances do not race.
DOCKERFILE
FROM python:3.13-slim
ENV PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 mysite.wsgi:application

Django-based content management systems such as Wagtail and Django CMS deploy the same way: they are ordinary Django projects, so the same container, database and bucket arrangement applies, with the admin and uploaded media in Cloud Storage. Keep media in the bucket and never rely on local disk.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which port must a Cloud Run container listen on?

    Cloud Run sets PORT (8080 by default) and sends requests there. Listen on 0.0.0.0 and read the variable instead of hard-coding a number.
  2. 2. What happens to a service with min instances 0 and no traffic?

    Scale to zero is the default. The next request triggers a cold start of a new instance.
  3. 3. What is a Cloud Run revision?

    Each configuration change creates a revision, and traffic rules decide which revisions receive requests.
  4. 4. Why set a max-instances limit?

    Without a ceiling, a traffic spike can scale the service far enough to exhaust a database connection limit or run up a large bill.

Summary

  • Cloud Run runs stateless containers that listen on PORT and scales them with requests, down to zero.
  • Concurrency, min instances and max instances control performance, cold starts and cost.
  • Each change makes an immutable revision; traffic rules and tags enable canary releases and rollback.
  • Keep services private by default, give each its own service account, and use Secret Manager for secrets.

Next: Cloud Run Functions