Quickstart: Deploy a Cloud Run functionusing the gcloud CLI
This page shows you how to deploy an HTTPCloud Run function using the gcloud CLI.
Before you begin
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
Install the Google Cloud CLI.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Toinitialize the gcloud CLI, run the following command:
gcloudinit
Create or select a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- Create a project: To create a project, you need the Project Creator role (
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission.Learn how to grant roles.
Create a Google Cloud project:
gcloud projects createPROJECT_ID
Replace
PROJECT_IDwith a name for the Google Cloud project you are creating.Select the Google Cloud project that you created:
gcloud config set projectPROJECT_ID
Replace
PROJECT_IDwith your Google Cloud project name.
If you're using an existing project for this guide,verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.
Verify that billing is enabled for your Google Cloud project.
Enable the Artifact Registry, Cloud Build, Cloud Run Admin API, and Cloud Logging APIs:
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission.Learn how to grant roles.gcloudservicesenableartifactregistry.googleapis.com
cloudbuild.googleapis.com run.googleapis.com logging.googleapis.com Install the Google Cloud CLI.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Toinitialize the gcloud CLI, run the following command:
gcloudinit
Create or select a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- Create a project: To create a project, you need the Project Creator role (
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission.Learn how to grant roles.
Create a Google Cloud project:
gcloud projects createPROJECT_ID
Replace
PROJECT_IDwith a name for the Google Cloud project you are creating.Select the Google Cloud project that you created:
gcloud config set projectPROJECT_ID
Replace
PROJECT_IDwith your Google Cloud project name.
If you're using an existing project for this guide,verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.
Verify that billing is enabled for your Google Cloud project.
Enable the Artifact Registry, Cloud Build, Cloud Run Admin API, and Cloud Logging APIs:
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission.Learn how to grant roles.gcloudservicesenableartifactregistry.googleapis.com
cloudbuild.googleapis.com run.googleapis.com logging.googleapis.com - To set the default project for your Cloud Run service:
ReplacePROJECT_ID with the name of the project you created for this quickstart.gcloudconfigsetprojectPROJECT_ID 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.
- ReviewCloud Run pricing or estimate costswith thepricing calculator.
Required roles
To get the permissions that you need to complete this quickstart, ask your administrator to grant you the following IAM roles:
- Cloud Run Source Developer (
roles/run.sourceDeveloper) on the project - Service Account User (
roles/iam.serviceAccountUser) on the service identity - Logs Viewer (
roles/logging.viewer) on the project
For more information about granting roles, seeManage access to projects, folders, and organizations.
You might also be able to get the required permissions throughcustom roles or otherpredefined roles.
Grant the Cloud Build service account access to your project
Cloud Build automatically uses theCompute Engine defaultservice account as the defaultCloud Build service account to build your source code andCloud Run resource, unless you override this behavior.
For Cloud Build to build your sources, grant the Cloud Build serviceaccount theCloud RunBuilder(roles/run.builder) role on your project:
gcloudprojectsadd-iam-policy-bindingPROJECT_ID\--member=serviceAccount:SERVICE_ACCOUNT_EMAIL_ADDRESS\--role=roles/run.builder
ReplacePROJECT_ID with your Google Cloudproject ID andSERVICE_ACCOUNT_EMAIL_ADDRESS with theemail address of the Cloud Build service account. If you're using theCompute Engine default service account as the Cloud Build service account, thenuse the following format for the service account email address:
PROJECT_NUMBER-compute@developer.gserviceaccount.com
ReplacePROJECT_NUMBER with your Google Cloudproject number.
For detailed instructions on how to find your project ID, and project number,seeCreatingand managing projects.
Granting the Cloud Run builder role takes a couple of minutes topropagate.
Write the sample function
To write an application, follow these steps:
Node.js
Create a new directory named
helloworldand change directory into it:mkdir helloworld cd helloworldCreate a
package.jsonfile in thehelloworlddirectory to specifyNode.js dependencies:{"name":"nodejs-docs-samples-functions-hello-world-get","version":"0.0.1","private":true,"license":"Apache-2.0","author":"Google Inc.","repository":{"type":"git","url":"https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git"},"engines":{"node":">=16.0.0"},"scripts":{"test":"c8 mocha -p -j 2 test/*.test.js --timeout=6000 --exit"},"dependencies":{"@google-cloud/functions-framework":"^3.1.0"},"devDependencies":{"c8":"^10.0.0","gaxios":"^6.0.0","mocha":"^10.0.0","wait-port":"^1.0.4"}}Create an
index.jsfile in thehelloworlddirectory with the followingNode.js sample:constfunctions=require('@google-cloud/functions-framework');// Register an HTTP function with the Functions Framework that will be executed// when you make an HTTP request to the deployed function's endpoint.functions.http('helloGET',(req,res)=>{res.send('Hello World!');});
Python
Create a new directory named
helloworldand change directory into it:mkdir helloworld cd helloworldCreate a
requirements.txtfile in thehelloworlddirectory, to specifyPython dependencies:functions-framework==3.9.2flask==3.0.3google-cloud-error-reporting==1.11.1MarkupSafe==2.1.3This adds packages needed by the sample.
Create a
main.pyfile in thehelloworlddirectory with the followingPython sample:importfunctions_framework@functions_framework.httpdefhello_get(request):"""HTTP Cloud Function. Args: request (flask.Request): The request object. <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data> Returns: The response text, or any set of values that can be turned into a Response object using `make_response` <https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>. Note: For more information on how Flask integrates with Cloud Functions, see the `Writing HTTP functions` page. <https://cloud.google.com/functions/docs/writing/http#http_frameworks> """return"Hello World!"
Go
Create a new directory named
helloworldand change directory into it:mkdir helloworld cd helloworldCreate a
go.modfile to declare thego module:modulegithub.com/GoogleCloudPlatform/golang-samples/functions/functionsv2/helloworldgo1.24.0requiregithub.com/GoogleCloudPlatform/functions-framework-gov1.8.1require(github.com/cloudevents/sdk-go/v2v2.15.2// indirectgithub.com/google/go-cmpv0.6.0// indirectgithub.com/google/uuidv1.6.0// indirectgithub.com/json-iterator/gov1.1.12// indirectgithub.com/modern-go/concurrentv0.0.0-20180306012644-bacd9c7ef1dd// indirectgithub.com/modern-go/reflect2v1.0.2// indirectgithub.com/stretchr/testifyv1.10.0// indirectgo.uber.org/multierrv1.11.0// indirectgo.uber.org/zapv1.27.0// indirectgolang.org/x/timev0.9.0// indirect)Create an
hello_http.gofile in thehelloworlddirectory with thefollowing Go code sample:// Package helloworld provides a set of Cloud Functions samples.packagehelloworldimport("fmt""net/http""github.com/GoogleCloudPlatform/functions-framework-go/functions")funcinit(){functions.HTTP("HelloGet",helloGet)}// helloGet is an HTTP Cloud Function.funchelloGet(whttp.ResponseWriter,r*http.Request){fmt.Fprint(w,"Hello, World!")}
Java
Create a new directory named
helloworldand change directory into it:mkdir helloworld cd helloworldCreate the following project structure to contain the source directoryand source file:
mkdir -p ~/helloworld/src/main/java/functionstouch ~/helloworld/src/main/java/functions/HelloWorld.javaUpdate the
HelloWorld.javafile with the following Java code sample:packagefunctions;importcom.google.cloud.functions.HttpFunction;importcom.google.cloud.functions.HttpRequest;importcom.google.cloud.functions.HttpResponse;importjava.io.BufferedWriter;importjava.io.IOException;publicclassHelloWorldimplementsHttpFunction{// Simple function to return "Hello World"@Overridepublicvoidservice(HttpRequestrequest,HttpResponseresponse)throwsIOException{BufferedWriterwriter=response.getWriter();writer.write("Hello World!");}}Create a
pom.xmlfile in thehelloworlddirectory, and add the followingJava dependencies:<?xmlversion="1.0"encoding="UTF-8"?><!--Copyright2020GoogleLLCLicensedundertheApacheLicense,Version2.0(the"License");youmaynotusethisfileexceptincompliancewiththeLicense.YoumayobtainacopyoftheLicenseathttp://www.apache.org/licenses/LICENSE-2.0Unlessrequiredbyapplicablelaworagreedtoinwriting,softwaredistributedundertheLicenseisdistributedonan"AS IS"BASIS,WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.SeetheLicenseforthespecificlanguagegoverningpermissionsandlimitationsundertheLicense.--><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.example.functions</groupId><artifactId>functions-hello-world</artifactId><version>1.0.0-SNAPSHOT</version><parent><groupId>com.google.cloud.samples</groupId><artifactId>shared-configuration</artifactId><version>1.2.0</version></parent><dependencyManagement><dependencies><dependency><artifactId>libraries-bom</artifactId><groupId>com.google.cloud</groupId><scope>import</scope><type>pom</type><version>26.32.0</version></dependency></dependencies></dependencyManagement><properties><maven.compiler.target>11</maven.compiler.target><maven.compiler.source>11</maven.compiler.source></properties><dependencies><!--RequiredforFunctionprimitives--><dependency><groupId>com.google.cloud.functions</groupId><artifactId>functions-framework-api</artifactId><version>1.1.0</version><scope>provided</scope></dependency><!--Thefollowingdependenciesareonlyrequiredfortesting--><dependency><groupId>com.google.truth</groupId><artifactId>truth</artifactId><version>1.4.0</version><scope>test</scope></dependency><dependency><groupId>com.google.guava</groupId><artifactId>guava-testlib</artifactId><scope>test</scope></dependency><dependency><groupId>org.mockito</groupId><artifactId>mockito-core</artifactId><version>5.10.0</version><scope>test</scope></dependency></dependencies><build><plugins><plugin><!--GoogleCloudFunctionsFrameworkMavenpluginThispluginallowsyoutorunCloudFunctionsJavacodelocally.Usethefollowingterminalcommandtorunagivenfunctionlocally:mvnfunction:run-Drun.functionTarget=your.package.yourFunction--><groupId>com.google.cloud.functions</groupId><artifactId>function-maven-plugin</artifactId><version>0.11.0</version><configuration><functionTarget>functions.HelloWorld</functionTarget></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-surefire-plugin</artifactId><!--version3.0.0-M4doesnotloadJUnit5correctly--><!--seehttps://issues.apache.org/jira/browse/SUREFIRE-1750 --><version>3.2.5</version><configuration><includes><include>**/*Test.java</include></includes><skipTests>${skipTests}</skipTests><reportNameSuffix>sponge_log</reportNameSuffix><trimStackTrace>false</trimStackTrace></configuration></plugin></plugins></build></project>
Ruby
Create a new directory named
helloworldand change directory into it:mkdir helloworld cd helloworldCreate a file named
app.rband paste the following code into it:require"functions_framework"FunctionsFramework.http"hello_get"do|_request|# The request parameter is a Rack::Request object.# See https://www.rubydoc.info/gems/rack/Rack/Request# Return the response body as a string.# You can also return a Rack::Response object, a Rack response array, or# a hash which will be JSON-encoded into a response."Hello World!"endCreate a file named
Gemfileand copy the following into it:source"https://rubygems.org"gem"base64","~> 0.2"gem"functions_framework","~> 1.4"If you don't have Bundler 2.0 or greater installed, installBundler.
Generate a
Gemfile.lockfile by running:bundle install
PHP
Create a new directory named
helloworldand change directory into it:mkdir helloworld cd helloworldCreate a file named
index.phpand paste the following code into it:use Psr\Http\Message\ServerRequestInterface;function helloGet(ServerRequestInterface $request): string{ return 'Hello, World!' . PHP_EOL;}If you aren't using Cloud Shell, create a
composer.jsonfile andpaste the following code into it:{ "require": { "google/cloud-functions-framework": "^1.0" }, "scripts": { "start": [ "Composer\\Config::disableProcessTimeout", "FUNCTION_TARGET=helloGet php -S localhost:${PORT:-8080} vendor/google/cloud-functions-framework/router.php" ] }}
.NET
Install.NET SDK.
From the console, create a new empty web project using the dotnetcommand.
dotnet new web -o helloworld-csharpChange directory to
helloworld-csharp:Replace the sample code in the project file
helloworld-csharp.csprojwith the following:<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net8.0</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Google.Cloud.Functions.Hosting" Version="3.0.1" /> </ItemGroup></Project>Replace the sample code in
Program.csfile with the following:using Google.Cloud.Functions.Framework;using Microsoft.AspNetCore.Http;using System.Threading.Tasks;namespace HelloWorld;public class Function : IHttpFunction{ public async Task HandleAsync(HttpContext context) { await context.Response.WriteAsync("Hello World!", context.RequestAborted); }}
Deploy the function
To deploy your Cloud Run function, follow these steps:
Deploy the function by running the following command in the directory thatcontains the sample code:
Node.js
gcloud run deploy nodejs-http-function \ --source . \ --function helloGET \ --base-image nodejs24 \ --regionREGION \ --allow-unauthenticatedReplaceREGION with the Google Cloudregion of the service where you want to deploy yourfunction. For example,
europe-west1.Python
gcloud run deploy python-http-function \ --source . \ --function hello_get \ --base-image python313 \ --regionREGION \ --allow-unauthenticatedReplaceREGION with the Google Cloudregion of the service where you want to deploy yourfunction. For example,
europe-west1.Go
gcloud run deploy go-http-function \ --source . \ --function HelloGet \ --base-image go125 \ --regionREGION \ --allow-unauthenticatedReplaceREGION with the Google Cloudregion of the service where you want to deploy yourfunction. For example,
europe-west1.Java
Run the following command in the directory that contains the
pom.xmlfile:gcloud run deploy java-http-function \ --source . \ --function functions.HelloWorld \ --base-image java21 \ --regionREGION \ --allow-unauthenticatedReplaceREGION with the Google Cloudregion of the service where you want to deploy yourfunction. For example,
europe-west1.Ruby
gcloud run deploy ruby-http-function \ --source . \ --function hello_get \ --base-image ruby34 \ --regionREGION \ --allow-unauthenticatedReplaceREGION with the Google Cloudregion of the service where you want to deploy yourfunction. For example,
europe-west1.PHP
gcloud run deploy php-http-function \ --source . \ --function helloGet \ --base-image php84 \ --regionREGION \ --allow-unauthenticatedReplaceREGION with the Google Cloudregion of the service where you want to deploy yourfunction. For example,
europe-west1..NET
gcloud run deploy csharp-http-function \ --source . \ --function HelloWorld.Function \ --base-image dotnet8 \ --regionREGION \ --allow-unauthenticatedReplaceREGION with the Google Cloudregion of the service where you want to deploy yourfunction. For example,
europe-west1.When the deployment is complete, the Google Cloud CLI displays a URL wherethe service is running. Open the URL in your browser to see the output ofyour function.
Success: You deployed an HTTP Cloud Run function usingthe gcloud CLI.
Clean up
To avoid additional charges to your Google Cloud account, delete all the resourcesyou deployed with this quickstart.
Delete your repository
Cloud Run doesn't charge you when your deployed service isn't in use.However, you might still becharged for storing the container image inArtifact Registry. To delete Artifact Registry repositories,follow the steps inDeleterepositories in the Artifact Registrydocumentation.
Delete your service
Cloud Run services don't incur costs until they receive requests.To delete your Cloud Run service, follow one of these steps:
Console
To delete a service:
In the Google Cloud console, go to the Cloud RunServices page:
Locate the service you want to delete in the services list, and clickits checkbox to select it.
ClickDelete. This deletes all revisions of the service.
gcloud
To delete a service, run the following command:
gcloud run services deleteSERVICE --regionREGION
Replace the following:
- SERVICE: name of your service.
- REGION: Google Cloud region of the service.
Delete your test project
Deleting your Google Cloud project stops billing for all resources in thatproject. To release all Google Cloud resources in your project, follow these steps:
What's next
To deploy a sample function to Cloud Run using the Google Cloud console,seeQuickstart: Deploy a function to Cloud Run using the Google Cloud console.
To deploy functions and create triggers using the Google Cloud console and theGoogle Cloud CLI, seeDeploy functions.
To view and delete existing functions, seeManage service revisions.
To build function containers in your own toolchain and deploy it toCloud Run, seeBuild functions.
To create triggers with Eventarc, seeCreate triggers with Eventarc.
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.