快速入門:使用 gcloud CLI 部署 Cloud Run 函式

本頁說明如何使用 gcloud CLI 部署 HTTP Cloud Run 函式。

事前準備

  1. 登入 Google Cloud 帳戶。如果您是 Google Cloud新手,歡迎 建立帳戶,親自評估產品在實際工作環境中的成效。新客戶還能獲得價值 $300 美元的免費抵免額,可用於執行、測試及部署工作負載。
  2. 安裝 Google Cloud CLI。

  3. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI

  4. 執行下列指令,初始化 gcloud CLI:

    gcloud init
  5. 建立或選取 Google Cloud 專案

    選取或建立專案所需的角色

    • 選取專案:選取專案時,不需要具備特定 IAM 角色,只要您已獲授角色,即可選取任何專案。
    • 建立專案:如要建立專案,您需要具備專案建立者角色 (roles/resourcemanager.projectCreator),其中包含 resourcemanager.projects.create 權限。瞭解如何授予角色
    • 建立 Google Cloud 專案:

      gcloud projects create PROJECT_ID

      PROJECT_ID 替換為您要建立的 Google Cloud 專案名稱。

    • 選取您建立的 Google Cloud 專案:

      gcloud config set project PROJECT_ID

      PROJECT_ID 替換為 Google Cloud 專案名稱。

  6. 如要使用現有專案進行本指南中的操作,請確認您具有完成本指南所需的權限。如果您建立新專案,則已具備必要權限。

  7. 確認專案已啟用計費功能 Google Cloud

  8. 啟用 Artifact Registry、Cloud Build、Cloud Run Admin API 和 Cloud Logging API:

    啟用 API 時所需的角色

    如要啟用 API,您需要具備服務使用情形管理員 IAM 角色 (roles/serviceusage.serviceUsageAdmin),其中包含 serviceusage.services.enable 權限。瞭解如何授予角色

    gcloud services enable artifactregistry.googleapis.com cloudbuild.googleapis.com run.googleapis.com logging.googleapis.com
  9. 安裝 Google Cloud CLI。

  10. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI

  11. 執行下列指令,初始化 gcloud CLI:

    gcloud init
  12. 建立或選取 Google Cloud 專案

    選取或建立專案所需的角色

    • 選取專案:選取專案時,不需要具備特定 IAM 角色,只要您已獲授角色,即可選取任何專案。
    • 建立專案:如要建立專案,您需要具備專案建立者角色 (roles/resourcemanager.projectCreator),其中包含 resourcemanager.projects.create 權限。瞭解如何授予角色
    • 建立 Google Cloud 專案:

      gcloud projects create PROJECT_ID

      PROJECT_ID 替換為您要建立的 Google Cloud 專案名稱。

    • 選取您建立的 Google Cloud 專案:

      gcloud config set project PROJECT_ID

      PROJECT_ID 替換為 Google Cloud 專案名稱。

  13. 如要使用現有專案進行本指南中的操作,請確認您具有完成本指南所需的權限。如果您建立新專案,則已具備必要權限。

  14. 確認專案已啟用計費功能 Google Cloud

  15. 啟用 Artifact Registry、Cloud Build、Cloud Run Admin API 和 Cloud Logging API:

    啟用 API 時所需的角色

    如要啟用 API,您需要具備服務使用情形管理員 IAM 角色 (roles/serviceusage.serviceUsageAdmin),其中包含 serviceusage.services.enable 權限。瞭解如何授予角色

    gcloud services enable artifactregistry.googleapis.com cloudbuild.googleapis.com run.googleapis.com logging.googleapis.com
  16. 如要為 Cloud Run 服務設定預設專案:
     gcloud config set project PROJECT_ID
    PROJECT_ID 替換為您為本快速入門導覽課程建立的專案名稱。
  17. 如果專案受限於網域限制組織政策,禁止未經驗證的叫用,您必須按照「測試私人服務」一節的說明存取已部署的服務。

  18. 查看 Cloud Run 定價,或使用 Pricing Calculator 估算費用。

必要的角色

如要取得完成本快速入門導覽課程所需的權限,請要求管理員授予您下列 IAM 角色:

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

您或許也能透過自訂角色或其他預先定義的角色,取得必要權限。

授予 Cloud Build 服務帳戶專案存取權

除非您覆寫這項行為,否則 Cloud Build 會自動使用 Compute Engine 預設服務帳戶做為預設的 Cloud Build 服務帳戶,建構您的原始碼和 Cloud Run 資源。

如要讓 Cloud Build 建構來源,請將專案的 Cloud Run 建構工具 (roles/run.builder) 角色授予 Cloud Build 服務帳戶:

gcloud projects add-iam-policy-binding PROJECT_ID \
    --member=serviceAccount:SERVICE_ACCOUNT_EMAIL_ADDRESS \
    --role=roles/run.builder

PROJECT_ID 替換為您的 Google Cloud專案 ID,並將 SERVICE_ACCOUNT_EMAIL_ADDRESS 替換為 Cloud Build 服務帳戶的電子郵件地址。如果您使用 Compute Engine 預設服務帳戶做為 Cloud Build 服務帳戶,請使用下列格式的服務帳戶電子郵件地址:

PROJECT_NUMBER-compute@developer.gserviceaccount.com

PROJECT_NUMBER 替換為您的 Google Cloud專案編號。

如需如何找出專案 ID 和專案編號的詳細操作說明,請參閱「建立及管理專案」。

授予 Cloud Run 建構人員角色後,需要幾分鐘才能傳播

編寫範例函式

如要撰寫申請書,請按照下列步驟操作:

Node.js

  1. 建立一個新目錄並命名為 helloworld,然後將目錄變更為該目錄:

       mkdir helloworld
       cd helloworld
    

  2. helloworld 目錄中建立 package.json 檔案,指定 Node.js 依附元件:

    {
      "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"
      }
    }
    
  3. helloworld 目錄中建立 index.js 檔案,並加入下列 Node.js 範例:

    const functions = 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

  1. 建立一個新目錄並命名為 helloworld,然後將目錄變更為該目錄:

       mkdir helloworld
       cd helloworld
    

  2. helloworld 目錄中建立 requirements.txt 檔案,指定 Python 依附元件:

    functions-framework==3.9.2
    flask==3.0.3
    google-cloud-error-reporting==1.11.1
    MarkupSafe==2.1.3
    

    這會新增範例所需的套件。

  3. helloworld 目錄中建立 main.py 檔案,並加入下列 Python 範例:

    import functions_framework
    
    @functions_framework.http
    def hello_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

  1. 建立一個新目錄並命名為 helloworld,然後將目錄變更為該目錄:

       mkdir helloworld
       cd helloworld
    

  2. 建立 go.mod 檔案來宣告 Go 模組

    module github.com/GoogleCloudPlatform/golang-samples/functions/functionsv2/helloworld
    
    go 1.25.0
    
    require github.com/GoogleCloudPlatform/functions-framework-go v1.8.1
    
    require (
    	github.com/cloudevents/sdk-go/v2 v2.15.2 // indirect
    	github.com/google/go-cmp v0.6.0 // indirect
    	github.com/google/uuid v1.6.0 // indirect
    	github.com/json-iterator/go v1.1.12 // indirect
    	github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
    	github.com/modern-go/reflect2 v1.0.2 // indirect
    	github.com/stretchr/testify v1.10.0 // indirect
    	go.uber.org/multierr v1.11.0 // indirect
    	go.uber.org/zap v1.27.0 // indirect
    	golang.org/x/time v0.9.0 // indirect
    )
    
  3. helloworld 目錄中建立 hello_http.go 檔案,並加入以下 Go 程式碼範例:

    
    // Package helloworld provides a set of Cloud Functions samples.
    package helloworld
    
    import (
    	"fmt"
    	"net/http"
    
    	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
    )
    
    func init() {
    	functions.HTTP("HelloGet", helloGet)
    }
    
    // helloGet is an HTTP Cloud Function.
    func helloGet(w http.ResponseWriter, r *http.Request) {
    	fmt.Fprint(w, "Hello, World!")
    }
    

Java

  1. 建立一個新目錄並命名為 helloworld,然後將目錄變更為該目錄:

       mkdir helloworld
       cd helloworld
    

  2. 建立下列專案結構,內含來源目錄和來源檔案:

    mkdir -p ~/helloworld/src/main/java/functions
    touch ~/helloworld/src/main/java/functions/HelloWorld.java
    
  3. 使用下列 Java 程式碼範例更新 HelloWorld.java 檔案:

    
    package functions;
    
    import com.google.cloud.functions.HttpFunction;
    import com.google.cloud.functions.HttpRequest;
    import com.google.cloud.functions.HttpResponse;
    import java.io.BufferedWriter;
    import java.io.IOException;
    
    public class HelloWorld implements HttpFunction {
      // Simple function to return "Hello World"
      @Override
      public void service(HttpRequest request, HttpResponse response)
          throws IOException {
        BufferedWriter writer = response.getWriter();
        writer.write("Hello World!");
      }
    }
  4. helloworld 目錄中建立 pom.xml 檔案,並新增下列 Java 依附元件:

    <?xml version="1.0" encoding="UTF-8"?>
    
    <!--
      Copyright 2020 Google LLC
    
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at
    
      http://www.apache.org/licenses/LICENSE-2.0
    
      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.
    -->
    
    <project xmlns="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>
        <!-- Required for Function primitives -->
        <dependency>
          <groupId>com.google.cloud.functions</groupId>
          <artifactId>functions-framework-api</artifactId>
          <version>1.1.0</version>
          <scope>provided</scope>
        </dependency>
    
        <!-- The following dependencies are only required for testing -->
        <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>
            <!--
              Google Cloud Functions Framework Maven plugin
    
              This plugin allows you to run Cloud Functions Java code
              locally. Use the following terminal command to run a
              given function locally:
    
              mvn function: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>
            <!-- version 3.0.0-M4 does not load JUnit5 correctly -->
            <!-- see https://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

  1. 建立一個新目錄並命名為 helloworld,然後將目錄變更為該目錄:

       mkdir helloworld
       cd helloworld
    

  2. 建立名為 app.rb 的檔案,將下列程式碼貼入其中:

    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!"
    end
  3. 建立一個檔案並命名為 Gemfile,然後將下列內容複製到檔案中:

    source "https://rubygems.org"
    
    gem "base64", "~> 0.2"
    gem "functions_framework", "~> 1.4"
  4. 如果尚未安裝 Bundler 2.0 以上版本,請安裝 Bundler

  5. 執行下列指令來產生 Gemfile.lock 檔案:

    bundle install
    

PHP

  1. 建立一個新目錄並命名為 helloworld,然後將目錄變更為該目錄:

       mkdir helloworld
       cd helloworld
    

  2. 建立名為 index.php 的檔案,將下列程式碼貼入其中:

    
    use Psr\Http\Message\ServerRequestInterface;
    
    function helloGet(ServerRequestInterface $request): string
    {
        return 'Hello, World!' . PHP_EOL;
    }
    
  3. 如果您未使用 Cloud Shell,請建立 composer.json 檔案,然後將下列程式碼貼入該檔案:

    {
        "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

  1. 安裝 .NET SDK

  2. 在主控台中,使用 dotnet 指令建立新的空白 Web 專案。

    dotnet new web -o helloworld-csharp
    
  3. 將目錄變更為 helloworld-csharp

  4. 將專案檔案 helloworld-csharp.csproj 中的程式碼範例替換成下列程式碼:

    <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>
  5. Program.cs 檔案中的程式碼範例替換為下列程式碼:

    
    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);
        }
    }

