Google Cloud Run Tutorial: Deploy a Container in Minutes

Google Cloud Run Tutorial: Deploy a Container in Minutes

Google Cloud Run is the fastest way to get a container running on Google Cloud without managing servers. You give it a container image, it gives you an HTTPS endpoint, and it scales the service from zero instances when idle to as many as your traffic needs — then back to zero when the traffic stops. There is no cluster to size, no node pool to upgrade, and no load balancer to configure. For a DevOps engineer, that makes Cloud Run the default answer for APIs, webhooks and internal tools.

This tutorial takes you from zero to a production-shaped Cloud Run service. You will deploy a first service from source code, learn how services, revisions and instances fit together, tune concurrency, CPU and memory, deal with cold starts, roll out a new version safely with traffic splitting, and lock the service down with IAM and secrets. Everything here uses the gcloud command line, because that is what you will use in a pipeline, and every step is one you can repeat in your own project. If you are new to Google Cloud itself, read our Google Cloud tutorial for beginners first; if you need a refresher on containers, our Docker tutorial for beginners covers building the image Cloud Run will run.

What Cloud Run Is — and What It Is Not

Cloud Run is a fully managed platform for running your code as a container on Google’s infrastructure. You deploy a container image, or source code that Cloud Run builds into an image for you, and Google runs it, routes HTTPS traffic to it, scales it, and manages TLS for the endpoint. Each service gets a unique HTTPS endpoint on a subdomain of run.app, and you can add a custom domain. It supports WebSockets, HTTP/2 end to end, and gRPC end to end, so it works for web applications, APIs, streaming endpoints and event-driven services alike.

Your code can run on Cloud Run in three ways, as described in the Cloud Run overview. A service responds to HTTP requests at a stable endpoint, with stateless instances that autoscale — this is the mode this tutorial focuses on, and the one most readers will use. A job executes parallelizable tasks that run to completion, started manually or on a schedule, which is the right shape for batch work, migrations and report generation. A worker pool handles always-on background workloads such as pull-based queues — Kafka consumers, Pub/Sub pull subscriptions or RabbitMQ consumers — that do not fit the request-and-response pattern. All three run sandboxed container instances in the same execution environment and can integrate with the rest of Google Cloud.

What Cloud Run is not matters just as much. It is not a Kubernetes cluster: there are no nodes, no pods and no YAML manifests to manage, which is the point, but it also means you cannot use Kubernetes features such as DaemonSets or custom schedulers. It is not a virtual machine: instances are stateless, they can be stopped at any time, and anything you need to keep must live in a database or an object store — never in the container’s local filesystem. And it is not a function platform in the old sense, although Cloud Run functions now run on the same infrastructure; if your workload is a single small function triggered by an event, Cloud Run functions may be a simpler fit than a full service.

The decision rule is simple. Choose Cloud Run when your workload fits in a container, answers HTTP requests or runs to completion, and benefits from scaling to zero when idle. Choose something else when you need long-lived stateful processes, direct control over the machine, or Kubernetes-native features. Most APIs, webhooks, internal dashboards and event handlers pass that test easily, which is why Cloud Run has become the default deployment target for so many teams on Google Cloud.

How Cloud Run Works: Services, Revisions and Instances

Three resources explain almost everything about Cloud Run, as the Cloud Run resource model documentation sets out: the service, the revision, and the instance. A service is the main resource. It lives in a specific Google Cloud region, it has a unique endpoint, and it holds your configuration: the container image, environment variables, memory and CPU limits, concurrency, scaling settings and IAM policy. A project can run many services in different regions, and Cloud Run automatically replicates a service across multiple zones within its region for redundancy and failover.

Every deployment to a service creates a revision. A revision is an immutable snapshot: one or more container images plus the configuration settings in force at deploy time, such as environment variables, memory limits and the concurrency value. You cannot modify a revision after it is created. Deploy a new image and you get a second revision; change an environment variable and you get a third. Cloud Run automatically routes requests to the latest healthy revision, and there is a maximum of 1,000 revisions per service — older unused revisions are eventually removed. Revisions are the reason rollbacks on Cloud Run are boring in the best sense: going back to the previous version means routing traffic to the revision that already exists, not rebuilding anything.

An instance is a single isolated environment running a copy of your container within a service. When requests arrive, Cloud Run starts instances to handle them; when requests stop, it scales instances down, all the way to zero. An instance handles up to its configured concurrency — the number of requests it processes at the same time — and Cloud Run adds instances when the existing ones are full. A service can rapidly scale out to one thousand instances, or even more if you request a quota increase. The instance is also the unit of billing: you pay for the requests your instances serve and the CPU and memory they use while running, which is why scaling to zero matters — an idle service with no instances running is not consuming compute.

