This resume is also available in English.

6. Deploying the system8 / 14 · All columns

Columns › 6. Deploying the system › Part 35

Deploying on GCP: Running Container Services on Cloud Run

在 GCP 上部署:用 Cloud Run 跑容器服務

Move the shop onto Google Cloud with Cloud Run as the main path: map AWS services to their GCP counterparts and compare Compute Engine, GKE, App Engine, Cloud Run functions and Cloud Storage with Cloud CDN; explain services, revisions, instances, the container contract, concurrency and billing with diagrams; then deploy step by step, split traffic, wire up Secret Manager and Cloud SQL, set up private services and a load balancer, and automate releases with GitHub Actions and Workload Identity Federation.

  • GCP
  • Cloud Run
  • Serverless
  • DevOps
  • CI/CD
In this article
  1. What this article solves
  2. Step 1: Choose a platform: six paths on GCP
  3. Step 2: GCP's building blocks: projects, regions, VPC and service accounts
  4. Step 3: Cloud Run's three nouns: service, revision, instance
  5. Step 4: The container contract: what Cloud Run expects of your code
  6. Step 5: Scaling, concurrency, cold starts and billing
  7. Step 6: Deploy the first service, step by step
  8. Step 7: Revisions and traffic splitting: canaries and rollback
  9. Step 8: Secrets and the database
  10. Step 9: Private services, calls between services and the public entry point
  11. Step 10: CI/CD: GitHub Actions deploying through Workload Identity Federation
  12. Step 11: Observability, cost, and when to move to GKE
  13. Common pitfalls
  14. Key takeaways
  15. References
  16. Next

The previous article, “Deploying on AWS: EKS and Elastic Scaling”, put the shop on EKS and scaled pods, nodes and data in three layers; the one before it, “Deploying on AWS: Running Container Services on ECS Fargate”, took another route: no nodes to manage, just containers and task definitions. This article moves to Google Cloud (GCP), and the main path is Cloud Run, which belongs to the same family as ECS Fargate but goes one step further: you do not decide on a cluster or on how many copies of a service run; the platform starts and stops instances according to requests. We first map AWS names to GCP, then explain each Cloud Run concept with a diagram, and finally deploy the four services step by step and connect them to the database, secrets, a private network and CI/CD.

What this article solves

The shop has decided to open a new environment on GCP: data must stay in the Taiwan region, the team has three people, and nobody wants to maintain Kubernetes cluster upgrades and add-ons. Earlier articles have already produced what we need: a container image per service (“Deploying One Go Service with Docker and Kubernetes”), graceful shutdown on SIGTERM (“Configuration and Graceful Shutdown in Go”), PostgreSQL and NATS JetStream. Following a quick-start guide, order goes onto Cloud Run and has a URL within five minutes, and then a series of problems appears:

  • The URL is public; anyone can call order directly and bypass the authentication in api-gateway.
  • The service runs as the default service account, whose permissions are broad enough to change the whole project.
  • The database password sits in an environment variable and shows up in the shell history of the deploy command.
  • During a flash sale order jumps to a hundred instances, each opening twenty connections, and Cloud SQL runs out of connections.
  • inventory consumes NATS events in the background and often seems to “do nothing” once deployed: with no requests coming in, its CPU is throttled and messages are not processed.
  • Every new version receives all traffic the moment it is deployed, and when something breaks, someone scrambles to find the previous version.

None of these are Cloud Run's fault; they come from not understanding its model first. This article works through the following, step by step:

  1. Choosing a platform: map AWS services to GCP and compare Cloud Run, Compute Engine, GKE, App Engine, Cloud Run functions and Cloud Storage with Cloud CDN: which scenario each fits and when not to use it.
  2. GCP's building blocks: projects, regions, the global VPC, service accounts, and the shop's architecture on GCP.
  3. Cloud Run's three nouns: service, revision, instance.
  4. The container contract: PORT, statelessness, the 10-second SIGTERM grace period, and Go code that honours the contract.
  5. Scaling, concurrency, cold starts and the two billing modes.
  6. Deploying the first service step by step: Artifact Registry, a service account, gcloud run deploy, and declarative YAML.
  7. Revisions and traffic splitting: tags, preview URLs, canaries and rollback.
  8. Secrets and the database: Secret Manager, three ways to reach Cloud SQL, the connection budget, and migrations with Cloud Run jobs.
  9. Private services: ingress settings, ID tokens between services, Direct VPC egress, the external load balancer, and where event consumers belong.
  10. CI/CD: GitHub Actions deploying through Workload Identity Federation, with deployer and runtime identities kept apart.
  11. Observability, cost, and when to move to GKE.

Step 1: Choose a platform: six paths on GCP

First, map the familiar AWS names to GCP. The names differ, but the roles correspond roughly one to one:

AWSGCPNotes
ECS on FargateCloud RunYou hand over containers; Cloud Run even sets the instance count from requests and can scale to 0
EKSGKE (Autopilot or Standard)Managed Kubernetes
EC2 + Auto Scaling GroupCompute Engine + managed instance group (MIG)Virtual machines and groups of machines cloned from a template
ECRArtifact RegistryRepository for container images and packages
ALBCloud Load Balancing (Application Load Balancer)GCP's external Application Load Balancer can be global: one IP serves users everywhere
RDS for PostgreSQLCloud SQL for PostgreSQLManaged database; high availability means two zones in one region
Secrets ManagerSecret ManagerStorage, versioning and access control for secrets
CloudWatch Logs / MetricsCloud Logging / Cloud MonitoringLogs and metrics; Cloud Run's standard output goes to Cloud Logging automatically
IAM roles (for workloads)Service accountsCode runs as an identity, and permissions are bound to that identity
LambdaCloud Run functionsWrite a single function, triggered by events or HTTP (formerly Cloud Functions)
S3 + CloudFrontCloud Storage + Cloud CDNStatic files and edge caching
Route 53 / ACMCloud DNS / Google-managed SSL certificatesDomains and certificates
ElastiCacheMemorystoreManaged Redis-compatible cache
NAT gatewayCloud NATEgress for private resources

One difference is worth remembering up front: an AWS VPC belongs to one region, whereas a GCP VPC is global and only its subnets are regional. On GCP, subnets in Taiwan (asia-east1) and Tokyo (asia-northeast1) can sit in the same VPC and talk over internal IPs without any peering.

Next, the six ways to run code on GCP. From left to right in the diagram below, you manage less and less, and you can tune less and less:

You manage and tune more Google manages more, you tune less Compute Engine + MIG machine image startup script legacy, GPUs NATS cluster GKE Standard node pools + YAML platforms that control nodes GKE Autopilot YAML (no nodes) already on Kubernetes Cloud Run container image stateless APIs spiky traffic Cloud Run functions one function event glue small jobs Cloud Storage + Cloud CDN static files front ends, docs, images What you hand over Fits App Engine is an older platform service near Cloud Run; new containerised projects usually pick Cloud Run.

Figure: Compute Engine leaves the operating system to you; GKE Standard leaves node pools to you, while Autopilot has Google manage nodes; Cloud Run takes only a container; Cloud Run functions take only a function; a static site has no server at all, just files in Cloud Storage behind Cloud CDN. App Engine is an older platform service that sits near Cloud Run.

OptionWhat you manageFitsWhyDoes not fit
Cloud Run (services)A container image and a few settingsStateless HTTP/gRPC services, spiky traffic, small teamsScales on requests, scales to 0, pay-per-use, no nodes or clusterStateful servers (databases, NATS), fixed inbound IPs, DaemonSet-style agents
Compute Engine + MIGOS, startup scripts, machine imagesLong-running programs needing special kernel settings or GPUs, legacy systems not yet containerised, a self-managed NATS clusterThe whole machine is yours; a MIG clones from a template, auto-heals and autoscalesMany small services scaling independently, frequent deploys; you schedule OS patching yourself
GKE AutopilotKubernetes resources (YAML)Already on Kubernetes, many services, need for Operators and the GitOps ecosystemKeeps the Kubernetes API, Google manages nodes, billed by pod resource requestsOnly a few stateless services; privileged containers or custom node settings
GKE StandardNode pools, upgrade strategy, Kubernetes resourcesLarge platforms that need control over nodes (machine types, GPUs, kernel parameters, DaemonSets)The most tunable; committed use discounts can lower the cost of steady loadNobody on the team can operate a cluster
App EngineCode and app.yamlExisting App Engine applicationsAn early fully managed platform that still worksNew projects: once containerised, Cloud Run offers more choice
Cloud Run functionsOne functionEvent glue: thumbnails after an upload, small jobs triggered by Pub/Sub messagesNo server code or Dockerfile; wire up the event source and it runsFull API services; code with many endpoints and shared middleware
Cloud Storage + Cloud CDNBuilt static filesSingle-page front ends, documentation sites, product imagesNo servers, and edge caching makes it fast everywherePages that need server-side computation

The shop's choices:

  • api-gateway, order and payment run as Cloud Run services. They are stateless HTTP services whose traffic is concentrated in sale periods and is light the rest of the time; scaling on requests and paying per use is a good match.
  • inventory runs as a Cloud Run worker pool. It is mainly a NATS consumer with no inbound requests; worker pools are the Cloud Run resource designed for programs that “work continuously in the background and have no URL”. Step 9 explains them.
  • NATS JetStream runs on Compute Engine. It writes to disk and needs a stable node identity: it is a stateful server and does not suit Cloud Run. Three VMs in three zones, each with a persistent disk.
  • The front end's static files go to Cloud Storage with Cloud CDN.

When would you go the other way and start with GKE? If you already have a full set of Kubernetes configuration (the one from “Deploying a Microservice System on Kubernetes”), need Argo CD and Operators, or already run dozens of services, GKE Autopilot lets you keep all that without managing nodes. Step 11 lists the signals for moving from Cloud Run to GKE.

Step 2: GCP's building blocks: projects, regions, VPC and service accounts

Global external Application LB + Cloud Armor Users Cloud Storage + Cloud CDN Project shop-prod Region asia-east1 (Taiwan) api-gateway service order service payment service inventory worker pool VPC shop-vpc (global) ← Cloud Run enters via Direct VPC egress Subnet run-asia-east1 IPs for Cloud Run Cloud SQL PostgreSQL private IP, HA pair Subnet data-asia-east1 NATS ×3 (Compute Engine) Cloud NAT fixed egress IP Cloud Run spreads across the region's zones itself; you pick zones for VMs and Cloud SQL. Managed (not in subnets) Artifact Registry images Secret Manager secrets, versions Cloud Logging / Monitoring Service accounts one per service Cloud DNS + managed certs

Figure: users enter api-gateway through a global external Application Load Balancer; the three Cloud Run services and the inventory worker pool reach into the VPC through Direct VPC egress, and from there Cloud SQL's private IP and NATS on Compute Engine. Artifact Registry, Secret Manager and Cloud Logging are regional or global managed services and do not live in subnets.

Reading the diagram from the outside in, one sentence per block:

  • Organisation and project. The project is GCP's basic unit: billing, enabled APIs, IAM permissions and quotas are all scoped to a project. The shop uses two projects, shop-dev and shop-prod. Splitting production from development makes permissions the easiest win: developers have broad rights in shop-dev and read-only access in shop-prod.
  • Regions and zones. asia-east1 is the Taiwan region, which contains several zones (asia-east1-a, -b, -c). Cloud Run and Artifact Registry are regional resources: you pick the region and Google spreads instances across its zones. For Cloud SQL and Compute Engine you choose zones yourself or turn on high availability.
  • VPC and subnets. The VPC is global; subnets belong to a region. The shop's shop-vpc has two subnets in asia-east1: run-asia-east1 for Cloud Run's Direct VPC egress and data-asia-east1 for the NATS VMs. Cloud SQL receives a private IP through private services access.
  • Service accounts. The identity code runs as on GCP, the counterpart of AWS IAM roles for workloads. Each Cloud Run service is given a service account; when the code calls a GCP API, the client libraries fetch a short-lived token for that identity from the metadata server, so there are no keys in the code.
  • Artifact Registry. Holds container images. An image address looks like asia-east1-docker.pkg.dev/shop-prod/shop/order:3f2a9c1d7e4b (region, project, repository, image, tag).
  • Secret Manager. Holds database passwords and the payment API key; each update creates a new version.
  • Cloud SQL. Managed PostgreSQL; production turns on high availability (primary and standby in two zones of the same region).
  • Cloud Logging / Cloud Monitoring. Every line the container writes to standard output lands in Cloud Logging; metrics such as request count, latency and instance count are available without installing anything.

Before starting, select the project and default region in gcloud and enable the APIs we will use (once per project):

gcloud config set project shop-prod
gcloud config set run/region asia-east1
gcloud services enable run.googleapis.com artifactregistry.googleapis.com \
  secretmanager.googleapis.com sqladmin.googleapis.com compute.googleapis.com \
  iamcredentials.googleapis.com

Step 3: Cloud Run's three nouns: service, revision, instance

Everything in Cloud Run revolves around three nouns. First, a diagram of how they relate:

Service order fixed URL traffic settings Revision order-00041 image a1b2… + settings Revision order-00042 image 3f2a… + settings 90% 10% instance instance instance instance 0 to N, by requests many requests each Revisions are immutable: each deploy or config change makes a new one; rollback = point traffic back.

Figure: the service order has a fixed URL and traffic settings; each deployment creates an immutable revision; traffic is split between revisions by percentage; each revision runs zero or more instances depending on load, and each instance handles several requests at once.

  • Service. A long-lived name such as order. It has a fixed URL, traffic settings (which revision gets what percentage), ingress and access control. The service itself runs no code.
  • Revision. Every deployment or configuration change (image, environment variables, memory, maximum instances…) creates a new revision with a name like order-00042-xuk. Revisions are immutable: each is a snapshot of “this image plus these settings”. Because they are immutable, rolling back is simply “point traffic at the old revision”, with no rebuild.
  • Instance. The container actually running. Cloud Run starts zero or more instances per revision according to incoming requests; after a while without requests, instances are shut down.

Compared with Kubernetes: a service is roughly “Service + HTTPRoute”, a revision is like “a ReplicaSet that is kept after every update”, and an instance is a pod. The difference is that Cloud Run's replica count is driven entirely by requests: you set bounds, but you cannot say “run 5” directly (worker pools are the exception).

Step 4: The container contract: what Cloud Run expects of your code

Cloud Run has only a few rules for containers, called the container contract. Each one has a reason:

RuleReasonSymptom when broken
Listen on the port given by PORT (default 8080)The platform chooses the port and forwards requests to itDeployment fails: the container did not start listening in time
Listen on 0.0.0.0, not just 127.0.0.1Requests come from outside the containerSame as above
The image must run on linux/amd64The contract requires Linux x86-64; multi-arch images must include linux/amd64An arm64 image built on an Apple-silicon laptop fails to deploy
Stateless: the filesystem is in memory and instances can go at any timeScaling relies on any instance being able to serve any requestUploaded files or sessions stored locally vanish on the next request
Exit within 10 seconds of SIGTERMOn scale-in or a new revision, the platform sends SIGTERM, then SIGKILL 10 seconds laterIn-flight requests are cut off and traces are lost

Two more details: Cloud Run injects three environment variables, K_SERVICE, K_REVISION and K_CONFIGURATION, so logging them tells you which revision produced an error; and some paths ending in z are reserved by the platform, and the documentation recommends avoiding all of them, so the /livez and /readyz used in the Kubernetes articles need new names here.

pull, start startup probe serving requests idle cleanup Cold start: the first request waits here 10 s grace SIGTERM SIGKILL Shorter cold starts: min instances, small images, little work at startup, CPU boost On SIGTERM: stop accepting → finish in-flight requests → close pools, flush traces

