irfan@backend:~/portfolio
Email me
← cd ../blog

Google Cloud / Cloud Run / Deployment / Beginner

Cloud Run from A to Z: one API from first deploy to CI/CD

Deploy one small API to Google Cloud Run: setup, env vars, secrets, rollback, sizing, cost, logs, and GitHub Actions deploys with no stored key.

On this page
  1. What Cloud Run is
  2. When to pick Cloud Run
  3. Setup
  4. Account and billing
  5. Install gcloud and create a project
  6. Region, APIs and the builder role
  7. Your first deploy
  8. Keep files out of the upload
  9. One command
  10. What happens after you press Enter
  11. Test it
  12. Public or private
  13. Make a change and deploy again
  14. Environment variables
  15. Secrets
  16. Create the secret
  17. Give the app its own identity
  18. Grant access first, then deploy
  19. Pin the version, not latest
  20. Revisions and rollback
  21. The catch: your traffic is now pinned
  22. Splits and tags for a safer release
  23. Cold starts and sizing
  24. The sizing knobs
  25. Use --min and --max, not --min-instances
  26. How you pay
  27. When instance-based billing makes sense
  28. Cost tips
  29. Logs and common errors
  30. Write logs as JSON
  31. Four errors you will hit
  32. Deploy from GitHub Actions
  33. Step 1: the accounts and roles
  34. Step 2: the pool, the provider and the condition
  35. Step 3: the workflow
  36. Recap

You have a container that runs on your laptop, and you want a public HTTPS URL for it. Google Cloud Run gives you one, with no server to rent or patch. This post takes one small app, hello-api, from its first deploy to a deploy on every GitHub push.

After this post you can:

  • deploy hello-api to Cloud Run with one command and open its URL
  • add settings and a secret safely, roll back a bad deploy in seconds, and size your instances
  • predict your bill, fix common errors from the logs, and deploy from GitHub with no stored key

The app is hello-api from Docker from Zero: a tiny Express API with a /health route and a Dockerfile. Build it there first. That post also explains images and containers.

What Cloud Run is#

Here is the end result. You run one command and get this back:

Service [hello-api] revision [hello-api-00001-abc] has been deployed and is serving 100 percent of traffic.
Service URL: https://hello-api-123456789012.us-central1.run.app

Open that URL with /health at the end, and you see {"status":"ok"}. You did not create a server or buy an HTTPS certificate. Google runs the container and starts more copies when traffic grows. When nobody calls it, it scales to zero copies.

Words you need:

  • Project: your workspace in Google Cloud. Every service, bill and permission lives inside one project.
  • Service: your deployed app on Cloud Run. It has a name (hello-api) and a URL.
  • Revision: a fixed snapshot of your service: one image plus its settings. Every deploy makes a new revision. Old ones stay, so you can go back.
  • Instance: one running copy of your container. Cloud Run runs zero, one or many at the same time.
  • Region: the place your service runs, like us-central1 (Iowa) or asia-southeast1 (Singapore). Pick one close to your users.

One service has many revisions over time. Traffic goes to one of them (or is split between a few). That revision runs as many instances as the traffic needs:

When to pick Cloud Run#

"Serverless" does not mean there are no servers. It means you don't manage them. You say how much memory and CPU each copy gets, and Google finds the machines. The trade-off is less control. For example, you can't log in to the machine with SSH (a remote terminal on a server).

ECS Fargate is AWS's service that runs containers without servers you manage. Here is how the three compare:

VM (Compute Engine)Cloud RunECS Fargate (AWS)
You managethe whole machine, OS patches includedyour container and its settingstask definitions, services, a load balancer
HTTPS URLyou set it upbuilt inthrough a load balancer you create
No trafficstill running, still billedscales to zero instancestasks keep running until you change the count
Good forfull control, special softwareweb APIs, sites, webhooksteams already on AWS

My rule: an HTTP app in a container, on Google Cloud, with traffic that goes up and down? Start with Cloud Run. Move to a VM only when you need something Cloud Run can't give you.

quick-check

You deploy hello-api three times. How many revisions does the service have?

quick-check

Nobody calls your Cloud Run service for a whole night. How many instances run?

Setup#

You do these steps once. After that, every deploy is one command.

  1. Create a Google Cloud account (new accounts get a free trial credit).
  2. Install the gcloud CLI and sign in with gcloud init.
  3. Create a project and set it as the default.
  4. Link a billing account to the project.
  5. Set a default region for Cloud Run.
  6. Enable the Cloud Run, Cloud Build and Artifact Registry APIs.
  7. Give the build account the Cloud Run Builder role (a set of permissions).

Account and billing#

Sign up at cloud.google.com. New customers get a $300 credit to spend over 90 days. You need a credit card to sign up, but Google does not bill you during the trial. Charges start only if you upgrade to a paid account. Cloud Run also has a monthly free tier on top of that (How you pay chapter).

Install gcloud and create a project#

gcloud is Google Cloud's command-line tool. Install it from the install guide (macOS, Windows and Linux). Don't want to install anything? Use Cloud Shell, a terminal in your browser with gcloud ready. Open it from the terminal icon at the top of the Google Cloud console.

gcloud --version
gcloud init

gcloud init opens your browser so you can sign in, then asks a few setup questions. Next, create a project and make it the default:

gcloud projects create my-hello-api-7
gcloud config set project my-hello-api-7

my-hello-api-7 is the project ID. It must be unique across all of Google Cloud, so add a few letters or numbers of your own. You can rename a project later. You can never change its ID, and the ID shows up in commands and URLs.

Now link billing. In the console, open Billing, then Link a billing account, and pick your account. Without billing, Cloud Run refuses to deploy, even on the free trial.

Region, APIs and the builder role#

gcloud config set run/region us-central1

gcloud services enable run.googleapis.com \
  cloudbuild.googleapis.com \
  artifactregistry.googleapis.com

The first line saves a default region. I still write --region in every command, so each one is clear on its own.

Google Cloud APIs are off by default in a new project. You turn on only what you use:

  • run.googleapis.com: Cloud Run itself.
  • cloudbuild.googleapis.com: Cloud Build, which builds your image in the cloud.
  • artifactregistry.googleapis.com: Artifact Registry, Google's registry where the image is stored.

The last step is a permission.

Words you need:

  • IAM (Identity and Access Management): how Google Cloud decides who may do what.
  • Role: a named set of permissions you grant to an identity.
  • Service account: an identity for a program, not a person.

Cloud Build builds your code as a service account. By default it uses the Compute Engine default service account, named PROJECT_NUMBER-compute@developer.gserviceaccount.com. The deploy-from-source docs say to give it the Cloud Run Builder role:

# your project number (digits), not the project ID
gcloud projects describe my-hello-api-7 --format="value(projectNumber)"

gcloud projects add-iam-policy-binding my-hello-api-7 \
  --member="serviceAccount:123456789012-compute@developer.gserviceaccount.com" \
  --role="roles/run.builder"

Replace 123456789012 with the number the first command printed. The grant takes a couple of minutes to work, so give it a moment before your first deploy.

For now this same account also runs your app, because you don't name another one yet. It may hold the Editor role (broad rights on the whole project). Google can grant that to it automatically. That is more than your app needs, so the Secrets chapter moves the app to its own account.

quick-check

You skip gcloud services enable and run a deploy. What happens?

Your first deploy#

Go to your hello-api folder (the one with server.js, package.json and the Dockerfile). First, one small file.

Keep files out of the upload#

gcloud uploads your folder to Google Cloud before it builds. It skips the files listed in .gcloudignore. No .gcloudignore but a .gitignore? The gcloud reference says it uses your .gitignore instead. Make it explicit. Create .gcloudignore:

.gcloudignore
.git
.gitignore
node_modules
.env
.env.*

Your .env file with passwords should never leave your laptop. node_modules is not needed, because the RUN npm ci line in your Dockerfile installs the packages during the build.

One command#

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

What each part means:

  • gcloud run deploy hello-api: deploy a service called hello-api. If it exists, this makes a new revision. If not, it creates the service.
  • --source .: build the image from the code in this folder.
  • --region us-central1: where the service runs.
  • --allow-unauthenticated: anyone on the internet can call the URL.

The first time, gcloud asks to create an Artifact Registry repository called cloud-run-source-deploy. Answer y. It stores your images there.

What happens after you press Enter#

source-deploy
  1. gcloud uploads your folder from your laptop, minus the files in .gcloudignore.
  2. Cloud Build finds your Dockerfile and builds the image.
  3. The image is pushed to Artifact Registry (cloud-run-source-deploy).
  4. Cloud Run creates a new revision from that image and its settings.
  5. One instance starts and must pass its startup check. Cloud Run tells your app which port to use in the PORT env var (8080 by default) and tries to connect there.
  6. The check passes, so the revision gets 100% of the traffic.
  7. gcloud prints the service URL.
step 1 / 7
If the startup check fails, the new revision gets no traffic and the deploy fails.

No Dockerfile in the folder? Then Cloud Build uses buildpacks, Google's tool that turns code into an image for you. It sees package.json and picks a Node base image. Then it installs your packages and runs your start script. The --source docs say a Dockerfile, if present, wins. Otherwise buildpacks build it. Buildpacks are great for getting started. Your own Dockerfile gives you full control (the Node version, USER node, the .dockerignore).

