Home Google CloudDeploy Containers to Google Cloud Run: Step-by-Step Guide

Deploy Containers to Google Cloud Run: Step-by-Step Guide

by Knowledge Base Linux
Deploy Containers to Google Cloud Run — Deploy Containers to Google Cloud Run: Step-by-Step Guide

Running containers in production usually means managing a Kubernetes cluster, node pools, and networking — heavy machinery for a simple API or web service. Google Cloud Run removes that burden: you give it a container image, and it runs your code on a fully managed, autoscaling serverless platform that scales to zero when idle. In this guide, you will containerize a small app, push the image to Artifact Registry, deploy it to Google Cloud Run with the gcloud CLI, and tune the container port, concurrency, and min/max instance settings like a production setup.

Technical diagram showing a container image deployed to Google Cloud Run with autoscaling instances

Technical diagram showing a container image deployed to Google Cloud Run with autoscaling instances

What Is Google Cloud Run? – Deploy Containers to Google Cloud Run

Google Cloud Run is a managed compute platform that runs stateless containers over HTTP. You do not provision servers, clusters, or node pools. Each revision of your service automatically scales horizontally based on incoming request load — from zero instances (you pay nothing while idle) up to the maximum you configure — and Google handles TLS, load balancing, and logging.

The contract is simple, and your container must honor it:

  • The container must listen on the port given by the PORT environment variable (default 8080) on all interfaces (0.0.0.0).
  • The container should be stateless: any local filesystem writes disappear when the instance stops.
  • The container should start quickly and shut down gracefully within 10 seconds on SIGTERM.

Prerequisites – Deploy Containers to Google Cloud Run

  • A Google Cloud project with billing enabled and the Cloud Run, Artifact Registry, and Cloud Build APIs enabled.
  • The gcloud CLI installed and authenticated (gcloud auth login and gcloud config set project PROJECT_ID). New to the CLI? Start with our gcloud CLI installation and first commands guide.
  • Docker installed locally for building and testing the image.

Set a few variables you will reuse throughout the guide:

export PROJECT_ID="my-project-id"
export REGION="us-central1"
export REPO="apps"
export SERVICE="hello-api"

Step 1: Build a Container That Honors the Google Cloud Run Contract

Create a minimal Node.js API. The critical detail is reading the PORT environment variable that Google Cloud Run injects at runtime:

// server.js
const http = require('http');

const port = process.env.PORT || 8080;

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ status: 'ok', served_by: process.env.K_SERVICE || 'local' }));
});

server.listen(port, '0.0.0.0', () => {
  console.log(`Listening on port ${port}`);
});

Pair it with a lean Dockerfile. Note the --omit=dev flag to keep the image small:

FROM node:20-slim
WORKDIR /app
COPY package.json ./
RUN npm install --omit=dev
COPY server.js ./
EXPOSE 8080
CMD ["node", "server.js"]

Build and test locally, passing a PORT value the same way Cloud Run will:

docker build -t hello-api:local .
docker run --rm -p 8080:8080 -e PORT=8080 hello-api:local
curl -s http://localhost:8080/ | head -c 200; echo

If that returns JSON, your container honors the contract. If your use case truly needs orchestration instead, compare with our tutorial on how to create a GKE cluster and deploy your first application.

Step 2: Push the Image to Artifact Registry

Cloud Run pulls images from Artifact Registry (or any accessible registry). Create a Docker repository and push the image using Cloud Build so the build itself runs on Google infrastructure:

gcloud artifacts repositories create "$REPO" \
  --repository-format=docker \
  --location="$REGION" \
  --description="Application container images"

gcloud builds submit --tag \
  "$REGION-docker.pkg.dev/$PROJECT_ID/$REPO/hello-api:v1" .

The full image path follows the pattern REGION-docker.pkg.dev/PROJECT_ID/REPOSITORY/IMAGE:TAG. Keep tags immutable per release (v1, v2) rather than reusing latest — it makes rollbacks predictable.

Step 3: Deploy to Google Cloud Run with gcloud run deploy

The core deployment command is gcloud run deploy. This first deploy creates the service, sets the container port explicitly, and opens it to public traffic:

gcloud run deploy "$SERVICE" \
  --image "$REGION-docker.pkg.dev/$PROJECT_ID/$REPO/hello-api:v1" \
  --region "$REGION" \
  --allow-unauthenticated \
  --port 8080

The command prints a Service URL like https://hello-api-abc123-uc.a.run.app. Verify it:

SERVICE_URL=$(gcloud run services describe "$SERVICE" \
  --region "$REGION" --format 'value(status.url)')
curl -s "$SERVICE_URL" | head -c 200; echo

Useful flags worth knowing at deploy time:

  • --set-env-vars "KEY=value,KEY2=value2" — inject configuration without rebuilding the image.
  • --memory 512Mi and --cpu 1 — size the instance (CPU options include fractional values like 0.5).
  • --no-allow-unauthenticated — keep the service private and require IAM invoker permission.
  • --service-account NAME@PROJECT_ID.iam.gserviceaccount.com — run with least-privilege identity instead of the default compute account.

Step 4: Tune Concurrency and Min/Max Instances on Google Cloud Run

Three settings control how Google Cloud Run scales your service, and getting them right is the difference between a cheap side project and a production-grade deployment.

Container port

We already set --port 8080 to match the EXPOSE directive and the app’s default. If your image listens on a different port (for example 3000), change the flag — do not rebuild the image just to remap the port. The app must still read the PORT environment variable; the flag only tells Cloud Run which port to probe.

Concurrency: requests per instance

Concurrency is how many requests one container instance handles simultaneously (default 80, maximum 1000). A Node.js or Go service that is truly async can safely raise it; a single-threaded, CPU-bound worker should lower it toward 1. Set it explicitly:

gcloud run services update "$SERVICE" \
  --region "$REGION" \
  --concurrency 40

Min and max instances

--min-instances keeps warm instances always running, eliminating cold starts at the cost of paying for idle capacity. --max-instances caps your bill during traffic spikes or retry storms. For a production API:

gcloud run services update "$SERVICE" \
  --region "$REGION" \
  --min-instances 1 \
  --max-instances 20

Watch scaling behavior live with the built-in metrics:

gcloud monitoring time-series list \
  --filter='metric.type="run.googleapis.com/container/instance_count"' \
  --project="$PROJECT_ID" | head -20

For background on reading these metrics, the official Cloud Run deployment documentation covers every gcloud run deploy flag in detail.

Troubleshooting Common Google Cloud Run Issues

“Container failed to start” and the revision never becomes ready

The number one cause is the container not listening on $PORT. Hard-coding port 8080 while Cloud Run probes the port from the PORT variable is the classic mistake — always bind process.env.PORT (or your language’s equivalent) on 0.0.0.0. Check the logs: gcloud run services logs read "$SERVICE" --region "$REGION" --limit 50.

HTTP 403 when calling the service

The service is private. Either redeploy with --allow-unauthenticated for public access, or grant the caller the roles/run.invoker IAM role and authenticate with an identity token.

Cold starts on the first request

With --min-instances 0 (the default), an idle service scales to zero and the next request waits for a fresh container boot. Set --min-instances 1 for latency-sensitive endpoints, or accept the trade-off for batch-style workloads.

Costs spike unexpectedly

An unbounded --max-instances combined with high concurrency retries can multiply your bill. Set an explicit maximum, enable Cloud Billing budgets with alerts, and review the run.googleapis.com/container/billable_instance_time metric after load tests.

Conclusion

You have taken a container from local Docker build to a production-tuned Google Cloud Run service: image stored immutably in Artifact Registry, deployed with gcloud run deploy, port wired through the PORT environment variable, and scaling bounded by explicit concurrency, min-instance, and max-instance settings. Next steps to explore: traffic splitting for canary revisions, connecting a custom domain with automatic TLS, and wiring Cloud Run to Pub/Sub or Cloud Scheduler for event-driven workloads.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.