GCP Compute: Cloud Run, Functions and GKE
Google Cloud offers three serverless-to-managed options for running application code in containers. Cloud Run functions run a single function in response to an HTTP request or an event. Cloud Run runs any stateless container that listens for requests, or a job that runs to completion. Google Kubernetes Engine (GKE) gives you the full Kubernetes API with a Google-managed control plane. They share a lot: all three run containers built from your code, read secrets from Secret Manager, run as a service account, and pull images from Artifact Registry.
The running example is an invented OrdersPortal shop in the project ordersportal-prod, region europe-west2 (London): an order-status function, an orders-api service on Cloud Run, and a GKE cluster for the warehouse system. Commands are for the current Google Cloud CLI (gcloud) and were checked against Google Cloud’s documentation in November 2026; they were not run here because they need a billing-enabled project. The one local sample (a Python function served by the Functions Framework 3.10) was run, and its output is shown.
Topics on this page
Section titled “Topics on this page”| Topic | What it answers |
|---|---|
| Choosing a compute service | Which of the three fits a workload |
| Cloud Run functions | Writing, testing and deploying event-driven functions |
| Cloud Run | Deploying containers, scaling, configuration and traffic splitting |
| Artifact Registry and Cloud Build | Where images live and how they are built |
| Google Kubernetes Engine | Autopilot and Standard clusters, node pools and autoscaling |
| Workload Identity Federation for GKE | Calling Google APIs from pods without keys |
Choosing a compute service
Section titled “Choosing a compute service”| Cloud Run functions | Cloud Run | GKE | |
|---|---|---|---|
| Unit you deploy | A function (source code) | A container image, or source built into one | Kubernetes manifests (Deployments, Services, and so on) |
| Runtime | Supported language runtimes | Anything in a Linux container | Anything in a container, plus DaemonSets, StatefulSets, operators |
| Scaling | Per request or event, to zero | Per request, to zero (or minimum instances) | Pods via HorizontalPodAutoscaler; nodes via Autopilot or cluster autoscaler |
| Request timeout | Up to 60 minutes for HTTP functions; up to 9 minutes for event-driven functions | Up to 60 minutes per request | No platform limit |
| Billing | Like Cloud Run (functions are Cloud Run services) | Request-based by default, or instance-based | Cluster management fee plus nodes (Standard) or pod resource requests (Autopilot) |
| You operate | Code only | Container and configuration | Cluster configuration, upgrades policy, workloads |
Start with the least operational option that meets the requirement. Move from a function to a Cloud Run service when you need several routes, a framework or a custom binary; move to GKE when you need Kubernetes features (stateful sets, sidecars and service mesh at scale, custom controllers, GPUs on node pools you control) or already run many services on Kubernetes.
Cloud Run functions
Section titled “Cloud Run functions”Cloud Functions was renamed Cloud Run functions in 2024: functions are now deployed as Cloud Run services built from your source with Google’s buildpacks, so they share Cloud Run’s scaling, networking and billing. Functions created through the Cloud Functions v2 API can still be managed with gcloud functions; for new functions Google documents gcloud run deploy with the --function flag.
A function is a handler registered with the open-source Functions Framework, which also lets you run it locally. This one returns the status of an order:
import functions_framework
ORDERS = {"ORD-1042": {"status": "shipped", "carrier": "Parcelo"}}
@functions_framework.httpdef order_status(request): order_id = request.args.get("id", "") order = ORDERS.get(order_id) if order is None: return {"error": f"unknown order {order_id!r}"}, 404 return {"id": order_id, **order}pip install functions-frameworkfunctions-framework --target=order_status --port=8085curl "http://localhost:8085/?id=ORD-1042"curl -w " %{http_code}" "http://localhost:8085/?id=ORD-9999"{"carrier":"Parcelo","id":"ORD-1042","status":"shipped"}{"error":"unknown order 'ORD-9999'"} 404Deploy from the source folder. --base-image selects the language runtime (for example python314 or nodejs24; check the runtime list for current versions and retirement dates), and Google patches the base image without a redeploy:
gcloud run deploy order-status \ --source . \ --function order_status \ --base-image python314 \ --region europe-west2 \ --no-allow-unauthenticatedEvent-driven functions receive CloudEvents from Eventarc, for example when an invoice PDF is uploaded to a bucket or a message arrives on a Pub/Sub topic:
# fragment: CloudEvent handler for a Cloud Storage "object finalized" eventimport functions_framework
@functions_framework.cloud_eventdef on_invoice_upload(cloud_event): data = cloud_event.data print(f"New invoice {data['name']} in bucket {data['bucket']} ({data.get('size')} bytes)")The trigger is created separately with gcloud eventarc triggers create, filtering on type=google.cloud.storage.object.v1.finalized and the bucket name, and naming a service account that may invoke the function. Event delivery is at least once, so handlers must be idempotent: processing the same upload twice must not create two invoices.
Pitfalls:
- Retired runtimes. Runtimes have published deprecation and decommission dates (Node.js 20 and Python 3.10, used in many older tutorials, are at or near the end of support). Pick the newest generally available runtime for new functions.
- Public by accident.
--allow-unauthenticatedmakes the function callable by anyone on the internet. Leave it off unless the endpoint is meant to be public, and grantroles/run.invokerto the callers that need it.
Cloud Run
Section titled “Cloud Run”Cloud Run runs stateless containers. The container must listen on the port in the PORT environment variable (8080 by default), start quickly and keep no state on local disk between requests. Each instance handles up to 80 concurrent requests by default (configurable), and Cloud Run adds instances as traffic grows and removes them, down to zero, when it stops.
# Build from source with Cloud Build and deploy in one stepgcloud run deploy orders-api --source . --region europe-west2
# Or deploy an image you built and pushed yourselfgcloud run deploy orders-api \ --image europe-west2-docker.pkg.dev/ordersportal-prod/apps/orders-api:1.4.0 \ --region europe-west2 \ --service-account orders-api@ordersportal-prod.iam.gserviceaccount.com \ --memory 512Mi --cpu 1 \ --concurrency 40 \ --min-instances 1 --max-instances 20 \ --timeout 300 \ --set-env-vars LOG_LEVEL=info \ --set-secrets DB_PASSWORD=orders-db-password:3--set-secrets can expose a Secret Manager secret as an environment variable (as above) or as a mounted file (/secrets/db=orders-db-password:3). Pin a version number in production; latest changes the value at the next instance start without a deployment.
Billing. With the default request-based billing, CPU is allocated only while a request is being processed and you pay for that time; the free tier includes 2 million requests a month. Instance-based billing keeps CPU allocated for the instance’s whole lifetime, which suits background work after the response and steady high traffic. --min-instances avoids cold starts at the price of paying for idle instances.
Revisions and traffic. Every deployment creates an immutable revision. Deploy a new revision without traffic, test it on a tagged URL, then shift traffic gradually:
gcloud run deploy orders-api --image .../orders-api:1.5.0 --no-traffic --tag canary --region europe-west2gcloud run services update-traffic orders-api --to-tags canary=10 --region europe-west2gcloud run services update-traffic orders-api --to-latest --region europe-west2 # promoteFor work that runs to completion instead of serving requests (a nightly export, a database migration), use Cloud Run jobs (gcloud run jobs create and gcloud run jobs execute), which run one or many parallel tasks with retries.
Pitfalls:
- Background work after the response with request-based billing. CPU is throttled once the response is sent, so the work stalls. Use instance-based billing, Cloud Tasks or a job.
- Local state. Files written to the container’s filesystem live in memory and disappear with the instance. Use Cloud Storage, a database or a mounted volume.
Artifact Registry and Cloud Build
Section titled “Artifact Registry and Cloud Build”Container images live in Artifact Registry, in repositories addressed as REGION-docker.pkg.dev/PROJECT/REPOSITORY/IMAGE:TAG. Container Registry (gcr.io hosted by Container Registry) was shut down in 2025; gcr.io addresses now only work when they are backed by Artifact Registry gcr.io repositories, so update old build files that push to gcr.io/PROJECT/....
# cloudbuild.yaml: build, push and deploy orders-apisteps: - name: gcr.io/cloud-builders/docker args: ["build", "-t", "europe-west2-docker.pkg.dev/$PROJECT_ID/apps/orders-api:$SHORT_SHA", "."] - name: gcr.io/cloud-builders/docker args: ["push", "europe-west2-docker.pkg.dev/$PROJECT_ID/apps/orders-api:$SHORT_SHA"] - name: gcr.io/google.com/cloudsdktool/cloud-sdk entrypoint: gcloud args: ["run", "deploy", "orders-api", "--image", "europe-west2-docker.pkg.dev/$PROJECT_ID/apps/orders-api:$SHORT_SHA", "--region", "europe-west2"]images: - europe-west2-docker.pkg.dev/$PROJECT_ID/apps/orders-api:$SHORT_SHAThe builder images themselves (gcr.io/cloud-builders/docker) are Google-owned images that still use gcr.io addresses; that is expected. $SHORT_SHA is populated when the build is started by a trigger connected to a repository. Tag images with the commit, not only latest, so every revision can be traced to source.
Google Kubernetes Engine
Section titled “Google Kubernetes Engine”GKE runs upstream Kubernetes with the control plane operated by Google. Two modes exist:
- Autopilot (the recommended default): Google provisions and manages nodes; you deploy workloads and pay for the CPU, memory and storage your pods request. Security hardening and Workload Identity Federation are on by default.
- Standard: you create and size node pools (machine types, GPUs, spot VMs) and pay for the nodes’ Compute Engine instances whether pods use them or not.
Every cluster pays a cluster management fee of $0.10 per hour; the GKE free tier gives each billing account $74.40 of monthly credit, which covers one Autopilot or zonal Standard cluster (not a regional Standard cluster).
# Autopilot cluster (regional by design)gcloud container clusters create-auto warehouse --region europe-west2 --release-channel regular
# Standard cluster with an autoscaling node poolgcloud container clusters create warehouse-std --region europe-west2 \ --num-nodes 1 --machine-type e2-standard-4 \ --enable-autoscaling --min-nodes 1 --max-nodes 5 \ --workload-pool ordersportal-prod.svc.id.goog
# Connect kubectl (needs the gke-gcloud-auth-plugin component)gcloud container clusters get-credentials warehouse --region europe-west2kubectl get nodesWith --region, a Standard cluster’s --num-nodes is per zone, so 1 means three nodes across three zones. Workloads use normal Kubernetes manifests; a Service of type LoadBalancer provisions a Google Cloud load balancer, and the Gateway API or Ingress gives HTTP(S) routing with managed certificates. Upgrades follow the cluster’s release channel (Rapid, Regular, Stable, or Extended for a longer support window); configure maintenance windows and exclusions instead of pinning versions forever.
Pitfalls:
- Pods without resource requests on Autopilot. Autopilot applies defaults and bills by requests, so set realistic CPU and memory requests for each container.
- Using GKE for one stateless API. The cluster fee, upgrades and Kubernetes skills cost more than the workload. Cloud Run is usually the better fit until you have many services or need Kubernetes features.
Workload Identity Federation for GKE
Section titled “Workload Identity Federation for GKE”Pods should call Google APIs (Cloud Storage, Pub/Sub, BigQuery) as an identity without service account key files. With Workload Identity Federation for GKE (enabled by default on Autopilot, and with --workload-pool on Standard), you grant IAM roles directly to a Kubernetes ServiceAccount, identified by a principal string that includes the project number, namespace and ServiceAccount name:
kubectl create serviceaccount stock-sync --namespace warehouse
gcloud storage buckets add-iam-policy-binding gs://ordersportal-stock-feeds \ --role roles/storage.objectViewer \ --member "principal://iam.googleapis.com/projects/123456789012/locations/global/workloadIdentityPools/ordersportal-prod.svc.id.goog/subject/ns/warehouse/sa/stock-sync"Pods that run with serviceAccountName: stock-sync then get short-lived credentials automatically through the client libraries. The older pattern, binding the Kubernetes ServiceAccount to a Google service account with roles/iam.workloadIdentityUser and an iam.gke.io/gcp-service-account annotation, still works and is needed for the few services that do not accept the principal form. Use one Kubernetes ServiceAccount per workload: a grant to a namespace’s default ServiceAccount applies to every pod that uses it.
Interview questions
Section titled “Interview questions”1. Cloud Run or Cloud Run functions for a webhook receiver? A function if it is one handler with a supported runtime and no framework; a Cloud Run service if it has several routes, uses a web framework or a custom binary, or you want to control the container. Both scale to zero and are billed the same way, so the choice is mostly about packaging and code organization.
2. A Cloud Run service sends emails after returning the response, and some emails never go out. Why? With request-based billing, CPU is only allocated during request processing, so work after the response is throttled and can be lost when the instance scales down. Do the work before responding, switch to instance-based billing, or hand it to Cloud Tasks or Pub/Sub.
3. When would you choose GKE Standard over Autopilot? When you need node-level control Autopilot does not offer or that is cheaper on Standard: specific machine families, privileged workloads, custom node images, or very high, steady utilization where bin-packing your own nodes costs less than paying per pod request.
4. How do pods on GKE authenticate to Cloud Storage without a key file? Workload Identity Federation for GKE: grant the IAM role to the Kubernetes ServiceAccount’s principal (or bind it to a Google service account), run the pod with that ServiceAccount, and the client libraries obtain short-lived tokens from the GKE metadata server.
5. Senior scenario: OrdersPortal runs 25 microservices on Compute Engine VMs. How do you plan the move? Classify services: stateless HTTP services move to Cloud Run first (fast wins, scale to zero, per-service IAM); event consumers become functions or Cloud Run services behind Eventarc or Pub/Sub; anything needing Kubernetes features, sidecars or long-running stateful processes goes to a GKE Autopilot cluster. Standardize builds to Artifact Registry with Cloud Build or GitHub Actions using Workload Identity Federation, move secrets to Secret Manager, give each service its own service account, and migrate traffic per service with revision tags and gradual traffic shifts, keeping the VMs until error rates and latency match.
Related pages
Section titled “Related pages”- Google Cloud overview and IAM — resource hierarchy, gcloud and identity
- Cloud Storage and BigQuery — where the services keep their data
- Kubernetes — the platform underneath GKE
- Docker — building the container images these services run