Test it#

curl https://hello-api-123456789012.us-central1.run.app/health

Use the URL gcloud printed. You get {"status":"ok"}. Lost the URL? Run gcloud run services describe hello-api --region us-central1 --format "value(status.url)".

Why does it work without changing the port? In Docker from Zero the app listens on Number(process.env.PORT) || 3000, on 0.0.0.0. Cloud Run sets PORT=8080 inside the container. That wins over ENV PORT=3000 in your Dockerfile. So the app listens where Cloud Run sends traffic. An app that always listens on 3000 fails the startup check with "Container failed to start" (Logs and common errors chapter).

Public or private#

--allow-unauthenticated gives the Cloud Run Invoker role (permission to call the service) to allUsers, which means everyone.

Leave the flag out on a new service, and gcloud asks you if it should allow public access. Say no (or pass --no-allow-unauthenticated), and the service is private. A private service answers 403 Forbidden unless the caller sends a Google identity token. That is a signed, short-lived proof of who is calling. Private is the right choice for internal APIs. For a learning app, public is fine.

On an existing service, leaving the flag out changes nothing. A public service stays public.

Company account blocks this? Some companies set an organization policy (a rule for every project in the company) that forbids granting roles to allUsers. Then use --no-invoker-iam-check instead. It turns off the permission check, and Google's public access guide calls it the recommended way.

Make a change and deploy again#

Edit the /health response, then run the same gcloud run deploy command. Cloud Run builds a new image, creates revision 00002, and moves the traffic once it starts. Revision 00001 stays, and you can send traffic back to it in seconds (Revisions and rollback chapter).

Want api.example.com instead of the run.app URL? Cloud Run's own domain mappings are still in preview and not recommended for production. Google recommends a global external Application Load Balancer instead. That is Google's load balancer: a front door that sends HTTPS traffic to your services, with your own domain and certificate.

quick-check

Your folder has a Dockerfile. You run gcloud run deploy --source . What builds the image?

quick-check

Your app always listens on port 3000 and ignores PORT. What happens on deploy?

quick-check

You create a new service with --no-allow-unauthenticated and open the URL in your browser. What do you see?

Environment variables#

hello-api now runs. A real app needs settings that change per environment. Add one route to server.js, so you can see the settings from outside:

app.get('/', (req, res) => {
  res.json({
    greeting: process.env.GREETING || 'hello',
    appEnv: process.env.APP_ENV || 'unknown',
    dbPasswordSet: Boolean(process.env.DB_PASSWORD),
  });
});

dbPasswordSet only says whether the password exists. Never send a secret back in a response or write it to a log.

Deploy it with two env vars:

gcloud run deploy hello-api \
  --source . \
  --region us-central1 \
  --set-env-vars GREETING=hi,APP_ENV=prod

curl the URL and you get {"greeting":"hi","appEnv":"prod","dbPasswordSet":false}. Now you want one more variable, LOG_LEVEL=debug. Guess first: what does this do?

gcloud run services update hello-api \
  --region us-central1 \
  --set-env-vars LOG_LEVEL=debug
set-wipes-the-list
  1. You deploy with --set-env-vars GREETING=hi,APP_ENV=prod. The service has both.
  2. You run --set-env-vars LOG_LEVEL=debug. The new list replaces the whole old list.
  3. GREETING and APP_ENV are gone. Your greeting is back to hello.
  4. With --update-env-vars, only the keys you name change. The rest stay.
step 1 / 4
--set-env-vars replaces. --update-env-vars adds or changes.

It deletes GREETING and APP_ENV. The env var docs call --set-env-vars a destructive action: the list you give replaces the whole list. Your greeting is back to hello. To add or change only some keys, use --update-env-vars:

FlagWhat it does
--set-env-vars A=1,B=2replaces all env vars with exactly this list
--update-env-vars B=3adds or changes B, keeps the rest
--remove-env-vars Adeletes only A
--clear-env-varsdeletes all of them

Notice the second command used gcloud run services update, not deploy. update changes settings on the image you already have. So Cloud Run makes a new revision without a new build. Don't set PORT yourself, because Cloud Run sets it.

quick-check

The service has GREETING=hi and APP_ENV=prod. You run --update-env-vars GREETING=hey. What does it have now?

Secrets#

hello-api now needs a database password that nobody can read in the console. Anyone with view access to your service can read its env vars there. That is fine for APP_ENV. It is not fine for a password.