Figure: when a request arrives and no instance is available, the platform pulls the image, starts the container and waits for the startup probe to pass; that wait is the cold start. The instance then serves requests; after idling for a while or on a revision change, the platform sends SIGTERM, the code has 10 seconds to clean up, and then SIGKILL follows.

The code in “Configuration and Graceful Shutdown in Go” was written for Kubernetes: it has a 30-second grace period and fails readiness first, waiting a few seconds for endpoint lists to update. Cloud Run gives only 10 seconds, so the cleanup budget must be tighter: stop accepting connections, finish in-flight requests, close shared resources. Here is the entry point of order, complete and compilable:

package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"net"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

// Cloud Run sends SIGKILL 10 seconds after SIGTERM; cleanup must finish within that.
const shutdownBudget = 8 * time.Second

func main() {
	slog.SetDefault(newLogger(os.Stdout))

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	ln, err := net.Listen("tcp", listenAddr(os.Getenv))
	if err != nil {
		slog.Error("listen", "err", err)
		os.Exit(1)
	}
	if err := run(ctx, ln, routes()); err != nil {
		slog.Error("server stopped", "err", err)
		os.Exit(1)
	}
}

// listenAddr reads the PORT that Cloud Run injects, falling back to 8080 locally.
// An empty host means all interfaces (0.0.0.0); listening only on 127.0.0.1 would
// keep outside requests from reaching the server.
func listenAddr(getenv func(string) string) string {
	port := getenv("PORT")
	if port == "" {
		port = "8080"
	}
	return ":" + port
}

// newLogger writes JSON that Cloud Logging understands: severity and message fields.
func newLogger(w io.Writer) *slog.Logger {
	return slog.New(slog.NewJSONHandler(w, &slog.HandlerOptions{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if len(groups) > 0 {
				return a
			}
			switch a.Key {
			case slog.LevelKey:
				a.Key = "severity"
				if lv, ok := a.Value.Any().(slog.Level); ok && lv == slog.LevelWarn {
					a.Value = slog.StringValue("WARNING") // Cloud Logging uses WARNING, not WARN
				}
			case slog.MessageKey:
				a.Key = "message"
			}
			return a
		},
	}))
}

func routes() http.Handler {
	mux := http.NewServeMux()
	// Not /healthz: Cloud Run reserves some paths that end in z.
	mux.HandleFunc("GET /health", func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
	})
	mux.HandleFunc("POST /orders", func(w http.ResponseWriter, _ *http.Request) {
		time.Sleep(300 * time.Millisecond) // simulate a database write; the real handler is in earlier articles
		w.WriteHeader(http.StatusCreated)
	})
	return mux
}

// run serves requests until ctx is cancelled (SIGTERM); it then stops accepting
// connections and finishes in-flight requests within shutdownBudget.
func run(ctx context.Context, ln net.Listener, h http.Handler) error {
	srv := &http.Server{Handler: h, ReadHeaderTimeout: 5 * time.Second}
	errCh := make(chan error, 1)
	go func() { errCh <- srv.Serve(ln) }()
	slog.Info("listening", "addr", ln.Addr().String(), "revision", os.Getenv("K_REVISION"))

	select {
	case err := <-errCh:
		if errors.Is(err, http.ErrServerClosed) {
			return nil
		}
		return err
	case <-ctx.Done():
	}

	slog.Info("SIGTERM received, draining")
	sctx, cancel := context.WithTimeout(context.Background(), shutdownBudget)
	defer cancel()
	if err := srv.Shutdown(sctx); err != nil {
		_ = srv.Close()
		return fmt.Errorf("shutdown: %w", err)
	}
	// Close the database pool and flush buffered traces last.
	slog.Info("bye")
	return nil
}

The reasons behind a few choices:

  • run takes a net.Listener rather than an address. A test can pass a listener on a random port and check directly that “after cancellation, in-flight requests still complete and new connections are refused”.
  • An 8-second cleanup budget. Two seconds are left for closing the pool and flushing traces. Request handling itself should also be shorter than this budget; long-running work does not belong in a request (see Cloud Run jobs in Step 8).
  • Logs use severity and message. Cloud Logging parses each JSON line into a structured entry and recognises these two fields, so the log viewer can filter by severity. slog's WARN must become Cloud Logging's WARNING.

Verify locally the way Cloud Run will run it: build a linux/amd64 image, start it on a different port, then send SIGTERM.

docker buildx build --platform linux/amd64 -t order:local .
docker run -d --name order -e PORT=9090 -p 9090:9090 order:local
curl -i localhost:9090/health                 # HTTP/1.1 200 OK
curl -s -o /dev/null -w '%{http_code}\n' -X POST localhost:9090/orders &
docker stop -t 10 order                        # SIGTERM, SIGKILL only after 10 seconds
docker logs order                              # listening → SIGTERM received → bye

The POST /orders in flight when docker stop is issued still gets 201, the log shows listening, SIGTERM received, draining and bye in order, and the container exits with 0.

Step 5: Scaling, concurrency, cold starts and billing

These are the Cloud Run settings with the most effect on behaviour and on the bill. Start with concurrency:

Max concurrency 80 200 requests in progress at once Max concurrency 1 200 requests in progress at once instance ≤ 80 requests instance ≤ 80 requests instance ≤ 80 requests about 3 instances are enough needs 200 instances (70 drawn) instances Min 1: kept warm, no cold start for the first request Max 20: the ceiling that protects the database; excess requests queue

Figure: 200 requests are in progress at the same time. With maximum concurrency 80, about 3 instances are enough; with 1, you need 200. Minimum instances keep a few warm; maximum instances is the ceiling, and requests beyond it queue or are rejected.

  • Maximum concurrency (--concurrency). The most requests one instance handles at once, up to 1000. New services created with gcloud default to 80 per vCPU. It is a ceiling, not a target: when CPU is already busy, the platform sends fewer requests and starts new instances instead. Go servers handle many concurrent requests naturally; keep the default or tune it with load tests, and set 1 only when a single request saturates CPU or memory, or the code cannot handle two requests at once.
  • Minimum instances (--min-instances). Keeps that many instances alive so the first request does not wait for a cold start. The cost is that you pay even without requests.
  • Maximum instances (--max-instances). Defaults to 100 per revision. It is a valve that protects what sits downstream: with at most 20 order instances and 5 connections per pool, the database never sees more than 100 connections (Step 8).
  • Request timeout (--timeout). Defaults to 5 minutes, up to 60 minutes. The shop's APIs should never take that long; set 30 seconds so stuck requests fail early.
  • Startup CPU boost (--cpu-boost). Gives extra CPU during cold starts and is on by default for new services. Go binaries start quickly; most of the time goes into building connection pools and reading configuration.

Cold starts are the most frequently asked question about Cloud Run: with no idle instance, a request waits for the platform to pull the image, start the container and pass the startup probe. Ways to reduce them, in order of effect: set minimum instances, keep the image small (distroless plus a static binary), avoid heavy work at startup (for example, do not pre-warm caches at startup), and keep CPU boost on.

Next, billing. Cloud Run has two billing modes, and the difference is whether CPU is available when there are no requests:

Request-based billing (default, --cpu-throttling) request request request request CPU throttled CPU only while handling requests (and starting, stopping), billed only then; background goroutines all but stop. Instance-based billing (--no-cpu-throttling) CPU the whole time; background work keeps running Suits background work and steady traffic; billed even with no requests; needs at least 512MiB. CPU available (billed) CPU throttled

Figure: with request-based billing, CPU is available only while requests are being handled (and during startup and shutdown); between requests CPU is throttled and background goroutines all but stop. With instance-based billing, CPU is available for the instance's whole lifetime, and the whole lifetime is billed.

Billing modegcloud flagFitsDoes not fit
Request-based (default)--cpu-throttlingAPIs with sporadic or spiky traffic; code that only works inside requestsCode that keeps working after the response, or pulls messages in the background
Instance-based--no-cpu-throttlingSteady traffic, services with background work (flushing buffered metrics, async processing)Idle services: you pay for CPU even with no requests

These names are fairly new; older documentation calls them “CPU only allocated during request processing” and “CPU always allocated”. Instance-based billing requires at least 512MiB of memory. The inventory that “did nothing” at the start was exactly a background NATS consumer in a request-billed service: with no HTTP requests arriving, its CPU was throttled.

Settings for the shop's four workloads, with reasons:

WorkloadTypeBillingMin / maxConcurrencyReason
api-gatewayServiceRequest-based1 / 3080The public entry point; one warm instance avoids cold starts; it only forwards, so one instance takes many requests
orderServiceRequest-based1 / 2040The maximum is limited by the database connection budget; concurrency from load tests, more conservative than the default
paymentServiceRequest-based1 / 1040Calls an external payment provider with longer latency; the cap protects the provider's rate limits
inventoryWorker pool(whole lifetime)Fixed at 2—Pulls NATS messages in the background with no requests; two instances share the load and back each other up

Step 6: Deploy the first service, step by step

First the whole flow, then each step:

Schematic 1 Repository artifacts repositories create shop 2 Build, push docker buildx --platform linux/amd64 3 Identity order-run only the roles it needs 4 Deploy gcloud run deploy order → new revision 5 Verify describe get the URL revisions list Tag images with the commit hash, not latest; create the service account first and pass --service-account.

Figure: schematic flow. ① Create an Artifact Registry repository; ② build the image locally or in CI and push it; ③ create a dedicated service account for the service with least privilege; ④ gcloud run deploy creates a new revision; ⑤ get the service URL and verify.

① Create the repository. One Docker-format repository per project is enough; all four services' images go into it:

gcloud artifacts repositories create shop \
  --repository-format=docker --location=asia-east1 \
  --description="shop service images"

② Build and push the image. Reuse the multi-stage Dockerfile from “Deploying One Go Service with Docker and Kubernetes”, and remember to target linux/amd64. Tag with the git commit hash, not latest: a revision records the image, and tags can be overwritten while hashes cannot.

gcloud auth configure-docker asia-east1-docker.pkg.dev
IMAGE=asia-east1-docker.pkg.dev/shop-prod/shop/order:$(git rev-parse --short=12 HEAD)
docker buildx build --platform linux/amd64 --build-arg SERVICE=order \
  -f deploy/docker/Dockerfile -t "$IMAGE" --push .

If you would rather not build locally, gcloud run deploy --source . uploads the source to Cloud Build: it builds with the Dockerfile if there is one, otherwise with Google Cloud's buildpacks. That suits prototypes and personal projects; in production, let CI build and push a fixed image so you can always tell which image was deployed.

③ Create the service account. If you do not specify one, Cloud Run uses the project's default Compute Engine service account, which often carries broad permissions. Give each service a dedicated account with only what it needs:

gcloud iam service-accounts create order-run --display-name="order (Cloud Run)"
# order connects to Cloud SQL
gcloud projects add-iam-policy-binding shop-prod \
  --member="serviceAccount:order-run@shop-prod.iam.gserviceaccount.com" \
  --role="roles/cloudsql.client"

Permission to read secrets is granted in Step 8, and only for its own secrets.

④ Deploy. One command turns the image and settings into a new revision:

gcloud run deploy order \
  --image="$IMAGE" \
  --region=asia-east1 \
  --service-account=order-run@shop-prod.iam.gserviceaccount.com \
  --no-allow-unauthenticated \
  --ingress=internal \
  --cpu=1 --memory=512Mi \
  --concurrency=40 --min-instances=1 --max-instances=20 \
  --timeout=30s \
  --startup-probe=httpGet.path=/health,periodSeconds=2,failureThreshold=15 \
  --set-env-vars=DB_INSTANCE=shop-prod:asia-east1:shop-pg

The reason for each flag: --no-allow-unauthenticated means callers must present an ID token and hold roles/run.invoker; --ingress=internal accepts only requests from the VPC (Step 9); resources, concurrency and bounds are from Step 5. During deployment the platform starts one instance and only counts the deployment as successful once it passes the startup probe, so a broken image never becomes a serving revision.

⑤ Verify.

gcloud run services describe order --region=asia-east1 --format='value(status.url)'
gcloud run revisions list --service=order --region=asia-east1

Because order is internal, calling it directly from a laptop is blocked; Step 9 covers how api-gateway calls it.

If you prefer the web console, the same settings live in the create-service form:

Schematic Create service 1 Container image URL asia-east1-docker.pkg.dev/shop-prod/shop/order:3f2a9c1d7e4b Select 2 Service name order Region asia-east1 (Taiwan) ▾ 3 Authentication ◉ Require authentication ○ Allow unauthenticated invocations 4 Billing ◉ Request-based ○ Instance-based Scaling: min 1 max 20 5 Ingress ◉ Internal ○ Internal + Cloud Load Balancing ○ All 6 Containers Variables & Secrets Security Port 8080 · CPU 1 · Memory 512MiB · Concurrency 40 · Timeout 30s Secret DB_PASSWORD ← order-db-password: version 3 Service account order-run@shop-prod.iam.gserviceaccount.com Create

Figure: schematic screen; the actual labels may differ between console versions. ① Pick the image from Artifact Registry; ② service name and region; ③ choose “Require authentication”; ④ billing and scaling: request-based billing, minimum and maximum instances; ⑤ set ingress to “Internal”; ⑥ in the container settings, fill in the port, resources, variables and secrets, and choose the service account on the security tab; finally press Create.

The declarative way: a service YAML. When the command's flags keep growing, write the service as YAML, keep it in git, and apply it with gcloud run services replace. The format follows Knative's Service, with most settings in annotations:

# deploy/cloudrun/order.yaml
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
  name: order
  labels:
    cloud.googleapis.com/location: asia-east1
  annotations:
    run.googleapis.com/ingress: internal
spec:
  template:
    metadata:
      annotations:
        autoscaling.knative.dev/minScale: '1'
        autoscaling.knative.dev/maxScale: '20'
        run.googleapis.com/startup-cpu-boost: 'true'
        run.googleapis.com/network-interfaces: '[{"network":"shop-vpc","subnetwork":"run-asia-east1"}]'
        run.googleapis.com/vpc-access-egress: all-traffic
    spec:
      serviceAccountName: order-run@shop-prod.iam.gserviceaccount.com
      containerConcurrency: 40
      timeoutSeconds: 30
      containers:
        - image: asia-east1-docker.pkg.dev/shop-prod/shop/order:3f2a9c1d7e4b
          ports:
            - name: http1
              containerPort: 8080
          env:
            - name: DB_INSTANCE
              value: shop-prod:asia-east1:shop-pg
            - name: DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: order-db-password
                  key: '3' # the Secret Manager version number
          resources:
            limits:
              cpu: '1'
              memory: 512Mi
          startupProbe:
            httpGet:
              path: /health
              port: 8080
            periodSeconds: 2
            failureThreshold: 15
gcloud run services replace deploy/cloudrun/order.yaml --region=asia-east1

Commands suit first steps and one-off changes; YAML suits production: every setting is reviewed in git, and you can see who changed what and when. Do not mix the two: a setting changed in the console is overwritten by the YAML on the next replace. This YAML also uses Direct VPC egress and secrets, which later steps explain; come back to it when you get there.

Step 7: Revisions and traffic splitting: canaries and rollback

“Blue-Green and Canary Releases: Doing Them Right and What to Watch For” explained why deploying and releasing should be separate. On Cloud Run this is built in: a revision is a deployment, and a traffic percentage is a release.

1 Deploy, no traffic 00041 · 100% 00042 canary · 0% --no-traffic --tag=canary 2 Verify on preview 00041 · 100% 00042 canary · 0% canary---order-… smoke tests, QA 3 Shift 10% 00041 · 90% 00042 canary · 10% --to-tags canary=10 4 Promote or revert 00041 · 0% 00042 canary · 100% --to-latest or 00041=100 Revisions are immutable: rollback only changes percentages, no rebuild; tag URLs ignore the percentages.

Figure: ① deploy the new revision with --no-traffic --tag canary; it gets 0% of traffic but has its own preview URL; ② verify through the preview URL; ③ send 10% of traffic to canary; ④ if metrics look good, move to 100%; if not, point traffic back to the previous revision with no rebuild.

The commands, step by step:

# ① deploy without traffic; the canary tag creates a preview URL starting with canary---
gcloud run deploy order --image="$IMAGE" --region=asia-east1 --no-traffic --tag=canary

# ② run smoke tests against the preview URL (order is private, so send an ID token; see Step 9)

# ③ 10% to the new revision; the rest stays proportionally on the existing revisions
gcloud run services update-traffic order --region=asia-east1 --to-tags=canary=10

# ④a metrics are fine: move everything over, and later deploys go back to "latest gets all traffic"
gcloud run services update-traffic order --region=asia-east1 --to-latest

# ④b something is wrong: send all traffic back to the previous revision
gcloud run services update-traffic order --region=asia-east1 --to-revisions=order-00041-mid=100

Behaviour worth knowing:

  • After --no-traffic, “the latest revision automatically gets all traffic” is switched off. Traffic that pointed to “latest” is pinned to the revision that was latest before the deployment. Use --to-latest to restore it.
  • Tag URLs ignore traffic percentages. While canary has 0%, its preview URL still works, which suits QA or smoke tests; move the tag to another revision or delete it and the URL follows.
  • Bounds exist at both service and revision level. --max-instances and --min-instances apply to each revision separately, so while old and new revisions coexist the total can double; the service-level --max and --min apply to the whole service, are divided among revisions receiving traffic, and can be changed without creating a revision. Use the coexisting total of the former when you compute the database connection budget.
  • Old and new versions handle requests at the same time. Database schema changes must be backward compatible, as Step 10 of “Blue-Green and Canary Releases” explained; that applies here too.

Where it fits: every service that directly affects users deserves a canary, especially order and payment. Where it is unnecessary: internal tools and documentation sites can simply be deployed. Cloud Run's own traffic splitting looks only at percentages and cannot route by user or header; rules like “internal staff first” belong in api-gateway or feature flags.

Step 8: Secrets and the database

Secrets: Secret Manager. Create the secret, add its value, then let only order-run read its own secret:

printf '%s' "$ORDER_DB_PASSWORD" | gcloud secrets create order-db-password \
  --replication-policy=user-managed --locations=asia-east1 --data-file=-
gcloud secrets add-iam-policy-binding order-db-password \
  --member="serviceAccount:order-run@shop-prod.iam.gserviceaccount.com" \
  --role="roles/secretmanager.secretAccessor"

The value is read from standard input, so it never appears in the shell history; replication is restricted to asia-east1 because the requirement at the start was to keep data in the Taiwan region (with automatic, Google decides where it is stored). Next, decide how the code receives it. Cloud Run offers two ways:

Environment variable --set-secrets=DB_PASSWORD=order-db-password:3 Secret Manager versions 1, 2, 3… read once at start order instance DB_PASSWORD=… (fixed) no value, no start pin a version Mounted file --set-secrets=/secrets/payment/provider-key=payment-provider-key:latest Secret Manager versions 1, 2, 3… fetched per read payment instance /secrets/payment/provider-key latest: no redeploy fetch fails, read fails

Figure: as an environment variable, the value is read once when the instance starts and never changes; if it cannot be read, the instance fails to start. Mounted as a file, each read fetches the value from Secret Manager, and with latest you get new versions without redeploying.

# environment variable: pinned version number
gcloud run deploy order --image="$IMAGE" --region=asia-east1 \
  --set-secrets=DB_PASSWORD=order-db-password:3
# file: mounted at /secrets/payment/provider-key, following latest
gcloud run deploy payment --image="$PAYMENT_IMAGE" --region=asia-east1 \
  --set-secrets=/secrets/payment/provider-key=payment-provider-key:latest
MethodWhen the value is readFitsWatch out for
Environment variableWhen the instance startsSettings read once at startup, such as the database passwordPin a version; to rotate, deploy a new revision, so changing the version is a release
Mounted fileOn every readKeys that rotate and that the code can re-read, such as the payment keyThe code must actually re-read the file; if Secret Manager is unreachable, the read fails

The documentation recommends pinned versions for environment variables: with latest, different instances of the same revision may see different values, and there is no record of when the value changed.

The database: three ways to reach Cloud SQL.

Cloud Run instance A /cloudsql/… socket B Go connector C plain TCP Cloud SQL (shop-pg) Public IP Private IP (the shop's choice) Built-in Cloud SQL Auth Proxy Into the VPC via Direct VPC egress connector encryption + IAM (WithPrivateIP) ordinary PostgreSQL, set sslmode yourself The shop picks B: private IP only, encrypted connections, access decided by roles/cloudsql.client.

Figure: A uses --add-cloudsql-instances to expose the connection as a Unix socket under /cloudsql/ in the container; it goes over Cloud SQL's public IP, but with encryption and an IAM check. B uses the Cloud SQL Go connector in the code and can use the private IP. C connects directly over TCP to Cloud SQL's private IP through Direct VPC egress.

MethodFitsWhyDoes not fit / watch out for
A. Unix socket (--add-cloudsql-instances)Getting started; the database has no private IP yetNo code changes; the DSN says host=/cloudsql/shop-prod:asia-east1:shop-pgPublic IP only; the database has a public IP, which organisation policies often forbid
B. Cloud SQL Go connectorYou want TLS and IAM authorisation over the private IPThe connector handles certificates and encryption; IAM decides who may connectCode changes and one more dependency; use WithLazyRefresh (below)
C. Private IP, directDirect VPC egress is in place and the database has only a private IPThe simplest: an ordinary PostgreSQL connectionConfigure sslmode for encryption yourself; access relies only on the database user and password

The shop picks B: the database has only a private IP, the connector encrypts the connection, and roles/cloudsql.client controls who can connect. The code:

package platform

import (
	"database/sql"
	"fmt"
	"strings"
	"time"

	"cloud.google.com/go/cloudsqlconn"
	"cloud.google.com/go/cloudsqlconn/postgres/pgxv5"
)

// OpenCloudSQL connects to PostgreSQL through the Cloud SQL Go connector.
// instance is the instance connection name, e.g. "shop-prod:asia-east1:shop-pg".
// Size maxOpen together with Cloud Run's maximum instances (see the connection budget).
func OpenCloudSQL(instance, user, password, dbname string, maxOpen int) (*sql.DB, func() error, error) {
	cleanup, err := pgxv5.RegisterDriver("cloudsql-postgres",
		cloudsqlconn.WithLazyRefresh(), // CPU is throttled outside requests, so refresh certificates on demand
		cloudsqlconn.WithDefaultDialOptions(cloudsqlconn.WithPrivateIP()),
	)
	if err != nil {
		return nil, nil, fmt.Errorf("register driver: %w", err)
	}
	// The connector encrypts the connection, hence sslmode=disable here.
	dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=disable",
		instance, quote(user), quote(password), quote(dbname))
	db, err := sql.Open("cloudsql-postgres", dsn)
	if err != nil {
		_ = cleanup()
		return nil, nil, err
	}
	db.SetMaxOpenConns(maxOpen)
	db.SetMaxIdleConns(maxOpen)
	db.SetConnMaxIdleTime(5 * time.Minute)
	return db, func() error {
		_ = db.Close()
		return cleanup()
	}, nil
}

// quote wraps a value using libpq rules, so passwords with spaces, quotes or
// backslashes are parsed correctly.
func quote(v string) string {
	v = strings.ReplaceAll(v, `\`, `\\`)
	return "'" + strings.ReplaceAll(v, "'", `\'`) + "'"
}

Two details that relate directly to Cloud Run:

  • WithLazyRefresh. By default the connector refreshes its connection certificates periodically in the background; with request-based billing, CPU is throttled outside requests and the background refresh may not run. This option switches to “refresh only when a connection finds the certificate expired”; the connector's own documentation uses Cloud Run as the example.
  • host is the instance connection name (project:region:instance), not an IP; the connector uses it to look up the private IP and build an encrypted connection. Values in the DSN are quoted following libpq rules, so special characters in the password do not break parsing.

The connection budget. The arithmetic from Step 9 of “Deploying on AWS: EKS and Elastic Scaling” still holds; “number of pods” simply becomes “maximum instances”:

order   at most 20 instances × 5 each = 100
payment at most 10 instances × 5 each =  50
reserved for migrations, admin tools and inventory = 30
total 180, which must stay below Cloud SQL's max_connections (set to 200)

On Cloud Run, --max-instances is not only a cost cap but also the database's fuse. While a new revision rolls out it coexists with the old one, and their instances together must fit the budget too, so leave headroom.

Database migrations: Cloud Run jobs. A service “waits for requests forever”; a job “runs to completion and exits”. Migrations, daily reconciliation and data fixes all suit jobs:

gcloud run jobs deploy order-migrate \
  --image=asia-east1-docker.pkg.dev/shop-prod/shop/order-migrate:3f2a9c1d7e4b \
  --region=asia-east1 \
  --service-account=order-run@shop-prod.iam.gserviceaccount.com \
  --set-secrets=DB_PASSWORD=order-db-password:3 \
  --network=shop-vpc --subnet=run-asia-east1 \
  --tasks=1 --max-retries=3 --task-timeout=10m
gcloud run jobs execute order-migrate --region=asia-east1 --wait

CI runs the job before deploying the new revision and stops if it fails, the same idea as the sync hook in Step 7 of “GitOps with Argo CD: Let the Cluster Follow git on Its Own”. A job may be retried, so the migration tool must be safe to run again (recording completed steps in a version table).

Step 9: Private services, calls between services and the public entry point

The first problem at the start was “order has a public URL”. Cloud Run handles this with two independent gates, and both need setting:

  • Ingress: where requests may come from. all means anywhere; internal accepts only requests from VPC networks in the same project (and Pub/Sub and Eventarc in the same project); internal-and-cloud-load-balancing also admits requests through a Google Cloud load balancer.
  • Authentication (IAM): who may call. With --no-allow-unauthenticated, a request must carry a Google-signed ID token, and that identity must hold roles/run.invoker on the service.
Users Load balancer + Cloud Armor Direct calls to run.app: blocked by ingress api-gateway ingress: internal + LB order ingress: internal, invoker payment ingress: internal, invoker Direct VPC egress, all-traffic with api-gateway's ID token VPC shop-vpc · subnet run-asia-east1 (Private Google Access on) Cloud SQL private IP NATS ×3 Compute Engine Cloud NAT fixed egress IP Payment provider allow list: Cloud NAT IP

Figure: external requests reach api-gateway only through the load balancer; api-gateway sends its requests into the VPC through Direct VPC egress and calls order and payment with its own ID token; order and payment accept only internal requests, and only from identities with the invoker role; when payment calls the external payment provider it goes through Cloud NAT, so the provider sees a fixed egress IP.

Calls between services. Three things:

  1. Give order and payment --ingress=internal and --no-allow-unauthenticated.
  2. Allow only api-gateway's service account to call them:
gcloud run services add-iam-policy-binding order --region=asia-east1 \
  --member="serviceAccount:api-gateway-run@shop-prod.iam.gserviceaccount.com" \
  --role="roles/run.invoker"
  1. api-gateway's requests must go through the VPC to count as “internal”. One approach listed in the documentation: configure Direct VPC egress on the caller, route all egress through the VPC (--vpc-egress=all-traffic), and turn on Private Google Access on that subnet:
gcloud compute networks subnets update run-asia-east1 \
  --region=asia-east1 --enable-private-ip-google-access
gcloud run deploy api-gateway --image="$GATEWAY_IMAGE" --region=asia-east1 \
  --network=shop-vpc --subnet=run-asia-east1 --vpc-egress=all-traffic

In the code, the idtoken package builds an HTTP client that adds the token automatically. The token's audience is order's URL:

package gateway

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"google.golang.org/api/idtoken"
)

// NewOrderClient returns the HTTP client used to call the order service.
// Every request carries Authorization: Bearer <ID token> automatically.
// The token's audience is the order URL; on Cloud Run the metadata server issues it
// for api-gateway's own service account and it is renewed before it expires.
func NewOrderClient(ctx context.Context, orderURL string) (*http.Client, error) {
	c, err := idtoken.NewClient(ctx, orderURL)
	if err != nil {
		return nil, fmt.Errorf("idtoken client for %s: %w", orderURL, err)
	}
	c.Timeout = 3 * time.Second // timeouts are covered in "Timeouts, Retries and Circuit Breakers"
	return c, nil
}

The principles for timeouts and retries are in “Timeouts, Retries and Circuit Breakers”. If api-gateway already uses the Authorization header to forward the user's JWT, put Google's ID token in X-Serverless-Authorization instead; Cloud Run then checks that header. If services talk gRPC, deploy with --use-http2.

The side effect of all-traffic: outbound traffic needs Cloud NAT. Once all egress goes through the VPC, payment's calls to the external payment provider also enter the VPC, and without Cloud NAT they cannot get out. That is a good thing, though: reserve a static external IP on Cloud NAT and the provider's IP allow list finally has a fixed value to hold.

gcloud compute routers create shop-router --network=shop-vpc --region=asia-east1
gcloud compute addresses create shop-nat-ip --region=asia-east1
gcloud compute routers nats create shop-nat --router=shop-router --region=asia-east1 \
  --nat-all-subnet-ip-ranges --nat-external-ip-pool=shop-nat-ip

Direct VPC egress versus connectors. There are two ways to connect Cloud Run to a VPC: Direct VPC egress, or the older Serverless VPC Access connector. The documentation now recommends Direct VPC egress: no charges for the connector's VMs, lower latency and higher throughput. The price is that scaling out has to create network interfaces, so scaling up from zero is somewhat slower, and it uses more IPs: in steady state each instance uses about 2 IPs, IPs are kept for a while after scaling in, the subnet must be at least /26, and its size should be planned as “maximum instances × 2, plus room for old and new revisions coexisting during a rollout”.

The public entry point: a global external Application Load Balancer. api-gateway needs its own domain, Cloud Armor in front to block attacks, and, on the same domain, / served from the front end's static files and /api/ from Cloud Run; the load balancer does all of this. Cloud Run also has a “domain mapping” feature, but it is still in preview, available only in some regions, and not recommended for production.

Schematic 1 Static IP addresses create shop-ip --global 2 Serverless NEG type: serverless Cloud Run service: api-gateway 3 Backend service EXTERNAL_MANAGED optional Cloud Armor policy 4 URL map / → front end (Cloud Storage) /api/ → api-gateway 5 Cert + HTTPS proxy Google-managed certificate shop.example.com 6 Forwarding rule shop-ip:443 → HTTPS proxy DNS A record to this IP Request path: user → IP:443 → forwarding rule → HTTPS proxy → URL map → backend → NEG → Cloud Run

Figure: schematic flow. ① Reserve a global static IP; ② create a serverless network endpoint group (serverless NEG) pointing at api-gateway; ③ create a backend service and add the NEG, optionally attaching a Cloud Armor policy; ④ the URL map decides which paths go to which backend; ⑤ a Google-managed certificate and an HTTPS target proxy; ⑥ a forwarding rule connects port 443 on the IP to the proxy; finally add a DNS A record pointing at the IP.

gcloud compute addresses create shop-ip --global                                   # ①
gcloud compute network-endpoint-groups create api-gateway-neg --region=asia-east1 \
  --network-endpoint-type=serverless --cloud-run-service=api-gateway               # ②
gcloud compute backend-services create api-gateway-be --global \
  --load-balancing-scheme=EXTERNAL_MANAGED                                          # ③
gcloud compute backend-services add-backend api-gateway-be --global \
  --network-endpoint-group=api-gateway-neg --network-endpoint-group-region=asia-east1
gcloud compute url-maps create shop-lb --default-service=api-gateway-be             # ④
gcloud compute ssl-certificates create shop-cert --global --domains=shop.example.com # ⑤
gcloud compute target-https-proxies create shop-https --url-map=shop-lb \
  --ssl-certificates=shop-cert
gcloud compute forwarding-rules create shop-https-rule --global \
  --load-balancing-scheme=EXTERNAL_MANAGED --address=shop-ip \
  --target-https-proxy=shop-https --ports=443                                      # ⑥

Finally, change api-gateway's ingress to internal-and-cloud-load-balancing: requests to the run.app URL are then turned away, and all external traffic must pass through the load balancer (and the Cloud Armor policy above). api-gateway handles user requests, so it allows unauthenticated calls (--allow-unauthenticated) and checks the user's JWT itself, as in “Building an API Gateway in Go: Routing, Authentication and Rate Limiting”. The certificate is only issued once DNS points at the load balancer, which takes a while.

Where the event consumer goes. inventory consumes NATS order.placed events and receives no HTTP requests. There are three options:

ApproachFitsWhyDoes not fit / watch out for
Cloud Run worker poolPull-based consumers (NATS, Kafka)No URL, no requests needed, a fixed instance count, CPU always availableNo built-in autoscaling on backlog; you choose and adjust the count yourself
Service + instance-based billing + minimum instancesOne program that has HTTP endpoints and also consumes in the backgroundOne service does it allScaling follows requests and CPU, not queue backlog
Switch to Pub/Sub push into a Cloud Run serviceYou are willing to replace the event system with GCP's Pub/SubEach message becomes an HTTP request, so scaling and billing return to the request modelThe whole event system changes; idempotency, redelivery and dead letters must be redesigned for Pub/Sub's semantics

The shop picks a worker pool: no code changes, and the NATS semantics (“Message Queues and Event-Driven Design”) stay the same.

gcloud run worker-pools deploy inventory --image="$INVENTORY_IMAGE" --region=asia-east1 \
  --service-account=inventory-run@shop-prod.iam.gserviceaccount.com \
  --instances=2 --network=shop-vpc --subnet=run-asia-east1

A worker pool also receives SIGTERM on a new revision or during maintenance, and the consumer shuts down by the same rules as in “Configuration and Graceful Shutdown in Go”: stop pulling new messages, finish and acknowledge the one in hand.

Step 10: CI/CD: GitHub Actions deploying through Workload Identity Federation

The same principle as in the AWS article: GitHub stores no long-lived keys. GCP's mechanism is called Workload Identity Federation: each GitHub Actions run gets a short-lived OIDC token, GCP checks which repository it came from, and exchanges it for short-lived credentials of a service account.

GitHub Actions release.yaml Security Token Service pool github / provider shop shop-deployer deployer service account ① OIDC token ③ impersonate (workloadIdentityUser) permissions: id-token: write ② check issuer and condition repository_owner == 'example' IAM binding allows only the example/shop repo Artifact Registry push images Cloud Run revisions run as order-run ④ push ④ deploy GitHub stores no long-lived keys; the deployer cannot read secrets or reach the database; runtimes cannot deploy.

Figure: ① the workflow asks GitHub for an OIDC token; ② it hands the token to GCP's Security Token Service, where the pool's provider checks the issuer and the attribute condition (only the example organisation); ③ the external identity impersonates the deployer service account shop-deployer, whose IAM binding allows only the example/shop repository; ④ with short-lived credentials it pushes images to Artifact Registry and deploys to Cloud Run; revisions run as runtime service accounts such as order-run.

One-time setup:

gcloud iam workload-identity-pools create github --location=global \
  --display-name="GitHub Actions"
gcloud iam workload-identity-pools providers create-oidc shop --location=global \
  --workload-identity-pool=github \
  --issuer-uri="https://token.actions.githubusercontent.com" \
  --attribute-mapping="google.subject=assertion.sub,attribute.repository=assertion.repository,attribute.repository_owner=assertion.repository_owner" \
  --attribute-condition="assertion.repository_owner == 'example'"

gcloud iam service-accounts create shop-deployer --display-name="CI deployer"
gcloud iam service-accounts add-iam-policy-binding \
  shop-deployer@shop-prod.iam.gserviceaccount.com \
  --role="roles/iam.workloadIdentityUser" \
  --member="principalSet://iam.googleapis.com/projects/123456789012/locations/global/workloadIdentityPools/github/attribute.repository/example/shop"

Always write --attribute-condition: without one, a token from any GitHub repository can enter the pool. Attributes must first be mapped in --attribute-mapping before conditions and IAM bindings can use them.

Keep the deployer and the runtime apart. This is the easiest thing to mix up on GCP:

Service accountUsed byPermissionsWhy
shop-deployerGitHub Actionsroles/run.developer; roles/artifactregistry.writer on the shop repository; roles/iam.serviceAccountUser on each runtime accountCan push images and deploy revisions, but cannot read secrets or reach the database
api-gateway-runapi-gateway at runtimeroles/run.invoker on order and paymentCan only call those two services
order-runorder at runtimeroles/cloudsql.client; roles/secretmanager.secretAccessor on its own secretsTouches only its own database and secrets
payment-runpayment at runtimeroles/cloudsql.client; roles/secretmanager.secretAccessor on the payment keyLikewise

roles/iam.serviceAccountUser is the key: a deployment names the service account the revision runs as, and the deployer must hold this role on that account. Otherwise anyone who can deploy could run code as any identity and gain all of its permissions. So grant it only on the *-run accounts, never at project level.

The workflow:

# .github/workflows/release.yaml
name: release
on:
  push:
    branches: [main]
permissions:
  contents: read
  id-token: write # ask GitHub for an OIDC token
concurrency:
  group: release
  cancel-in-progress: false
env:
  REGION: asia-east1
  REG: asia-east1-docker.pkg.dev/shop-prod/shop
jobs:
  deploy:
    runs-on: ubuntu-latest
    strategy:
      max-parallel: 1
      matrix:
        service: [order, payment, api-gateway]
    env:
      SERVICE: ${{ matrix.service }}
    steps:
      - uses: actions/checkout@v6
      - uses: google-github-actions/auth@v3
        with:
          project_id: shop-prod
          workload_identity_provider: projects/123456789012/locations/global/workloadIdentityPools/github/providers/shop
          service_account: shop-deployer@shop-prod.iam.gserviceaccount.com
      - uses: google-github-actions/setup-gcloud@v3
      - name: Build and push
        run: |
          gcloud auth configure-docker "${REGION}-docker.pkg.dev" --quiet
          IMAGE="${REG}/${SERVICE}:${GITHUB_SHA::12}"
          docker buildx build --platform linux/amd64 --build-arg SERVICE="$SERVICE" \
            -f deploy/docker/Dockerfile -t "$IMAGE" --push .
          echo "IMAGE=$IMAGE" >> "$GITHUB_ENV"
      - uses: google-github-actions/deploy-cloudrun@v3
        with:
          service: ${{ matrix.service }}
          region: ${{ env.REGION }}
          image: ${{ env.IMAGE }}
          no_traffic: true
          tag: canary
      - name: Send 10% to canary
        run: gcloud run services update-traffic "$SERVICE" --region="$REGION" --to-tags=canary=10
      # After watching the metrics, a person runs --to-latest or points traffic back (Step 7)

The reasons behind a few choices:

  • id-token: write lets the workflow request an OIDC token from GitHub; without it, auth fails.
  • deploy-cloudrun's no_traffic and tag map to gcloud run deploy --no-traffic --tag, so the new revision starts with no traffic; then 10% is shifted. Moving everything over is a human decision; as in “Blue-Green and Canary Releases”, it can later be replaced by an automatic, metric-based check.
  • max-parallel: 1 deploys the three services in turn; concurrency keeps two pushes from deploying at the same time.
  • The rest of each service's settings (memory, secrets, VPC) are not in CI. gcloud run deploy changes only what is specified and carries the other settings over from the previous revision. For a fully declarative setup, pass the YAML from Step 6 through deploy-cloudrun's metadata input.
  • Pin third-party actions to a commit SHA in production; the reasons are in “Microservice Security: Authentication, Authorisation, Secrets and Supply Chain”.

Step 11: Observability, cost, and when to move to GKE

Observability. Cloud Run gives you three things without installing an agent: standard output in Cloud Logging (each JSON line becomes a structured entry), built-in metrics (request count, latency distribution, instance count, CPU and memory utilisation), and a request log for every request. The metrics to watch, and why:

MetricWhy watch it
p95/p99 request latency, split by revisionCompare old and new versions during a canary
5xx ratio, split by revisionLikewise; the main basis for rolling back
Instance count versus maximum instancesSitting at the cap means requests are queuing; adjust the cap or concurrency
Container startup latencyWhen cold starts slow down, check image size and what runs at startup
Cloud SQL connection countCheck that the connection budget still holds

Tracing keeps the OpenTelemetry setup from “Observability in Go: Logs, Metrics and Tracing”; point the exporter at Google Cloud's tracing service and the instrumentation stays the same. Note that with request-based billing, CPU is throttled outside requests, so batched traces and metrics may sit in a buffer; that is why the code in Step 4 flushes them on shutdown.

Cost. Only the structure here; prices change, so check the official pricing page:

  • With request-based billing, cost follows “time spent handling requests”; idle services cost almost nothing, which is Cloud Run's biggest advantage.
  • Minimum instances and instance-based billing make “time without requests” billable too. Use them only on services that really need them.
  • The connection budget and maximum instances are also cost guard rails: a bug that loops or attack traffic cannot inflate the bill without limit.
  • Cloud NAT, the load balancer and Cloud SQL high availability are fixed costs that run even at zero traffic.
  • Set a budget and alerts on the project; label resources (service, env) so the bill can be broken down by service.

When to move from Cloud Run to GKE. If two or three of these signals appear, GKE Autopilot is worth evaluating:

  • Dozens of services, and a wish for unified GitOps (Argo CD), Operators and a service mesh.
  • A need for DaemonSet-style agents, privileged containers or custom node settings.
  • Many workloads that must autoscale on queue backlog (tools like KEDA), where worker pools' fixed counts are not enough.
  • Very steady traffic that is busy around the clock, where paying by node or pod resources plus committed use discounts is cheaper.
  • Stateful components (NATS, caches) that you want to manage on the same platform as the services.

Conversely, if there are few services, traffic is spiky and nobody on the team wants to run a cluster, staying on Cloud Run is the right call. Container images, graceful shutdown and service accounts all carry straight over to GKE; the main cost of moving is rewriting Cloud Run settings as Kubernetes resources.

Common pitfalls

  • Building on an Apple-silicon laptop without --platform linux/amd64. The image is arm64 and the container fails to start on deploy; specify the platform explicitly in CI and locally.
  • Listening on a fixed 8080 or only on 127.0.0.1. Read PORT and leave the host empty.
  • Using paths ending in z, such as /healthz or /readyz. Some are reserved by the platform, and the documentation recommends avoiding them all.
  • Keeping Kubernetes' 30-second shutdown budget. Cloud Run gives only 10 seconds; cleanup must finish within that.
  • Background goroutines in a request-billed service. CPU is throttled outside requests, so message consumption, scheduled work and background refreshes all stall; use a worker pool or instance-based billing, or turn the work into requests.
  • Storing files on the container's filesystem. It lives in memory, consumes the instance's memory and disappears when the instance goes; put uploads in Cloud Storage.
  • Running as the default Compute Engine service account. Give each service a dedicated account with only the roles it needs.
  • Granting the deployer roles/iam.serviceAccountUser at project level. The deployer could then run code as any identity in the project; grant it only on the runtime accounts.
  • Setting only --no-allow-unauthenticated while ingress stays all. IAM blocks callers without permission, but the service is still exposed to the internet; internal services need both gates closed.
  • Leaving api-gateway's ingress at all. Anyone can hit the run.app URL directly and bypass the load balancer and Cloud Armor; switch to internal-and-cloud-load-balancing.
  • Leaving maximum instances at the default 100. Multiplied by the pool size it exceeds the database's limit; set it from the connection budget, counting old and new revisions coexisting during a rollout.
  • --vpc-egress=all-traffic without Cloud NAT. Every outbound request fails; Cloud NAT also gives you a fixed egress IP.
  • A Direct VPC egress subnet that is too small. Each instance uses about 2 IPs, and IPs are held for a while after scaling in; scale-out stalls halfway when IPs run out.
  • Secrets in environment variables with latest. Different instances may see different values; pin versions for environment variables and mount files when you want automatic rotation.
  • Assuming the next deploy gets all traffic after a --no-traffic deploy. “Latest gets all traffic” has been switched off; restore it with --to-latest.
  • Using domain mapping in production. It is still a preview feature; use a global external Application Load Balancer in production.
  • A Workload Identity Federation provider with no attribute condition. Any GitHub repository could enter the pool; restrict at least the organisation, then the repository in the IAM binding.

Key takeaways

  • Choose Cloud Run for stateless HTTP services with spiky traffic and small teams; run stateful servers on Compute Engine or GKE; choose GKE Autopilot for systems that are already a full Kubernetes setup; use Cloud Run functions for event glue and Cloud Storage with Cloud CDN for static sites.
  • The project is GCP's basic unit, and production is kept apart from development; the VPC is global while subnets are regional; code runs as a service account, one per service.
  • In Cloud Run, a service is a name plus traffic settings, a revision is an immutable “image plus settings” snapshot, and instances come and go with requests; rolling back means pointing traffic at an old revision.
  • The container contract: listen on PORT and 0.0.0.0, run on linux/amd64, stay stateless, exit within 10 seconds of SIGTERM; avoid paths ending in z.
  • Concurrency is a ceiling, not a target; minimum instances trade cold starts for idle cost; maximum instances are a fuse for both cost and database connections.
  • With request-based billing there is no CPU outside requests, so background work stalls; put background consumers in a worker pool or use instance-based billing.
  • Deploy with --no-traffic --tag to ship without releasing, verify through the preview URL, then shift gradually with update-traffic.
  • Keep secrets in Secret Manager and pin versions for environment variables; reach Cloud SQL over its private IP with the Go connector and remember WithLazyRefresh; maximum instances × pool size must fit the budget; run migrations as Cloud Run jobs.
  • Internal services set both --ingress=internal and the IAM invoker role; callers use Direct VPC egress and send ID tokens; the outside world comes in only through the load balancer.
  • CI exchanges tokens through Workload Identity Federation, and the provider must have an attribute condition; keep the deployer and runtime accounts apart and grant serviceAccountUser only on the runtime accounts.

References

Next

By now the same shop can run on AWS EKS, on ECS Fargate and on GCP Cloud Run. All of these articles assumed it was “already split into four services”, though. The next article, “From Monolith to Microservices: Evolving the Architecture at 100K, 1M and 10M Scale”, steps back to ask what the same shop should look like at different scales, and when a monolith with read replicas and a cache is enough — and at that stage, one Cloud Run service plus one Cloud SQL instance may well be the most economical way to deploy it.