部署函式

如要部署 Cloud Run 函式,請按照下列步驟操作:

  1. 如要部署函式,請在包含程式碼範例的目錄中執行下列指令:

    Node.js

    gcloud run deploy nodejs-http-function \
          --source . \
          --function helloGET \
          --base-image nodejs24 \
          --region REGION \
          --allow-unauthenticated
    

    REGION 替換為要部署函式的服務 Google Cloud 區域。例如:europe-west1

    Python

    gcloud run deploy python-http-function \
          --source . \
          --function hello_get \
          --base-image python314 \
          --region REGION \
          --allow-unauthenticated
    

    REGION 替換為要部署函式的服務 Google Cloud 區域。例如:europe-west1

    Go

    gcloud run deploy go-http-function \
           --source . \
           --function HelloGet \
           --base-image go126 \
           --region REGION \
           --allow-unauthenticated
    

    REGION 替換為要部署函式的服務 Google Cloud 區域。例如:europe-west1

    Java

    在包含 pom.xml 檔案的目錄中執行下列指令:

    gcloud run deploy java-http-function \
           --source . \
           --function functions.HelloWorld \
           --base-image java25 \
           --region REGION \
           --allow-unauthenticated
    

    REGION 替換為要部署函式的服務 Google Cloud 區域。例如:europe-west1

    Ruby

    gcloud run deploy ruby-http-function \
           --source . \
           --function hello_get \
           --base-image ruby40 \
           --region REGION \
           --allow-unauthenticated
    

    REGION 替換為要部署函式的服務 Google Cloud 區域。例如:europe-west1

    PHP

    gcloud run deploy php-http-function \
           --source . \
           --function helloGet \
           --base-image php84 \
           --region REGION \
           --allow-unauthenticated
    

    REGION 替換為要部署函式的服務 Google Cloud 區域。例如:europe-west1

    .NET

    gcloud run deploy csharp-http-function \
          --source . \
          --function HelloWorld.Function \
          --base-image dotnet10 \
          --region REGION \
          --allow-unauthenticated
    

    REGION 替換為要部署函式的服務 Google Cloud 區域。例如:europe-west1

  2. 部署完成後,Google Cloud CLI 會顯示服務執行的網址。在瀏覽器中開啟網址,即可查看函式的輸出內容。

清除所用資源

為避免系統向您的 Google Cloud 帳戶收取額外費用,請刪除您透過本快速入門導覽課程部署的所有資源。

刪除存放區

部署的服務閒置時,Cloud Run 不會向您收費。 不過,您可能仍須支付在 Artifact Registry 中儲存容器映像檔的費用。如要刪除 Artifact Registry 存放區,請按照 Artifact Registry 說明文件中的「刪除存放區」一節操作。

刪除服務

Cloud Run 服務收到要求後才會產生費用。如要刪除 Cloud Run 服務,請按照下列步驟操作:

控制台

如要刪除服務:

  1. 前往 Google Cloud 控制台的 Cloud Run「Services」(服務) 頁面:

    前往 Cloud Run

  2. 在服務清單中找出您要刪除的服務,然後按一下核取方塊來選取。

  3. 按一下「Delete」(刪除)。如此便會刪除服務的所有修訂版本。

gcloud

如要刪除服務,請執行下列指令:

gcloud run services delete SERVICE --region REGION

更改下列內容:

  • SERVICE:服務名稱。
  • REGION:服務的 Google Cloud 區域。

刪除測試專案

刪除 Google Cloud 專案後,系統就會停止對該專案中的所有資源收取費用。如要釋出專案中的所有 Google Cloud 資源,請按照下列步驟操作:

    刪除 Google Cloud 專案:

    gcloud projects delete PROJECT_ID

後續步驟