Two more concepts complete the picture. The execution environment is the sandbox your container runs in: the first generation environment, based on gVisor, and the second generation environment, a microVM with fuller Linux compatibility and better CPU and network performance under sustained load. The first generation can start faster for some services; if you leave the choice unspecified, Cloud Run picks for you. And traffic management is built in: you can send all traffic to the latest revision, split traffic between revisions, or roll back, all without redeploying anything.

Deploy Your First Service

Before you deploy anything, you need a Google Cloud project with billing enabled and the Cloud Run API turned on, plus the gcloud command line authenticated against that project. If that is not set up yet, the Google Cloud tutorial linked in the introduction walks through it. Pick a region close to your users — us-central1 is a safe default for North America, europe-west1 for Europe — because the region is fixed for the service once you create it. Set it once so you do not have to repeat it on every command:

gcloud config set project my-project-id
gcloud config set run/region us-central1

The simplest possible service is a small web application that listens on the PORT environment variable and answers on the root path. Cloud Run injects PORT into every container, and your application must listen on it — this is the single most common reason a first deployment fails, because a container that listens on a hard-coded port never receives traffic. The application below is a minimal Python service using only the standard library, so there are no dependencies to install:

# main.py
import os
from http.server import BaseHTTPRequestHandler, HTTPServer

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.end_headers()
        self.wfile.write(b"Hello from Cloud Run")

if __name__ == "__main__":
    port = int(os.environ.get("PORT", "8080"))
    HTTPServer(("0.0.0.0", port), Handler).serve_forever()

Deploying from source is the fastest path: Cloud Run builds the container image for you with buildpacks, so you do not need a Dockerfile at all for a first deployment. From the directory containing main.py, run:

gcloud run deploy hello --source . --region us-central1 --allow-unauthenticated

The command builds the image, pushes it to Artifact Registry, creates the service, and prints the service URL when it finishes. The –allow-unauthenticated flag makes the service public, which is what you want for a first test; without it, the service requires authentication and your curl request will be rejected. Open the printed URL in a browser or run curl against it, and you should see “Hello from Cloud Run”. If the deploy fails, the usual causes are a missing PORT listener, a build failure, or an API that is not enabled — the error message will say which one.

Once the source-based deploy works, switch to deploying a prebuilt image, because that is what a CI pipeline will do. Build the image with a Dockerfile, push it to Artifact Registry, and deploy by image name:

docker build -t us-central1-docker.pkg.dev/my-project-id/hello-repo/hello:v1 .
docker push us-central1-docker.pkg.dev/my-project-id/hello-repo/hello:v1
gcloud run deploy hello --image us-central1-docker.pkg.dev/my-project-id/hello-repo/hello:v1 --region us-central1 --allow-unauthenticated

Notice what happened: deploying a new image created a second revision, and traffic moved to it automatically. The first revision still exists, and you can see both of them with gcloud run revisions list –service hello –region us-central1. From here on, every deploy is the same operation — build, push, deploy — and every deploy creates a new revision you can roll back to.

Configure Concurrency, CPU, Memory and Timeouts

Defaults will get a service running, but production services need their resources set deliberately, and the four settings that matter most are concurrency, CPU, memory and request timeout. Concurrency is the maximum number of requests one instance handles at the same time. If your application is I/O-bound — it spends most of its time waiting on a database or an external API — a higher concurrency lets one instance do more work and reduces the number of instances you need. If it is CPU-bound, higher concurrency just makes each request slower, because the requests share the same CPU. Start with the default, measure under load, and raise concurrency only when the measurements say the instance has idle capacity.

CPU and memory are set per instance, and they travel together: more memory is available at higher CPU allocations, and the right combination depends on what your application actually uses. The way to choose is to deploy, send realistic traffic, and read the metrics — Cloud Run reports instance CPU and memory utilization in Cloud Monitoring, and the numbers will tell you whether you are paying for capacity you do not use or starving an instance that needs more. Do not guess these values from a blog post; the correct values for your application are the ones your own metrics support.

Two CPU behaviours deserve attention. By default, CPU is allocated only while a request is being processed, which keeps costs down for services that are idle between requests. If your service does background work outside of requests — a cache refresh, a background thread — that work will be starved under the default, and you need CPU always allocated instead. That setting costs more, because the instance is billed for CPU even when no request is in flight. Similarly, the request timeout is configurable: a request that runs longer than the timeout is closed with an error, so set the timeout to match the slowest legitimate request your service handles, and move genuinely long-running work into a Cloud Run job instead of stretching the timeout to cover it.

Set these values at deploy time so they are recorded in the revision and reproducible from your pipeline:

gcloud run deploy hello \
  --image us-central1-docker.pkg.dev/my-project-id/hello-repo/hello:v1 \
  --region us-central1 \
  --concurrency 80 \
  --cpu 1 \
  --memory 512Mi \
  --timeout 60s \
  --min-instances 0 \
  --max-instances 10

The max-instances flag is a safety rail, not a performance target: it caps how far the service can scale, which protects you from a runaway bill if something goes wrong, but it also means requests will queue or fail if legitimate traffic exceeds the cap. Set it high enough for your real peak plus headroom, and treat it as a budget control rather than a tuning knob.

Scaling, Cold Starts and Min Instances

Scaling on Cloud Run is automatic and request-driven: instances start when requests arrive and stop when they are no longer needed, down to zero. That is the feature that makes Cloud Run cheap for spiky and bursty workloads, and it is also the source of its most-discussed drawback, the cold start. A cold start is the delay a request experiences when no instance is free to serve it and Cloud Run has to start a new container first. The delay has three parts — the container image is pulled, the container starts, and your application initializes — and for most services it is measured in hundreds of milliseconds to a few seconds.

The first fix for cold starts is to make the container itself start fast, because that is the part you control most directly. Listen on the PORT environment variable before doing any other work, so the instance can accept traffic as early as possible. Initialize clients lazily, and move optional work — loading reference data, warming caches, pre-compiling templates — out of the startup path. Keep the image small with a multi-stage Dockerfile that copies only the built application into the final image.

The second fix is min instances, which keeps a number of instances warm even when they serve no requests, so a request arriving after a quiet period finds a warm instance instead of waiting for a cold start. Set it at the service level, which applies across revisions and takes effect without a new deployment:

gcloud run services update hello --region us-central1 --min-instances 1

Min instances cost money — warm instances are billed at a lower rate than instances serving requests, but they are billed — so use them deliberately: one warm instance for a user-facing API with a latency budget, zero for a batch webhook that nobody waits on. Treat the minimum as a target, not a guarantee: capacity shortages or a container that crashes at startup can leave you below it for a while, so min instances reduce cold starts rather than eliminating them. Startup CPU boost is a third lever: it gives a new instance extra CPU while it starts and for a short period after, which shortens the initialization phase for applications that do heavy work at startup.

One more scaling behaviour catches people out: scaling is per revision, not per service. When you deploy a new revision and split traffic between the old and the new, each revision scales independently, so a revision receiving one percent of traffic still runs its own instances. That is correct behaviour, but it means a traffic split has a cost, and it is one more reason to finish a rollout and retire the old revision rather than leaving a split in place indefinitely.

Safe Rollouts: Revisions, Traffic Splitting and Rollback

Revisions turn deployments into a safe, reversible operation, but only if you use the traffic controls instead of sending every deploy straight to one hundred percent of users. The pattern is gradual rollout: deploy the new revision with no traffic, verify it, then shift a small percentage of traffic to it, watch the metrics, and increase the percentage in steps. Cloud Run supports all of this without redeploying anything, because traffic routing is a property of the service, not of the revision.

Start by deploying the new revision without traffic. The –no-traffic flag creates the revision and leaves the existing routing untouched, which gives you a revision URL you can test directly:

gcloud run deploy hello \
  --image us-central1-docker.pkg.dev/my-project-id/hello-repo/hello:v2 \
  --region us-central1 --no-traffic
gcloud run services update-traffic hello --region us-central1 --to-revisions hello-v2=10,hello-v1=90

The second command sends ten percent of traffic to the new revision and ninety percent to the old one. The revision names in that command are the ones Cloud Run assigned — list them with gcloud run revisions list if you are unsure. Now watch: error rate, latency and instance counts for the new revision in Cloud Monitoring, and your application’s own logs, filtered to the new revision. If the new revision is healthy, increase the share in steps — 10, 50, then 100 — and if it is not, the fix is one command:

gcloud run services update-traffic hello --region us-central1 --to-latest

That sends all traffic back to the latest healthy revision, and the failed revision stays available for inspection. Two habits make this workflow reliable. First, use revision tags for testing: a tag gives a revision a stable URL, so you can run smoke tests against the exact revision before it receives production traffic. Second, keep rollouts short: a ten-percent split left running for a week is not a rollout, it is two production versions, and it doubles the surface you have to monitor, debug and pay for. Roll forward or roll back, and retire the old revision once the new one has proven itself.

One more detail: Cloud Run runs a deploy health check by default, starting a single instance of the new revision and waiting for its startup probe to pass before the deployment succeeds. That catches the most common deployment failures — a container that crashes on startup — before any traffic reaches the revision. If you disable the check, the startup probe only runs when the revision is first invoked or when min instances are set, which means a broken revision can sit undetected until a user finds it.

Security, Networking and Connecting to Google Cloud Services

A Cloud Run service is private by default: it requires authentication, and only callers with the right IAM permission can invoke it. The –allow-unauthenticated flag used in this tutorial makes a service public, which is fine for a demo and correct for a genuinely public API, but it should be a deliberate choice rather than a habit. For a service that should only be called by your own systems, leave authentication on and grant the Cloud Run Invoker role to the specific service account that calls it. That is the whole access model: there is no API key to leak and no password to rotate, just IAM, and the caller’s identity is the service account.

Give the service itself an identity too. By default a revision runs as the Compute Engine default service account, which usually has far more permission than a single service needs. Create a dedicated service account for the service, grant it only the roles it requires — read a specific Cloud Storage bucket, publish to a specific Pub/Sub topic, connect to a specific Cloud SQL instance — and deploy with –service-account. When the service calls a Google Cloud API, Cloud Run uses that service identity, so the permissions you grant are the permissions the code gets, and nothing more. This is the single highest-value security practice on Cloud Run, and it costs nothing to do.

Secrets deserve the same discipline. Never bake a secret into a container image or an environment variable that shows up in the console: use Secret Manager, and mount the secret as an environment variable or a volume so the value is delivered at runtime. The same rule applies to database passwords, API keys and private keys. If you can read the secret by describing the service, it is not a secret — it is configuration.

Networking is the last piece. By default a Cloud Run service reaches the public internet and Google Cloud APIs, and it can be reached from the internet if it is public. To reach resources inside your VPC — a Cloud SQL instance with private IP or a Memorystore instance — attach a VPC connector or use Direct VPC egress. To stop the internet reaching a service at all, set ingress to internal-only, so only traffic from within Google Cloud can invoke it. And for traffic between your own services, use service-to-service authentication with the caller’s identity token rather than opening the receiving service to the world.

Logging and monitoring come free with the platform and are worth setting up before you need them. Cloud Run sends stdout and stderr to Cloud Logging automatically, structured JSON logs are parsed into fields you can filter on, and request metrics, instance counts and error rates appear in Cloud Monitoring without any agent to install. Add an uptime check and an alert on error rate before the service matters, not after the first outage.

Frequently Asked Questions

How much does Cloud Run cost?

Cloud Run bills for the requests your instances serve and the CPU and memory they use while running, and a service scaled to zero uses no compute. This guide gives no prices because they change by region and over time — check the Cloud Run pricing page and the pricing calculator for your region before estimating, and set a budget alert on the project so a traffic spike cannot turn into a surprise bill.

Why is my Cloud Run service returning 403 or 503 errors?

A 403 usually means the service requires authentication and the caller has no Invoker permission — either grant the role or deploy with –allow-unauthenticated if the service is meant to be public. A 503 usually means no instance is ready: the container is still starting, it crashed on startup, or max instances is too low for the traffic. Check the revision’s logs first; a crash loop and a cold-start backlog look the same from the outside and have different fixes.

Can Cloud Run run a container that does not serve HTTP?

Yes, as a job or a worker pool rather than a service. A Cloud Run job runs a container to completion on demand or on a schedule, which suits batch work, migrations and report generation. A worker pool runs always-on background workloads such as queue consumers. A service is for HTTP request handling; if your container never listens on a port, deploy it as a job instead of fighting the service model.

How do I fix Cloud Run cold starts?

Make the container start fast by listening on PORT before doing other work, initializing clients lazily and keeping the image small; enable startup CPU boost so new instances get extra CPU while they initialize; and set min instances to keep at least one instance warm for latency-sensitive services. Min instances cost money and are a target rather than a guarantee, so use them for user-facing APIs and leave them at zero for workloads nobody waits on.

Should I use Cloud Run or GKE for my application?

Use Cloud Run when your workload fits in a container, answers HTTP requests or runs to completion, and benefits from scaling to zero without cluster management. Use GKE when you need Kubernetes features such as persistent volumes, DaemonSets or custom schedulers, or when you already run a large Kubernetes estate. Many teams use both: Cloud Run for APIs and event handlers, GKE for the stateful or specialized workloads that need a cluster. If you want the credential that covers this material, our GCP certification roadmap maps the path.

Conclusion

Cloud Run rewards a simple mental model: a service is a container with a URL, a revision is a frozen deploy, and an instance is a running copy that appears when traffic arrives and disappears when it leaves. Everything else — concurrency, min instances, traffic splitting, IAM, VPC egress — is a control on that model, and you now know what each control does and when to reach for it. The next step is to build something real with it: take an API you already run, containerize it, deploy it with the commands in this tutorial, and put a gradual rollout and a budget alert around it before it matters.

Scroll to Top