Words you need:

  • Secret Manager: Google's store for passwords and keys. Cloud Run reads the value from there when an instance starts.
  • Secret: a named entry in Secret Manager, like db-password.
  • Version: each value you save in a secret gets a number: 1, 2, 3. A new password is a new version.
  • Runtime service account: the identity your running app uses to call Google Cloud. Until now, the build account (the Compute Engine default service account) also ran your app.
  • Mount: make a secret show up as a file inside the container, instead of as an env var.

Create the secret#

gcloud services enable secretmanager.googleapis.com

gcloud secrets create db-password --replication-policy="automatic"

read -rs DB_PASSWORD
printf '%s' "$DB_PASSWORD" | gcloud secrets versions add db-password --data-file=-
unset DB_PASSWORD

read -rs reads the password without showing it, so it never lands in your shell history (as echo my-password would). --data-file=- tells gcloud to read the value from that pipe. This is version 1.

Give the app its own identity#

The service identity docs recommend a service account you create yourself. The default one may hold the Editor role, far more than your app needs. Create one just for hello-api:

gcloud iam service-accounts create hello-api-sa \
  --display-name="hello-api runtime"

Grant access first, then deploy#

This order matters. During a deploy, Cloud Run checks every secret the service uses. It confirms the runtime service account can read it. So grant the Secret Manager Secret Accessor role first:

gcloud secrets add-iam-policy-binding db-password \
  --member="serviceAccount:hello-api-sa@my-hello-api-7.iam.gserviceaccount.com" \
  --role="roles/secretmanager.secretAccessor"

IAM grants can take a few minutes to work. If the deploy below says the account can't read the secret, wait a bit and run it again. Then deploy with the new identity and the secret:

gcloud run deploy hello-api \
  --source . \
  --region us-central1 \
  --service-account hello-api-sa@my-hello-api-7.iam.gserviceaccount.com \
  --update-secrets DB_PASSWORD=db-password:1

DB_PASSWORD=db-password:1 means: put version 1 of the secret db-password into the env var DB_PASSWORD. Your code reads process.env.DB_PASSWORD as normal. curl the URL and dbPasswordSet is now true. Same as with env vars, --set-secrets replaces all secrets and --update-secrets adds to them.

secret-on-deploy
  1. You grant hello-api-sa the Secret Accessor role on db-password.
  2. You deploy with --update-secrets DB_PASSWORD=db-password:1.
  3. Cloud Run checks that hello-api-sa can read db-password.
  4. A new instance starts, and Cloud Run reads version 1 from Secret Manager.
  5. The value goes into DB_PASSWORD before your app starts.
  6. Your app reads process.env.DB_PASSWORD.
step 1 / 6
Skip the first step and the deploy fails at step 3, so the old revision keeps serving.

Pin the version, not latest#

You can write db-password:latest. For env vars, Google recommends a fixed number instead. An env var is read once, when the instance starts. With latest, old instances keep the old password and new ones get the new one. So two values are live at once.

With a pinned number, a password change is a normal change you can see. Add version 2, then run gcloud run services update hello-api --update-secrets DB_PASSWORD=db-password:2. That makes a new revision, and you can roll it back like any other.

Need the value to change without a new revision? Mount the secret as a file instead:

gcloud run services update hello-api \
  --region us-central1 \
  --update-secrets /secrets/db/password=db-password:latest

Your app reads the file /secrets/db/password. Cloud Run fetches a mounted secret from Secret Manager each time your app reads the file.

quick-check

You deploy with --update-secrets DB_PASSWORD=db-password:1, but forgot the Secret Accessor role. What happens?

Revisions and rollback#

A new version of hello-api returns errors. You want the old one back now, without a new build. First, list the revisions:

gcloud run revisions list --service hello-api --region us-central1

Each line is one revision, like hello-api-00004-xyz (the bad one) and hello-api-00003-pqr (the last good one). Send all traffic back to the good one:

gcloud run services update-traffic hello-api \
  --region us-central1 \
  --to-revisions hello-api-00003-pqr=100

No build, no new revision. The rollback docs say the routing changes immediately. This works because revisions never change after they are made. Revision 00003 is the exact image and settings that worked yesterday.

The catch: your traffic is now pinned#

You fix the bug and deploy again. Revision 00005 starts. How much traffic does it get?

Zero. By setting 00003=100, you told Cloud Run "send traffic to this exact revision". The docs say every later deploy keeps that traffic pattern. The new revision is ready, but nobody reaches it. To go back to normal, where each new deploy gets the traffic, run:

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

--to-latest sends 100% to the newest revision now, and to every future one.

rollback-and-back
  1. Deploy 00004: it gets 100% because traffic follows the latest.
  2. Errors! You run update-traffic --to-revisions 00003=100.
  3. Users are on 00003 again, in seconds.
  4. You fix the bug and deploy 00005. It gets 0%, because traffic is pinned to 00003.
  5. You test 00005, then run update-traffic --to-latest.
  6. 00005 gets 100%, and future deploys follow the latest again.
step 1 / 6
After a rollback, a new deploy does not take traffic until you run --to-latest.

Splits and tags for a safer release#

The same command can split traffic. This sends 10% to the new revision as a canary (a small test group of real users):

gcloud run services update-traffic hello-api \
  --region us-central1 \
  --to-revisions hello-api-00005-abc=10,hello-api-00003-pqr=90

You can also deploy with --no-traffic --tag test. The new revision gets 0% of users plus its own URL, like https://test---hello-api-123456789012.us-central1.run.app. You test it there, then move traffic. Ship Without Fear explains canary and blue/green (two full copies, with all traffic switched at once).

One rule for any rollback: the old revision must still work with your database. The new version may have changed the schema (the tables and columns). Then rolling back the code may not be enough. Ship Without Fear covers safe migrations.

quick-check

Yesterday you rolled back with --to-revisions hello-api-00003-pqr=100. Today you deploy 00006. What share of traffic does 00006 get?

Cold starts and sizing#

hello-api is slow on the first request each morning. Here is why:

cold-start
  1. A request arrives, and no instance is running (scaled to zero).
  2. Cloud Run starts a new instance from your image.
  3. Your app boots and starts listening on PORT.
  4. The startup check passes.
  5. Only now the first request gets its answer, so it is slow.
  6. The next requests hit the warm instance and are fast.
step 1 / 6
Steps 2 to 4 are the cold start. A warm instance skips them.

That wait is a cold start. Ways to make it hurt less:

  • Keep one instance warm with --min 1. No cold start, but you pay for it all day. With the default billing, an idle warm instance costs a lower idle rate (How you pay chapter).
  • Startup CPU boost. Extra CPU while an instance starts. The gcloud reference says it is on by default for new services.
  • A smaller image and fast startup code. Don't load heavy libraries before app.listen(). Docker from Zero shows how to shrink the image.

The sizing knobs#

hello-api also ran out of memory once. These flags set the size of each instance and how many can run:

gcloud run services update hello-api \
  --region us-central1 \
  --memory 1Gi \
  --cpu 1 \
  --concurrency 80 \
  --max 3

Words you need:

  • vCPU: a virtual CPU, about one CPU core of compute.
  • In flight: a request that was sent but has no answer yet.
SettingDefault for a new serviceWhat it controls
--memory512Mi (max 32Gi)memory per instance
--cpu1 vCPU (max 8)CPU per instance
--concurrency80 × vCPUs, so 80 at 1 vCPU (max 1,000)max requests in flight on one instance
--min0instances kept warm for the whole service
--max100 per revisionthe most instances that can run
--timeout300 seconds (max 3,600)longest a request can take

Sources: the Cloud Run docs for memory, CPU, concurrency, max instances and the request timeout. More memory needs more CPU: above 4Gi you need at least 2 vCPUs.

Toy numbers for concurrency. 200 requests are in flight, and concurrency is 80. One instance takes at most 80, so Cloud Run needs at least 3 instances. With concurrency 1 you need 200. High concurrency suits an API that mostly waits on a database. Use 1 only for code that can't handle two requests at once.

Use --min and --max, not --min-instances#

Each limit comes in two versions:

FlagsWhere it livesChanges without a new revision?
--min, --maxthe whole serviceyes
--min-instances, --max-instanceseach revisionno

The min instances docs recommend the service-level flags. The max instances docs suggest a max of 3 for a new service, to keep cost under control. Cloud Run can go over the max for a short time during a spike.

quick-check

Concurrency is 80. Suddenly 400 requests are in flight at the same time. How many instances do you need at least?

quick-check

You want a cap that you can change without making a new revision. Which flag?

How you pay#

Before you leave hello-api running, you need to know what it costs.

Words you need:

  • Request-based billing: the default. You pay for CPU and memory only while an instance starts, shuts down, or has at least one request in flight. Plus a small fee per request.
  • Instance-based billing: you pay for the whole life of every instance, from start to stop, even when it does nothing. The rate per second is lower, and there is no per-request fee.
  • vCPU-second / GiB-second: one vCPU (or one GiB of memory) used for one second.

Toy numbers first. hello-api gets 100,000 requests a month. Each takes 200 ms. The instance has 1 vCPU and 512 MiB of memory, and the requests never overlap. This math assumes --min 0, the default. If you set --min 1 earlier, set it back first:

gcloud run services update hello-api --region us-central1 --min 0
  • Time with a request in flight: 100,000 × 0.2 s = 20,000 seconds.
  • CPU: 20,000 × 1 vCPU = 20,000 vCPU-seconds.
  • Memory: 20,000 × 0.5 GiB = 10,000 GiB-seconds.

Now compare that with the monthly free tier on the Cloud Run pricing page (based on us-central1 prices):

Free each monthRequest-based billingInstance-based billing
CPU180,000 vCPU-seconds240,000 vCPU-seconds
Memory360,000 GiB-seconds450,000 GiB-seconds
Requests2 millionno request fee

With request-based billing, this toy app fits inside the free tier many times over. The free tier counts across all projects on one billing account and resets every month.

When instance-based billing makes sense#

Now say one instance stays up the whole month: 30 days × 86,400 s = 2,592,000 seconds. With instance-based billing, that is 2,592,000 vCPU-seconds against 240,000 free, about 10 times. So why would anyone pick it?

Because with request-based billing, the CPU is throttled (slowed to almost nothing) outside requests. Code that keeps working after it sends the response barely runs. A background job or a queue reader are examples.

The billing settings docs say instance-based billing suits that background work, and steady traffic. Request-based suits traffic that comes and goes. The flags still use the old names:

# instance-based billing (CPU always on)
gcloud run services update hello-api --region us-central1 --no-cpu-throttling

# back to request-based billing (the default)
gcloud run services update hello-api --region us-central1 --cpu-throttling

One more cost: --min 1. With request-based billing, that warm instance is billed all month, at a lower "idle" rate when it has no requests.

Cost tips#

  • Let it scale to zero. Set --min only when cold starts really hurt.
  • Cap it with --max. A bug or a traffic flood can't start 100 instances.
  • Watch outbound traffic. Only 1 GiB a month within North America is free.
  • Set a budget alert. In the console: Billing, then Budgets & alerts. The budget docs warn that an alerts-only budget does not cap spending. It emails you, so --max is still your real limit.
quick-check

Your service sends an email after it has already sent the response. With default billing, the emails are very slow. Why?

Logs and common errors#

hello-api breaks one day. Anything it writes to stdout or stderr (the normal output and error output, like console.log and console.error) ends up in Cloud Logging. Read the last 50 lines from your terminal:

gcloud run services logs read hello-api --region us-central1 --limit 50

The console has the same logs: open your service, then the Logs tab.

Write logs as JSON#

A plain line like console.log('payment failed for order 7') is hard to search. Write one JSON object per line instead:

console.log(JSON.stringify({
  severity: 'ERROR',
  message: 'payment failed',
  orderId: 7,
}));

The logging docs say Cloud Logging uses severity as the log level and message as the main text. The other fields become searchable. In Logs Explorer, the filter jsonPayload.orderId=7 finds that line. Same rule as for env vars: never log a password or a token.

Four errors you will hit#

Each one shows the exact message from the troubleshooting docs. Guess the cause before you open it.

Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable.

The revision never got healthy. Common causes:

  • The app listens on a fixed port, not on PORT.
  • The app listens on 127.0.0.1, not 0.0.0.0 (Docker from Zero explains why).
  • The app crashed at startup. Read the logs for the stack trace.
  • The image was built for ARM (an Apple Silicon Mac) and not for 64-bit Linux. --source builds in Cloud Build, so it avoids this.

Run the image locally with -e PORT=8080 -p 8080:8080 first. It gives the same error, faster.

403 Forbidden. Your client does not have permission to get URL from this server.

The service is private (Public or private, in the first deploy chapter). For a public API, deploy with --allow-unauthenticated. For a caller that should be allowed, give its account the Cloud Run Invoker role (roles/run.invoker) on the service and send a Google identity token.

The request was aborted because there was no available instance.

Every instance is full and Cloud Run can't start more, often because you reached --max. Check the instance count on the Metrics tab. Raise --max if the traffic is real. If it is a bug or an attack, the cap did its job.

While handling this request, the container instance was found to be using too much memory and was terminated.

The app used more memory than --memory allows. Raise it (Cold starts and sizing chapter), or find the leak. Files your app writes to its own disk also count as memory on Cloud Run.

quick-check

Your app listens on 127.0.0.1 instead of 0.0.0.0. Which error do you see on deploy?

Deploy from GitHub Actions#

The last step for hello-api: you push to main, and GitHub deploys the new version. No key or password is stored anywhere.

Words you need:

  • OIDC token: a short-lived, signed note from GitHub that says "this job runs in repo my-org/hello-api on branch main". ECS Fargate from Zero explains OIDC in full.
  • Claim: one fact inside that token, like repository or ref (the branch).
  • Issuer: who signed the token. For GitHub Actions it is https://token.actions.githubusercontent.com, the same for every repo.
  • Workload Identity Federation (WIF): Google's way to trust tokens from outside Google and trade them for short-lived Google credentials.
  • Pool and provider: the pool is a group of outside identities. The provider inside it says "trust tokens from this issuer, if they pass a check".
  • Attribute condition: that check, written over the claims. For example, "repository must be my-org/hello-api".
  • principalSet: an IAM name for a group of outside identities, like "every token from this repo".
github-to-cloud-run
  1. You push to main, and the workflow starts.
  2. The job asks GitHub for an OIDC token.
  3. The auth action (the Google login step) sends it to Google. The provider checks the issuer and the attribute condition.
  4. Google lets the job act as github-deployer (the CI service account), with credentials that expire soon.
  5. The deploy-cloudrun action uploads the code, and hello-api-build (the build account) builds it.
  6. The new revision runs as hello-api-sa, and curl checks /health.
step 1 / 6
No long-lived key exists anywhere, so there is nothing to leak or rotate.

Three service accounts take part. Each one gets only what its job needs:

Service accountWho uses itRoles
github-deployerthe GitHub jobCloud Run Source Developer, Service Usage Consumer, and Service Account User on the other two
hello-api-buildCloud Build, during the buildCloud Run Builder
hello-api-sayour running app (Secrets chapter)Secret Accessor on db-password

Service Account User lets github-deployer act as another account. It needs this so the build can run as hello-api-build and the new revision can run as hello-api-sa.

Why a new build account? Your first deploy builds as the Compute Engine default account, which may hold Editor. A deployer that can act as that account could get Editor through a build. The build service account docs recommend your own build account for least privilege (the smallest set of rights that works).

Step 1: the accounts and roles#

Do this once, from your laptop. Fill in your own values on the first three lines:

PROJECT_ID=my-hello-api-7
PROJECT_NUMBER=123456789012
REPO=my-org/hello-api
DEPLOYER="github-deployer@${PROJECT_ID}.iam.gserviceaccount.com"
BUILDER="hello-api-build@${PROJECT_ID}.iam.gserviceaccount.com"

gcloud services enable iam.googleapis.com cloudresourcemanager.googleapis.com \
  iamcredentials.googleapis.com sts.googleapis.com

gcloud iam service-accounts create github-deployer
gcloud iam service-accounts create hello-api-build

gcloud projects add-iam-policy-binding "$PROJECT_ID" \
  --member="serviceAccount:${BUILDER}" --role="roles/run.builder"

for ROLE in roles/run.sourceDeveloper roles/serviceusage.serviceUsageConsumer; do
  gcloud projects add-iam-policy-binding "$PROJECT_ID" \
    --member="serviceAccount:${DEPLOYER}" --role="$ROLE"
done

for SA in "hello-api-sa@${PROJECT_ID}.iam.gserviceaccount.com" "$BUILDER"; do
  gcloud iam service-accounts add-iam-policy-binding "$SA" \
    --member="serviceAccount:${DEPLOYER}" --role="roles/iam.serviceAccountUser"
done

Two of those APIs are new:

  • sts.googleapis.com (Security Token Service): checks the GitHub token and gives back a Google token.
  • iamcredentials.googleapis.com: turns that into short-lived credentials for github-deployer.

The deployer roles come from the deploy-from-source docs. The deployer does not get Cloud Run Admin, so it can't change who may call the service. The deploy-cloudrun README agrees: CI should not change public access. A public service stays public when CI deploys.

Step 2: the pool, the provider and the condition#

gcloud iam workload-identity-pools create github \
  --project="$PROJECT_ID" --location=global \
  --display-name="GitHub Actions"

gcloud iam workload-identity-pools providers create-oidc hello-api \
  --project="$PROJECT_ID" --location=global \
  --workload-identity-pool=github \
  --issuer-uri="https://token.actions.githubusercontent.com" \
  --attribute-mapping="google.subject=assertion.sub,attribute.repository=assertion.repository,attribute.ref=assertion.ref" \
  --attribute-condition="assertion.repository == '${REPO}' && assertion.ref == 'refs/heads/main'"

gcloud iam service-accounts add-iam-policy-binding "$DEPLOYER" \
  --project="$PROJECT_ID" \
  --role="roles/iam.workloadIdentityUser" \
  --member="principalSet://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/github/attribute.repository/${REPO}"

The attribute condition is the most important line. Every repo shares one issuer. So without a condition, your provider accepts a token from any GitHub repo. Google's WIF docs say you must use a condition for GitHub. Mine allows one repo, and only its main branch. The last command lets tokens from that repo act as github-deployer.

  • You can only check a claim you mapped. That is why the mapping lists repository and ref.
  • Google is case-sensitive. GitHub is not. Write my-org/hello-api exactly as the token has it.
  • A repo name can be reused by someone else after a rename or delete. Google recommends the numeric ID claims instead. Map repository_id and check it in the condition. Get the ID with gh api repos/my-org/hello-api --jq .id.

The auth README says changes can take up to 5 minutes to work.

Step 3: the workflow#

The workflow (key lines):

on:
  push:
    branches: [main]
# ...
concurrency:
  group: deploy-hello-api
  cancel-in-progress: false
# ...
    permissions:
      contents: read
      id-token: write
# ...
      - uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3.0.0
        with:
          project_id: my-hello-api-7
          workload_identity_provider: projects/123456789012/locations/global/workloadIdentityPools/github/providers/hello-api
          service_account: github-deployer@my-hello-api-7.iam.gserviceaccount.com
# ...
      - env:
          URL: ${{ steps.deploy.outputs.url }}
        run: curl --fail "$URL/health"
Show full code: the deploy workflow
name: deploy

on:
  push:
    branches: [main]

concurrency:
  group: deploy-hello-api
  cancel-in-progress: false

jobs:
  deploy:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      id-token: write
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

      - uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3.0.0
        with:
          project_id: my-hello-api-7
          workload_identity_provider: projects/123456789012/locations/global/workloadIdentityPools/github/providers/hello-api
          service_account: github-deployer@my-hello-api-7.iam.gserviceaccount.com

      - id: deploy
        uses: google-github-actions/deploy-cloudrun@2028e2d7d30a78c6910e0632e48dd561b064884d # v3.0.1
        with:
          service: hello-api
          region: us-central1
          source: ./
          flags: --build-service-account=projects/my-hello-api-7/serviceAccounts/hello-api-build@my-hello-api-7.iam.gserviceaccount.com

      - env:
          URL: ${{ steps.deploy.outputs.url }}
        run: curl --fail "$URL/health"
  • id-token: write lets the job ask GitHub for the OIDC token.
  • Each action is pinned to a commit SHA (the 40-character ID of one exact commit). Docker from Zero gives the reason. These were the latest releases on 24 October 2026.
  • concurrency makes a second push wait, so two deploys never race.
  • The service keeps the settings you made by hand, like env vars, secrets and hello-api-sa.
  • The URL goes through env:, not straight into run:. GitHub's security guide recommends this, so a value can't be read as shell code.
  • The curl step calls the service URL. If traffic is still pinned from a rollback, it hits the old revision. Run update-traffic --to-latest once before you turn this on.

One more line for the .gcloudignore from your first deploy. The auth step writes a short-lived credentials file like gha-creds-1a2b3c.json into the job's folder, and source: ./ uploads that folder:

gha-creds-*.json
quick-check

Your provider has no attribute condition. What is the risk?

quick-check

A teammate opens a pull request from a branch called fix-login. Can it deploy to Cloud Run?

Recap#

ChapterWhat you can now do
What Cloud Run issay what a project, service, revision, instance and region are, and pick Cloud Run over a VM or ECS for an HTTP app with changing traffic
Setupset up a project: billing, a default region, three APIs and the builder role
Your first deploydeploy with gcloud run deploy --source ., explain each step from upload to URL, and know a private service returns 403
Environment variablesadd one env var with --update-env-vars without wiping the others
Secretsstore a password in Secret Manager, grant the Secret Accessor role first, then deploy with a pinned version
Revisions and rollbackroll back with update-traffic --to-revisions, run --to-latest after the fix, split traffic or test on a tag URL
Cold starts and sizingset memory, CPU, concurrency and service-level --min and --max
How you payexplain request-based and instance-based billing, work out vCPU-seconds, and keep cost low with scale to zero, --max and a budget alert
Logs and common errorsread logs, write JSON logs, and fix the four common errors
Deploy from GitHub Actionsset up WIF with an attribute condition, give each account only the roles it needs, and deploy on every push with pinned actions and no stored key

Try it yourself:

  • Deploy hello-api, break it on purpose (listen on port 3000 only), then roll back with update-traffic.
  • Add a secret, rotate it to version 2, and watch the new revision appear.
  • Try it on a real app with a database, with a budget alert and --max 3 from day one.

Read next: ECS Fargate from Zero runs the same kind of app the AWS way.