Deploy functions in Cloud Run

This page describes how to deploy and modify functions in Cloud Run. For an example walkthrough of deploying a Hello World function, see Deploy a sample function.

Behind the scenes, Cloud Run function deployments use Google Cloud's buildpacks and Cloud Build to automatically build container images from your function's source code without having to install Docker on your machine or set up buildpacks or Cloud Build.

Cloud Run function deployments also use Artifact Registry to store artifacts and manage container images. Artifact Registry automatically creates the Artifact Registry repository cloud-run-source-deploy if your project hasn't already created one with this name.

Before you begin

  1. Make sure you have set up a new project for Cloud Run as described in the setup page.

  2. Enable the Artifact Registry, Cloud Build, Cloud Run Admin API, and Cloud Logging APIs:

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

    Optionally, enable the Eventarc API to use event triggers:

     gcloud services enable eventarc.googleapis.com
    
  3. If you are under a domain restriction organization policy restricting unauthenticated invocations for your project, you will need to access your deployed service as described under Testing private services.

Required roles

To get the permissions that you need to deploy Cloud Run services from source, ask your administrator to grant you the following IAM roles on your project:

For a list of IAM roles and permissions that are associated with Cloud Run, see Cloud Run IAM roles and Cloud Run IAM permissions. If your Cloud Run service interfaces with Google Cloud APIs, such as Cloud Client Libraries, see the service identity configuration guide. For more information about granting roles, see deployment permissions and manage access.

Roles for service account

  • For Cloud Build to be able to build your sources, grant the Cloud Build Service Account role to the Compute Engine default service account by running the following:

    gcloud projects add-iam-policy-binding PROJECT_ID \
        --member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com \
        --role=roles/cloudbuild.builds.builder
    

    Replace PROJECT_NUMBER with your Google Cloud project number, and PROJECT_ID with your Google Cloud project ID. For detailed instructions on how to find your project ID, and project number, see Creating and managing projects.

    Granting the Cloud Build Service Account role to the Compute Engine default service account takes a couple of minutes to propagate.

  • Create and deploy a function

    You can deploy a function using the Google Cloud console, or the gcloud CLI. Click the tab for instructions on using the tool of your choice.

    Console

    1. In the Google Cloud console, go to the Cloud Run page:

      Go to Cloud Run

    2. Click Write a function.

    3. In the Service name field, enter a name to describe your function. Service names must only begin with a letter, and contain up to 49 characters or less, including letters, numbers, or hyphens. Service names can't end with hyphens, and must be unique per region and project. A service name cannot be changed later and is publicly visible.

    4. In the Region list, use the default value, or select the region where you want to deploy your function.

    5. In the Runtime list, use the default value, or select a runtime version.

    6. Optionally, in the Trigger section, click Add trigger and select an option. The Eventarc trigger pane opens, where you can modify the following details for the trigger:

      1. In the Trigger name filed, enter a name for the trigger, or use the default name.

      2. Select a Trigger type from the list to specify one of the following trigger types:

        • Google Sources to specify triggers for Pub/Sub, Cloud Storage, Firestore, and other Google event providers.

        • Custom to produce and consume events from your application code. Follow the prompts in the Eventarc trigger pane to create a channel. A channel is a resource that is used as a pipeline to deliver custom events from producers to consumers. Custom events are published to a channel, and an Eventarc trigger subscribes to those events.

        • Third-party to integrate with non-Google providers that offer an Eventarc source. For more information, see Third-party events in Eventarc.

      3. Select an Event provider from the list, to select a product that provides the type of event for triggering your function. For the list of event providers, see Event providers and destinations.

      4. Select an Event type from the list. Your trigger configuration varies depending on the supported event type. For more information, see Event types.

      5. In the Region field, select a location for the Eventarc trigger. In general, the location of an Eventarc trigger should match the location of the Google Cloud resource that you want to monitor for events. In most scenarios, you should also deploy your function in the same region. See Understand Eventarc locations for more details about Eventarc trigger locations.

      6. In the Service account field, select a service account. Eventarc triggers are linked to service accounts to use as an identity when invoking your function. Your Eventarc trigger's service account must have the permission to invoke your function. By default, Cloud Run uses the Compute Engine default service account.

      7. Optionally, specify the Service URL path to send the incoming request to. This is the relative path on the destination service to which the events for the trigger should be sent. For example: /, /route, route, and route/subroute.

      8. Once you've completed the required fields, click Save trigger.

    7. Under Authentication, configure the following:

      • If you are creating a public HTTP function, for example a webhook, select Allow unauthenticated invocations. Selecting this assigns the IAM Invoker role to the special identifier allUser. You can use IAM to edit this setting later after you create the service. If you don't have permissions (Cloud Run Admin role) to select this, the service will deploy and require authentication.

      • If you are creating an event-triggered function, select Require authentication.

    8. Optionally, update the following additional configurations for your functions:

      1. Set CPU allocation and pricing as needed.

      2. Under Service autoscaling, specify minimum instances as needed.

      3. Set the Ingress control settings as needed.

      4. Expand the Container(s), Volumes, Networking, Security section, to set other optional settings in the appropriate tabs:

    9. Click Create, and wait for Cloud Run to create the service using a placeholder revision.

    10. The console will redirect you to the Source tab where you can see the source code of your function. Click Save and redeploy.

    11. In the Source tab, you can optionally click Show Payload to see an example payload of incoming events.

    12. After deployment, test the created function by clicking the Test button.

    gcloud

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

      Activate Cloud Shell

      At the bottom of the Google Cloud console, a Cloud 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. Update gcloud components to the latest version:

      gcloud components update
      
    3. Run the following command in the directory that contains the sample code:

      gcloud beta run deploy FUNCTION \
             --source . \
             --function FUNCTION_ENTRYPOINT \
             --base-image BASE_IMAGE \
             --region REGION
      

      Replace:

      • FUNCTION with the name of the function you are deploying. You can omit this parameter entirely, but you will be prompted for the name if you omit it.

      • FUNCTION_ENTRYPOINT with the entry point to your function in your source code. This is the code Cloud Run executes when your function runs. The value of this flag must be a function name or fully-qualified class name that exists in your source code.

      • BASE_IMAGE with the base image environment for your function. For more details about base images and the packages included in each image, see Runtimes base images.

      • REGION with the Google Cloud region where you want to deploy your function. For example, us-central1.

      Optional:

      • If you are creating a public HTTP function, for example a webhook, specify the --allow-unauthenticated flag. This flag assigns the Cloud Run IAM Invoker role to the special identifier allUser. You can use IAM to edit this setting later after you create the service. If you are creating an event-triggered function or authenticated service, you can omit this flag.

    Optionally, after deploying your function, you can add Eventarc triggers to your function. To add a trigger, run the following command:

      gcloud eventarc triggers create EVENTARC_TRIGGER_NAME \
          --location=EVENTARC_TRIGGER_LOCATION \
          --destination-run-service=FUNCTION \
          --destination-run-region=REGION \
          --event-filters="type=EVENTARC_FILTER_TYPE" \
          --event-filters="EVENTARC_EVENT_FILTER" \
          --service-account=EVENTARC_TRIGGER_SERVICE_ACCOUNT
    

    Replace:

    • EVENTARC_TRIGGER_NAME with the name of the Eventarc trigger.

    • EVENTARC_TRIGGER_LOCATION with the location for the Eventarc trigger. In general, the location of an Eventarc trigger should match the location of the Google Cloud resource that you want to monitor for events. In most scenarios, you should also deploy your function in the same region. See Understand Eventarc locations for more details about Eventarc trigger locations.

    • FUNCTION with the name of your deployed function.

    • REGION with the Cloud Run region of the function.

    • EVENTARC_FILTER_TYPE with the event filters that the trigger monitors. An event that matches all the --event-filters filters triggers calls to your function. Each trigger must have a supported event type in the form --event-filters="type=EVENTARC_FILTER_TYPE". This event type can't be changed after creation. To change EVENT_FILTER_TYPE, create a new trigger and delete the old one. Optionally, you can repeat the --event-filters flag with a supported filter in the form ATTRIBUTE=VALUE to add more filters.

    • EVENTARC_TRIGGER_SERVICE_ACCOUNT with a service account. Eventarc triggers are linked to service accounts to use as an identity when invoking your function. Your Eventarc trigger's service account must have the permission to invoke your function. By default, Cloud Run uses the Default compute service account.

    Terraform

    To manage functions using Terraform, you must build your function code into a container image, then define your Cloud Run service in a Terraform configuration using the google_cloud_run_v2_service resource from the Google Cloud Platform Provider.

    1. Follow the instructions on building a function to create a container image. Copy the full path of the container image for the IMAGE_URL variable used in the next step.

    2. Create a new main.tf file with this content:

      provider "google" {
        project = "PROJECT-ID"
      }
      
      resource "google_cloud_run_v2_service" "default" {
        name     = "SERVICE"
        location = "REGION"
        client   = "terraform"
        template {
          containers {
            image = "IMAGE_URL"
          }
        }
      }
      
      resource "google_cloud_run_v2_service_iam_member" "noauth" {
        location = google_cloud_run_v2_service.default.location
        name     = google_cloud_run_v2_service.default.name
        role     = "roles/run.invoker"
        member   = "allUsers"
      }
      

      Replace:

      • PROJECT-ID with the Google Cloud project ID.
      • REGION with the Google Cloud region.
      • SERVICE with the name of your Cloud Run service. Service names must be 49 characters or less and must be unique per region and project.
      • IMAGE_URL with a reference to the container image, for example, us-docker.pkg.dev/cloudrun/container/hello:latest. If you use Artifact Registry, the repository REPO_NAME must already be created. The URL has the shape LOCATION-docker.pkg.dev/PROJECT_ID/REPO_NAME/PATH:TAG

      This configuration allows public access (the equivalent of --allow-unauthenticated). To make the service private, remove the google_cloud_run_v2_service_iam_member stanza.

    3. Initialize Terraform:

      terraform init
    4. Apply the Terraform configuration:

      terraform apply

      Confirm you want to apply the actions described by entering yes.

    Cloud Run locations

    Cloud Run is regional, which means the infrastructure that runs your Cloud Run services is located in a specific region and is managed by Google to be redundantly available across all the zones within that region.

    Meeting your latency, availability, or durability requirements are primary factors for selecting the region where your Cloud Run services are run. You can generally select the region nearest to your users but you should consider the location of the other Google Cloud products that are used by your Cloud Run service. Using Google Cloud products together across multiple locations can affect your service's latency as well as cost.

    Cloud Run is available in the following regions:

    Subject to Tier 1 pricing

    • asia-east1 (Taiwan)
    • asia-northeast1 (Tokyo)
    • asia-northeast2 (Osaka)
    • asia-south1 (Mumbai, India)
    • europe-north1 (Finland) leaf icon Low CO2
    • europe-southwest1 (Madrid) leaf icon Low CO2
    • europe-west1 (Belgium) leaf icon Low CO2
    • europe-west4 (Netherlands) leaf icon Low CO2
    • europe-west8 (Milan)
    • europe-west9 (Paris) leaf icon Low CO2
    • me-west1 (Tel Aviv)
    • us-central1 (Iowa) leaf icon Low CO2
    • us-east1 (South Carolina)
    • us-east4 (Northern Virginia)
    • us-east5 (Columbus)
    • us-south1 (Dallas) leaf icon Low CO2
    • us-west1 (Oregon) leaf icon Low CO2

    Subject to Tier 2 pricing

    • africa-south1 (Johannesburg)
    • asia-east2 (Hong Kong)
    • asia-northeast3 (Seoul, South Korea)
    • asia-southeast1 (Singapore)
    • asia-southeast2 (Jakarta)
    • asia-south2 (Delhi, India)
    • australia-southeast1 (Sydney)
    • australia-southeast2 (Melbourne)
    • europe-central2 (Warsaw, Poland)
    • europe-west10 (Berlin) leaf icon Low CO2
    • europe-west12 (Turin)
    • europe-west2 (London, UK) leaf icon Low CO2
    • europe-west3 (Frankfurt, Germany) leaf icon Low CO2
    • europe-west6 (Zurich, Switzerland) leaf icon Low CO2
    • me-central1 (Doha)
    • me-central2 (Dammam)
    • northamerica-northeast1 (Montreal) leaf icon Low CO2
    • northamerica-northeast2 (Toronto) leaf icon Low CO2
    • southamerica-east1 (Sao Paulo, Brazil) leaf icon Low CO2
    • southamerica-west1 (Santiago, Chile) leaf icon Low CO2
    • us-west2 (Los Angeles)
    • us-west3 (Salt Lake City)
    • us-west4 (Las Vegas)

    If you already created a Cloud Run service, you can view the region in the Cloud Run dashboard in the Google Cloud console.

    Enable event retries

    Eventarc uses Pub/Sub as its transport layer and has a default retry policy that might not work well for your function.

    After creating an Eventarc trigger, we strongly recommend updating the retry policy in Eventarc and configuring dead-letter topic in Pub/Sub.

    Modify an existing function

    You can either modify the configuration or the code of your function:

    Modify configuration

    To modify configuration parameters, such as CPU allocation, memory, and VPC connectivity:

    Console

    1. In the Google Cloud console, go to the Cloud Run page:

      Go to Cloud Run

    2. Locate the service you want to update in the services list, and click to open the details of that service.

    3. Click Edit and deploy new revision to display the revision deployment form.

    4. Modify any configuration setting.

    5. Click Deploy and wait for the deployment to finish.

    gcloud

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

      Activate Cloud Shell

      At the bottom of the Google Cloud console, a Cloud 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. To update one or more service configuration setting, use the gcloud beta run services update SERVICE command with the command line flags of the configuration you want to update. Replace SERVICE with the name of the service.

    Re-deploy new source code

    You can modify your function's base image, runtime, and source code using either the Google Cloud console or the gcloud CLI.

    Click the tab for instructions using the tool of your choice.

    Console

    1. In the Google Cloud console, go to the Cloud Run page:

      Go to Cloud Run

    2. Locate the function you want to update in the Services list, and click to open the details of that function.

    3. Navigate to the Source tab, and click Edit Source.

    4. Click Edit runtime and security updates next to Base image, and select a different Runtime or Environment from the list as needed, and click Save.

    5. Modify the Function entry point as needed.

    6. In the Files section, select Add file to create a new file, Rename file to rename a file, or Delete file to delete a file.

    7. In the Code section, modify your source code as needed.

    8. Click Save and Redeploy, and wait for the deployment to finish.

    gcloud

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

      Activate Cloud Shell

      At the bottom of the Google Cloud console, a Cloud 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. Run the following command in the directory that contains the function's source code:

      gcloud beta run deploy FUNCTION \
             --source . \
             --function FUNCTION_ENTRYPOINT \
             --base-image BASE_IMAGE \
             --region REGION
      

      Replace:

      • FUNCTION with the name of the function you want to modify.

      • FUNCTION_ENTRYPOINT with the entry point to your function in your source code.

      • BASE_IMAGE with the base image environment for your function. In most cases, you can specify the runtime ID, for example, nodejs22.

        Alternatively, if you want to use a specific system package in the stack or specify the region where the base image is downloaded from, you can specify one of the following:

        • The full base image path, such as us-central1-docker.pkg.dev/serverless-runtimes/google-22-full/runtimes/nodejs22. This option lets you specify the base image, a specific system package in the stack, and the region where the base image is downloaded from.
        • The alias of the full base image path, such as google-22/nodejs22 or google-22-full/nodejs22. This shorter alias option lets you specify the base image and a specific system package in the stack.

        For more details about base images and the packages included in each image, see Runtime base images.

      • REGION with the Google Cloud region where you want to deploy your function. For example, us-central1.

      Optional flags

      You can configure the following optional flags while modifying your function:

      • Build environment variables flags for specifying environment variables during the build step, such as for configuring build-time specific certificates, or parameters.

      • Worker pool flags for specifying which worker pool to use in VPC Service Controls secured build context.

      • Custom build service accounts flags for specifying an alternative to the default build service account for increased security.

      • Automatic base image updates flag to disable automatic updates. By default, functions have automatic security updates enabled.

    What's next

    After you deploy a new function, you can do the following: