Deploy services from source code

This page describes how to deploy a new service or service revision toCloud Run directly from source code using a singlegcloud CLI command,gcloud run deploy with the--source flag. For an examplewalkthrough of deploying a Hello World service, seeDeploy from source quickstarts.Note: The deploy command defaults to source deployment if you don't supply--image or--source flags.There are two different ways to use this feature:

Note that source deployments useArtifact Registry tostore built containers. If your project doesn't already have an Artifact Registryrepository with the namecloud-run-source-deploy in the region you aredeploying to, this feature automatically creates an Artifact Registry repositorywith the namecloud-run-source-deploy.

If a Dockerfile is present in the source code directory, the uploaded sourcecode is built using that Dockerfile. If no Dockerfile is present in the sourcecode directory, Google Cloud's buildpacks automatically detects the language youare using and fetches the dependencies of the code to make a production-readycontainer image, using a secure base image managed by Google.

By default, security fixes are only applied when the Cloud Runservice is deployed. Whenyou enable automatic security updates for a service, that service receives patchesautomatically with zero downtime. Learn more aboutconfiguring security updates.

Before you begin

  • Make sure you have set up a new project for Cloud Run as describedin thesetup page.
  • If you are under a domain restriction organization policyrestricting unauthenticated invocations for your project, you will need to access your deployed service as described underTesting private services.

  • Enable the Cloud Run Admin API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enable permission.Learn how to grant roles.

    Enable the API

    After the Cloud Run Admin API is enabled, the Compute Engine default service account isautomatically created.

Required roles

To deploy from source, you or your administrator must grant thedeployer account the following IAM roles.

Click to view required roles for the deployer account

To get the permissions that you need to build and deploy from source, ask your administrator to grant you the following IAM roles:

For a list of IAM roles and permissions that are associated withCloud Run, seeCloud Run IAM rolesandCloud Run IAM permissions.If your Cloud Run service interfaces withGoogle Cloud APIs, such as Cloud Client Libraries, see theservice identity configuration guide.For more information about granting roles, seedeployment permissionsandmanage access.

Supported languages

In addition to sources with a Dockerfile, deploying from sourcesupports the following languages usingGoogle Cloud's buildpacks:

RuntimeSource deploymentBuildpack configuration
GoDeploy a Go serviceConfigure Go buildpacks
Node.jsDeploy a Node.js serviceConfigure Node.js buildpacks
PythonDeploy a Python serviceConfigure Python buildpacks
Java
(includes Kotlin, Groovy, Scala)
Deploy a Java serviceConfigure Java buildpacks
.NETDeploy a .NET serviceConfigure .NET buildpacks
RubyDeploy a Ruby serviceConfigure Ruby buildpacks
PHPDeploy a PHP serviceConfigure PHP buildpacks

Read more details aboutsupported language versions.

Deploy from source with build

This section describes how to useGoogle Cloud's buildpacksand Cloud Build to automatically build container images from your sourcecode without having to install Docker on your machine or set up buildpacks orCloud Build.

Limitations

  • Deploy from source uses Artifact Registry and Cloud Build, so this feature is only available inregions supported by Artifact Registry andCloud Build.
  • Deploying from source is a conveniencefeature, and does not allow full customization of the build. For morecontrol, build the container image using Cloud Build, for example,usinggcloud builds submit, and thendeploy the container image using, for example,gcloud run deploy --image.
  • Deploying from source with Google Cloud's buildpacks sets the Last Modified Dateof source files to Jan 1, 1980. This is the default behavior of buildpacks and is designed to supportreproducible builds. Depending on yourlanguage framework, this can affect browser-side caching of static files. Ifyour application is affected by this, Google recommends disablingetag andLast-Modified HTTP headers in your application.
  • Deploying from source with Google Cloud's buildpacks always usesgcr.io/buildpacks/builder:latest.If your preferred language or OS configuration is not available inlatest,use a specific builder tocreate an application image using your preferred builder.
  • You can deploy your service from source using Kotlin and other JVM languagessuch asJava. The language you use must conform tothe following rules:

    • You can build the application using Maven or Gradle.
    • The build file contains all the plugins required to product classes.

Before you deploy with build

Before you deploy from source with build:

  • Follow the steps inBefore you begin.

  • Enable the Cloud Build API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enable permission.Learn how to grant roles.

    Enable the API

Required roles

To deploy from source with build, you or your administrator must grant theCloud Build service account the following IAM roles.

Click to view required roles for the Cloud Build service account

Cloud Build automatically uses theCompute Engine default service account as the default Cloud Build service account to build your source code and Cloud Run resource, unless you override this behavior. For Cloud Build to build your sources, ask your administrator to grantCloud Run Builder (roles/run.builder) to the Compute Engine default service account on your project:

gcloudprojectsadd-iam-policy-bindingPROJECT_ID\--member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com\--role=roles/run.builder

ReplacePROJECT_NUMBER with your Google Cloud project number, andPROJECT_ID with your Google Cloud project ID. For detailed instructions on how to find your project ID, and project number, seeCreating and managing projects.

Granting the Cloud Run builder role to the Compute Engine default service account takes a couple of minutes topropagate.

Note:

Theiam.automaticIamGrantsForDefaultServiceAccounts organization policy constraint prevents the Editor role from being automatically granted to default service accounts. If you created your organization after May 3, 2024, this constraint is enforced by default.

We strongly recommend that you enforce this constraint to disable the automatic role grant. If you disable the automatic role grant, you must decide which roles to grant to the default service accounts, and thengrant these roles yourself.

If the default service account already has the Editor role, we recommend that you replace the Editor role with less permissive roles.To safely modify the service account's roles, usePolicy Simulator to see the impact of the change, and thengrant and revoke the appropriate roles.

For a list of IAM roles and permissions that are associated withCloud Run, seeCloud Run IAM rolesandCloud Run IAM permissions.If your Cloud Run service interfaces withGoogle Cloud APIs, such as Cloud Client Libraries, see theservice identity configuration guide.For more information about granting roles, seedeployment permissionsandmanage access.

Deploy with build

To deploy from source code, click the tab for instructions on using the tool ofyour choice.

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, aCloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. Change to your source directory. The source directory uses a Dockerfile ifpresent, although it's not required.

  3. Build and deploy your service:

    gcloudrundeploySERVICE--source.

    ReplaceSERVICE with the name you want for yourservice.

  4. Respond to any prompts to install required APIs by respondingy whenprompted. You only need to do this once for a project. Respond to otherprompts by supplying the platform and region, if you haven't set defaultsfor these as described in thesetup page.

  5. Wait for the build and deploy to complete. When finished,Cloud Run displays a success message.

After deployment, this service revision serves 100%of traffic.

Cloud Code

To deploy from source usingCloud Code, read theIntelliJ andVisual Studio Code guides.

Gemini CLI

Use the/deploy command in theGemini CLItool to deploy a Cloud Run service fromsource code.

To use the Gemini CLI with theCloud Run extension,follow these steps:

  1. Install the latest version of theGemini CLIin one of the following development environments:

    • Terminal
    • Cloud Shell
    • VS Code using Gemini Code Assist agent mode (see the"VS Code" tab)
  2. Install the Cloud Run extension:

    geminiextensionsinstallhttps://github.com/GoogleCloudPlatform/cloud-run-mcp
  3. Sign in to the Google Cloud CLI:

    gcloudauthlogin
  4. Set up Application Default Credentials:

    gcloudauthapplication-defaultlogin
  5. Change to your source code directory.

  6. Launch the Gemini CLI:

    gemini
  7. Build and deploy your service:

    /deploy
    • If you are prompted to provide the Google Cloud project, enteryour project name.
    • If you are prompted to select a tool, selectdeploy_local_folder.
  8. Wait for the build and deploy to complete. When finished,Cloud Run displays a success message.

MCP

To deploy a Cloud Run service from source codefrom a Model Context Protocol (MCP) client, install theCloud Run Model Context Protocol (MCP) server.

Installation instructions vary depending on the MCP client. Often, theyrequire adding the following lines to the settings JSON file:

"mcpServers":{"cloud-run":{"command":"npx","args":["-y", "@google-cloud/cloud-run-mcp"]}}

Compose

Preview — Cloud Run Compose deploy

This feature is subject to the "Pre-GA Offerings Terms" in the General Service Terms section of theService Specific Terms. Pre-GA features are available "as is" and might have limited support. For more information, see thelaunch stage descriptions.

You can store yourCompose Specification inaYAML file and then deploy it from source code as a Cloud Runservice using a single gcloud command.

  1. Change to your source directory. The source directory uses a Dockerfileif present, although it's not required.

  2. In your project directory, create acompose.yaml file with yourservice definitions.

    services:web:build:.ports:-"8080:8080"

    You can also specify more configuration options such as environmentvariables, secrets, and volume mounts.

  3. To deploy the services, run thegcloud beta run compose up command:

    gcloud beta run compose up compose.yaml
  4. Respondy to any prompts to install required components or to enableAPIs.

  5. Optional:Make your service publicif you want to allow unauthenticated access to the service.

After deployment, the Cloud Run service URL is displayed. Copythis URL and paste it into your browser to view the running container. You candisable the default authentication from the Google Cloud console.

Deploy from source without build

Preview — Deploy without build

This feature is subject to the "Pre-GA Offerings Terms" in the General Service Terms section of theService Specific Terms. Pre-GA features are available "as is" and might have limited support. For more information, see thelaunch stage descriptions.

You can deploy source artifacts directly toCloud Run, bypassing the Cloud Build step.The way this works is that instead of building a containerimage from source, you can upload a pre-packaged archive of your applicationdirectly to a Cloud Storage bucket. Cloud Run then takes thisarchive and runs it directly on a base image. This approach resultsin dramatically faster deployment times.

Limitations

Deploy to source without build only supports the following:

  • Cloud Run services.
  • Supported runtimes (no Dockerfile support).
  • Source archive (.tar.gz) <= 250 MiB.
  • Binary (for example, go binary) or script (for example, python script) must becompatible with x86 architecture.
  • The source has to be self-contained, with all the dependencies packaged. Theruntime base image only contains the minimum operating system and a fewlanguage libraries.

Before you deploy without build

To use the "deploy without build" feature:

  • Make sure you have followed the steps inBefore you begin.
  • Enable the Cloud Run and Cloud Storage APIs:

    gcloud services enable run.googleapis.com \  storage.googleapis.com
  • You must install the application dependencies locally before deploying, asthey won't be installed (no build).

Deploy without build

This section describes how to deploy your artifact directly toCloud Run without using build.

gcloud

To deploy a local source directory, use the--no-build flag to tell thedeploy command to bypass the Cloud Build step:

gcloud beta run deploySERVICE_NAME \  --sourceAPPLICATION_PATH \  --no-build \  --base-image=BASE_IMAGE \  --command=COMMAND \  --args=ARG

Replace the following:

  • SERVICE_NAME: the name of your Cloud Runservice.
  • APPLICATION_PATH: the location of your applicationon the local file system.
  • BASE_IMAGE: theruntime base imageyou want to use for your application. For example,us-central1-docker.pkg.dev/serverless-runtimes/google-24-full/runtimes/nodejs24.
  • COMMAND: the command that the container starts up with.
  • ARG: an argument you send to thecontainer command. If you use multiple arguments, specify each on its ownline.

YAML

You can store your service specification in a YAML file and then deploy itusing the gcloud CLI or the Google Cloud consoleservice.yamleditor.

  1. Create a storage bucket to hold your application:

    gcloud storage buckets create gs://BUCKET_NAME --location=BUCKET_LOCATION

    Replace the following:

    • BUCKET_NAME: the name you want to give your bucket, subject tonaming requirements. For example,my-bucket.
    • BUCKET_LOCATION: thelocation of your bucket. For example,US.
  2. Create an archive with your application source using either zip or tar,for example:

    tar -cvzfARCHIVE_NAMEAPPLICATION_PATH

    Replace the following:

    • ARCHIVE_NAME: the name of the archive tocreate. For example,app.tar.gz.
    • APPLICATION_PATH: the location of yourapplication on the local file system. For example,~/my-application.To archive the current working directory, set this value to*.
  3. Upload your application archive to Cloud Storage:

    gcloud storage cpARCHIVE_NAME gs://BUCKET_NAME

    Replace the following:

    • ARCHIVE_NAME: the local path to the archive youcreated previously. For example,app.tar.gz.
    • BUCKET_NAME: the name of the bucket you createdpreviously. For example,my-bucket.
  4. Create a newservice.yaml file with the following content:

    apiVersion: serving.knative.dev/v2kind: Servicemetadata: name:SERVICE_NAMEspec: template:   metadata:     annotations:       run.googleapis.com/sources: '{"": "gs://BUCKET_NAME/ARCHIVE_NAME"}'       run.googleapis.com/base-images: '{"": "BASE_IMAGE"}'   spec:     containers:     - image: scratch       command:       -COMMAND       args:       -ARG1       -ARG-N     runtimeClassName: run.googleapis.com/linux-base-image-update

    Replace the following:

    • SERVICE_NAME: the name of your Cloud Runservice. Service names must be 49 characters or less and must be uniqueper region and project.
    • BUCKET_NAME: the name of the bucket you createdpreviously. For example,my-bucket.
    • ARCHIVE_NAME: the local path to the archive youcreated previously. For example,app.tar.gz.
    • BASE_IMAGE: the runtime base image you want touse for your application. For example,us-central1-docker.pkg.dev/serverless-runtimes/google-24-full/runtimes/nodejs24.
    • COMMAND: the command that the container isto start up with.
    • ARG1: the argument you are sending to thecontainer command. If you use multiple arguments, specify each on itsown line, for example, as shown,ARG-N.
  5. Deploy the new service:

    gcloud run services replace service.yaml

REST API

REST API:

curl -H "Content-Type: application/json" \-H "Authorization: BearerACCESS_TOKEN" \-X POST \-d '{"template": {"containers": [{"command": ["npm"], "args": ["start"], "image": "scratch", "baseImageUri": "google-22/nodejs22", "sourceCode": {"cloudStorageSource": {"bucket": "'GCS_BUCKET_NAME", "object":"ARCHIVE"}}}]}}' \https://run.googleapis.com/v2/projects/PROJECT_ID/locations/REGION/services?serviceId=SERVICE_NAME

Examples of deploying from source without build

This section shows examples of how to deploy from source without using build.

Node.js

Create a Node.js service:

  1. Create a new directory namedhelloworld and change directoryinto it:

    mkdir helloworldcd helloworld
  2. Create apackage.json file with the following contents:

    {"name":"helloworld","description":"Simple hello world sample in Node","version":"1.0.0","private":true,"main":"index.js","type":"module","scripts":{"start":"node index.js"},"engines":{"node":">=16.0.0"},"author":"Google LLC","license":"Apache-2.0","dependencies":{"express":"^4.17.1"}}
  3. In the same directory, create aindex.js file, and copy the followinglines into it:

    importexpressfrom'express';constapp=express();app.get('/',(req,res)=>{constname=process.env.NAME||'World';res.send(`Hello${name}!`);});constport=parseInt(process.env.PORT)||8080;app.listen(port,()=>{console.log(`helloworld: listening on port${port}`);});

    This code creates a basic web server that listens on the port defined by thePORT environment variable.

  4. In yourhelloworld directory, run the following command to install the service dependencies locally:

    npm install
  5. In yourhelloworld directory, deploy the service using the--no-build flag, which tells thedeploy command to skip theCloud Build step:

    gcloud beta run deploy helloworld \ --source . \ --region=REGION \ --no-build \ --base-image=nodejs24 \ --command=node \ --args=index.js

    Replace the following:

    • REGION: the region where your service is deployed.

Python

Create a Python service:

  1. Create a new directory namedhelloworld and change directoryinto it:

    mkdirhelloworldcdhelloworld
  2. Create a file namedmain.py and paste the following code into it:

    importosfromflaskimportFlaskapp=Flask(__name__)@app.route("/")defhello_world():"""Example Hello World route."""name=os.environ.get("NAME","World")returnf"Hello{name}!"if__name__=="__main__":app.run(debug=True,host="0.0.0.0",port=int(os.environ.get("PORT",8080)))

    This code responds to requests with our "Hello World" greeting. HTTPhandling is done by a Gunicorn web server in the container. Whendirectly invoked for local use, this code creates a basic web server thatlistens on the port defined by thePORT environment variable.

  3. Create a file namedrequirements.txt and paste the following code into it:

    Flask==3.0.3gunicorn==23.0.0Werkzeug==3.0.3

    This code adds packages needed by the sample.

  4. Vendor the dependencies:

    pip3 install -r requirements.txt --target=./vendor
  5. Deploy the service using the gcloud CLI. The--no-build flag tells thedeploy command to bypass the Cloud Build step:

    gcloud beta run deploy helloworld \  --source . \  --region=REGION \  --no-build \  --base-image=python313 \  --command=python \  --args=main.py \  --set-env-vars PYTHONPATH=./vendor

ReplaceREGION with the region where your service is deployed.

Troubleshooting

This section gives some tips on troubleshooting deploy from source without using build.

Local development

Deploying from source without using build works similarly to mounting your code orexecutable to the base image.

For example:

  1. Make a copy of all the contents:

    cp -R python/hello-world/ workspace
  2. Run the base image as root user with the source mounted. You can optionallyinclude-p 8080:8080 if you need to curl from a host machine.

    docker run -it -v "LOCAL_PATH" -u 0 us-central1-docker.pkg.dev/serverless-runtimes/google-22-full/runtimes/python313 /bin/bash`

    ReplaceLOCAL_PATH with the location of your local source files.

  3. Run the server:

    python main.py

Execution log

The execution log is useful for debugging deployment failure. In theGoogle Cloud console, go toObservability > Logs.

Permission denied on Cloud Storage access

If your Cloud Run service is encountering "Permission denied" errorswhen trying to access Cloud Storage objects, you must grant theroles/storage.objectViewer role to your Cloud Run service account:

gcloud projects add-iam-policy-bindingPROJECT \  --member="SERVICE_ACCOUNT" \  --role="roles/storage.objectViewer"

Replace the following:

  • PROJECT: your Google Cloud project ID.
  • SERVICE_ACCOUNT: your Cloud Run service account.For example,service-123@serverless-robot-staging.iam.gserviceaccount.com.

Automating building from source

As a best practice for avoiding unversioned changes in local source, Googlerecommends that you automatically deploy when changes are pushed to your Gitrepository. To make this easier, you can connect and configure continuousdeployment to your Cloud Run service. By connecting your GitHub repositories toCloud Run, you can configure builds and deploy your repositorieswithout writing Dockerfiles or build files.

To configure automated builds, set up automation as described in thecontinuous builds page,making sure you choose the option for building source with buildpacks.

What's next

After you deploy a Cloud Run service, you can do the following:

Learn about the source deploy configurations:

You can automate the builds and deployments of your Cloud Run servicesusing Cloud Build triggers:

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-17 UTC.