Cloud and deployment · Intermediate · 16 min
How to Deploy a Container to Google Cloud Run
By Padding · Updated 15 Nov 2026
Google Cloud Run
You will package a small Node.js 26 web service with a Dockerfile, deploy it to Google Cloud Run with one gcloud command, cap how far it can scale, roll back to an earlier revision, and delete every resource the deploy created.
On this page
Cloud Run runs a container for you and gives it an HTTPS address. You do not manage servers. Google starts instances when requests arrive, adds more under load, and, by default, scales to zero instances when nothing is calling, so an idle service costs close to nothing. The container only has to listen for HTTP on the port that Cloud Run tells it to use.
In this tutorial you will write a small web service, deploy it straight from its source folder, change it, and roll the change back. The last step deletes everything.
This can cost money. Cloud Run bills for the time your code handles requests, plus memory and CPU while it does, and the build and the stored image are billed through Cloud Build and Artifact Registry. Idle services scale to zero, but images and any settings that keep an instance warm still bill. Cloud Run has a free usage allowance, and its size changes. Check cloud.google.com/run/pricing before you start, and consider setting a budget alert in Cloud Billing. The last step lists every resource to delete.
Step 1 · Set up gcloud and the project
Sign in, choose the project, and set a default region. Replace PROJECT_ID with your project's ID, and pick a region near your users, such as europe-west1. Both are examples:
gcloud auth login
gcloud config set project PROJECT_ID
gcloud config set run/region europe-west1Deploying from source uses three services: Cloud Run itself, Cloud Build to build the image, and Artifact Registry to store it. Enable them once for the project. If you skip this, gcloud run deploy asks to enable them for you:
gcloud services enable run.googleapis.com cloudbuild.googleapis.com artifactregistry.googleapis.comYou need permission to deploy. The simplest way is to be an owner of a project that is only for learning. In a shared project, the docs list the roles for the deployer and for the build service account; start from docs.cloud.google.com/run/docs/deploying-source-code. If the first deploy fails with a permission error naming a role, grant that role and wait a couple of minutes, since IAM changes take time to apply.
Step 2 · Write the service
The service answers every request with a line of JSON. Two details matter for Cloud Run. It listens on the port in the PORT environment variable, which Cloud Run sets (the default is 8080), and it listens on all interfaces, not only on localhost. It also stops cleanly on SIGTERM, which Cloud Run sends before it shuts an instance down. It uses only Node.js built-ins, so there is nothing to install.
mkdir hello-run
cd hello-run
cat > server.js <<'JS'
const http = require('node:http')
const port = process.env.PORT || 8080
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ message: 'Hello from Cloud Run', node: process.version }) + '\n')
})
server.listen(port, '0.0.0.0', () => {
console.log(`Listening on port ${port}`)
})
process.on('SIGTERM', () => {
server.close(() => process.exit(0))
})
JS
cat > Dockerfile <<'DOCKER'
FROM node:26-slim
WORKDIR /app
COPY server.js ./
ENV NODE_ENV=production
USER node
CMD ["node", "server.js"]
DOCKERThe Dockerfile follows /tutorials/write-a-dockerfile-for-a-node-app, so the reasoning for each line is there. Because a Dockerfile is in the folder, Cloud Run builds from it. Without one, it would detect the language and use Google Cloud buildpacks instead.
Optionally test the container on your own machine first. Publishing to 127.0.0.1 keeps the port private to you:
docker build -t hello-run .
docker run --rm -e PORT=8080 -p 127.0.0.1:8080:8080 hello-runIn a second terminal, curl http://127.0.0.1:8080/ prints the JSON line. Stop the container with Ctrl+C.
Step 3 · Deploy
One command uploads the folder, builds the image with Cloud Build, stores it in Artifact Registry and creates the service:
gcloud run deploy hello-run --source . --region europe-west1 --allow-unauthenticatedRead two of those flags before you run it. --source . means "build this folder". --allow-unauthenticated makes the service public: anyone on the internet who has the URL can call it, and you pay for every request, so leave the flag out for anything that is not meant to be public. Without it, the service is private, and callers must send a Google identity token. The first deploy also creates an Artifact Registry repository named cloud-run-source-deploy in the region, and the command may ask permission to do that or to enable APIs; answer y.
The build takes a few minutes. It ends with a line that includes Service URL: and an address like https://hello-run-<hash>-ew.a.run.app.
Check it worked
URL=$(gcloud run services describe hello-run --region europe-west1 --format='value(status.url)')
curl -s "$URL"The reply is {"message":"Hello from Cloud Run","node":"v26...."}. For a private service (deployed without --allow-unauthenticated), send an identity token instead:
curl -s -H "Authorization: Bearer $(gcloud auth print-identity-token)" "$URL"Troubleshooting
Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable: the container exited or listens onlocalhostor on a fixed port. Listen on0.0.0.0and onprocess.env.PORT. Read the revision's logs withgcloud run services logs read hello-run --region europe-west1, or in the Logs tab of the service in the console.PERMISSION_DENIEDduring the build, naming a service account and a role: the account that runs the build is missing that role. Grant it and wait a few minutes before retrying.- The service returns
403 Forbiddentocurl: it is private. Either call it with an identity token, or, if it is meant to be public, redeploy with--allow-unauthenticated. Some organisations block public services with a policy, in which case the flag fails and an administrator must change the policy. Billing account for project ... is not found: the project has no billing account linked. Link one in Cloud Billing.
Step 4 · Limit scaling and set resources
By default Cloud Run adds instances as traffic grows, and every one of them bills. For a test service, cap it. A cap also limits the damage of an accidental or malicious flood of requests. Setting a new configuration creates a new revision of the service:
gcloud run deploy hello-run --source . --region europe-west1 \
--allow-unauthenticated --max-instances 2 --memory 512Mi--max-instances 2 allows at most two instances at once, and requests beyond what they can handle wait or fail. --min-instances is the opposite: keeping one or more instances always running avoids slow first requests (cold starts) but bills for the idle time, so leave it at its default of zero for this tutorial. --memory 512Mi sets each instance's memory. 512 MiB is also the default, and it is the smallest value that works with the second-generation execution environment; Google's memory page says the first generation accepts as little as 128 MiB, so a smaller number such as 256Mi can fail depending on the environment. Other flags documented for the command include --cpu, --concurrency for how many requests one instance handles at once, and --timeout for the longest request.
Step 5 · Add settings and secrets
Pass plain settings as environment variables with --update-env-vars, which changes only the variables you name. (--set-env-vars replaces all existing ones.) Do not use environment variables or the command line for anything secret:
gcloud run services update hello-run --region europe-west1 --update-env-vars GREETING=helloFor secrets, store the value in Secret Manager and let Cloud Run mount it. Create the value in a private file, so that it does not appear in your shell history, load it as a secret, delete the file, and mount the secret as a file inside the container. The service account that runs the service needs the role roles/secretmanager.secretAccessor on that secret. A service runs as the Compute Engine default service account unless you chose another one, so ask the service which account it uses, and grant that account the role on this one secret only:
gcloud services enable secretmanager.googleapis.com
install -m 600 /dev/null api-key.txt
openssl rand -hex 16 | tr -d '\n' >> api-key.txt
gcloud secrets create api-key --data-file=api-key.txt
rm api-key.txt
PROJECT_NUMBER=$(gcloud projects describe PROJECT_ID --format='value(projectNumber)')
RUN_SA=$(gcloud run services describe hello-run --region europe-west1 --format='value(spec.template.spec.serviceAccountName)')
RUN_SA=${RUN_SA:-$PROJECT_NUMBER-compute@developer.gserviceaccount.com}
gcloud secrets add-iam-policy-binding api-key \
--member="serviceAccount:$RUN_SA" --role=roles/secretmanager.secretAccessor
gcloud run services update hello-run --region europe-west1 --set-secrets=/secrets/api-key=api-key:latestThe describe command prints an empty value when the service uses the default account, and the next line then falls back to the default account's address, PROJECT_NUMBER-compute@developer.gserviceaccount.com. Replace PROJECT_ID with your project's ID. Deploying with secrets also needs the Service Account User role (roles/iam.serviceAccountUser) on that account, which an owner of a learning project already has.
A key that starts with / in --set-secrets is a path to mount, so the container finds the value in the file /secrets/api-key. A key that does not start with / becomes an environment variable instead. If the update still fails with a permission error on the secret, the message names the account that lacks the role; grant it as above and retry. Read /tutorials/keep-secrets-out-of-git for why the value never goes into your code or Dockerfile.
Step 6 · Roll back
Every deploy or update makes a numbered revision, and traffic goes to the latest by default. List them, and send all traffic back to an earlier one. Replace REVISION with a name from the list:
gcloud run revisions list --service hello-run --region europe-west1
gcloud run services update-traffic hello-run --region europe-west1 --to-revisions=REVISION=100=100 is the percentage of traffic. To split traffic between two revisions while you test a change, give each a percentage that adds up to 100. To go back to always using the newest revision, run gcloud run services update-traffic hello-run --region europe-west1 --to-latest.
Step 7 · Delete everything
Cloud Run services do not bill while idle, but the other resources do. Delete them. First the service, which removes its revisions and its URL:
gcloud run services delete hello-run --region europe-west1Then the Artifact Registry repository that holds the built images. This deletes every image in it, so run it only if the repository holds nothing you need:
gcloud artifacts repositories delete cloud-run-source-deploy --location=europe-west1If you created the secret, delete that too. The source upload also went to a Cloud Storage bucket that the deploy created. List the buckets in the project, find the one made by the deploy (its name is something like run-sources-PROJECT_ID-europe-west1), check that it holds only your demo, and delete it with everything in it:
gcloud secrets delete api-key
gcloud storage buckets list --format='value(name)'
gcloud storage rm -r gs://BUCKET_NAMEgcloud storage rm -r on a bucket URL deletes the objects and then the bucket. Replace BUCKET_NAME with the name from the list.
If the project was only for this tutorial, the surest cleanup is to delete the whole project, which stops all billing for it after a short delay. This cannot be undone, and it removes everything in the project:
gcloud projects delete PROJECT_IDCheck it worked
gcloud run services list no longer shows hello-run, and gcloud artifacts repositories list no longer shows cloud-run-source-deploy. Check the Billing reports the next day to see that charges have stopped.
Next steps
- Understand the Dockerfile:
/tutorials/write-a-dockerfile-for-a-node-app. - Keep credentials out of code:
/tutorials/keep-secrets-out-of-git. - Google's references: docs.cloud.google.com/run/docs/deploying-source-code and docs.cloud.google.com/sdk/gcloud/reference/run/deploy.
Related tutorials
- How to Write a Dockerfile for a Node.js AppYou will write a Dockerfile for a small Express app on Node.js 26, build it into an image, run it as a container on port 3000 as a non-root user, and order the file so rebuilds take seconds.
- How to Keep Passwords and API Keys Out of GitYou will keep secrets in a git-ignored .env file, commit a safe template instead, stop a commit that contains a key with a pre-commit hook, and learn what to do when a secret has already been committed.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials