クイックスタート: gcloud CLI で Cloud Run functions の関数をデプロイする

このページでは、gcloud CLI を使用して Cloud Run functions の HTTP 関数をデプロイする方法について説明します。

始める前に

  1. 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.
  2. Install the Google Cloud CLI.

  3. 外部 ID プロバイダ(IdP)を使用している場合は、まずフェデレーション ID を使用して gcloud CLI にログインする必要があります。

  4. gcloud CLI を初期化するには、次のコマンドを実行します。

    gcloud init
  5. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  6. Verify that billing is enabled for your Google Cloud project.

  7. 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
  8. Grant roles to your user account. Run the following command once for each of the following IAM roles: roles/run.sourceDeveloper, roles/run.admin, roles/logging.viewer

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE

    Replace the following:

    • PROJECT_ID: your project ID.
    • USER_IDENTIFIER: the identifier for your user account—for example, myemail@example.com.
    • ROLE: the IAM role that you grant to your user account.
  9. Install the Google Cloud CLI.

  10. 外部 ID プロバイダ(IdP)を使用している場合は、まずフェデレーション ID を使用して gcloud CLI にログインする必要があります。

  11. gcloud CLI を初期化するには、次のコマンドを実行します。

    gcloud init
  12. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  13. Verify that billing is enabled for your Google Cloud project.

  14. 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
  15. Grant roles to your user account. Run the following command once for each of the following IAM roles: roles/run.sourceDeveloper, roles/run.admin, roles/logging.viewer

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE

    Replace the following:

    • PROJECT_ID: your project ID.
    • USER_IDENTIFIER: the identifier for your user account—for example, myemail@example.com.
    • ROLE: the IAM role that you grant to your user account.
  16. 次のコマンドを実行して、Cloud Run サービスのデフォルト プロジェクトを設定します。
     gcloud config set project PROJECT_ID
    PROJECT_ID は、このクイックスタートで作成したプロジェクトの名前に置き換えます。
  17. ドメイン制限の組織のポリシーでプロジェクトの未認証呼び出しが制限されている場合は、限定公開サービスのテストの説明に従って、デプロイされたサービスにアクセスする必要があります。

  18. サービス ID にサービス アカウント ユーザーのロールが付与されていることを確認します。デフォルトでは、サービス ID は Compute Engine のデフォルトのサービス アカウントです。

    ロールを付与する

    サービス ID リソースに対するアクセス権を付与するには、gcloud iam service-accounts add-iam-policy-binding コマンドを使用します。ハイライト表示された変数は、適切な値に置き換えてください。

          gcloud iam service-accounts add-iam-policy-binding SERVICE_ACCOUNT_EMAIL \
              --member="PRINCIPAL" \
              --role="roles/iam.serviceAccountUser"
          

    次のように置き換えます。

    • SERVICE_ACCOUNT_EMAIL: サービス ID として使用しているサービス アカウントのメールアドレス。たとえば次のようなものです。
      • Compute Engine のデフォルトのサービス アカウント: PROJECT_NUMBER-compute@developer.gserviceaccount.com
      • 作成したサービス アカウント: SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com
    • PRINCIPAL: ユーザー ID。通常は、Google アカウントのメールアドレスです。
  19. Cloud Build サービス アカウントに次の IAM ロールを付与します。

    ここをクリックして Cloud Build サービス アカウントに必要なロールを表示

    この動作をオーバーライドしない限り、Cloud Build は、ソースコードと Cloud Run リソースのビルドにデフォルトの Cloud Build サービス アカウントとして Compute Engine のデフォルトのサービス アカウントを自動的に使用します。Cloud Build がソースをビルドできるようにするには、プロジェクトの Compute Engine のデフォルトのサービス アカウントに Cloud Run ビルダーroles/run.builder)を付与するよう管理者に依頼します。

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

    PROJECT_NUMBER は Google Cloudプロジェクト番号に、PROJECT_ID は Google Cloudプロジェクト ID に置き換えます。プロジェクト ID とプロジェクト番号を確認する方法については、プロジェクトの作成と管理をご覧ください。

    Compute Engine のデフォルト サービス アカウントに Cloud Run ビルダーのロールを付与すると、反映されるまでに数分かかることがあります。

  20. Cloud Run の料金を確認するか、料金計算ツールで費用を見積もります。
  21. サンプル関数を作成する

    アプリケーションを作成するには、次の操作を行います。

    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. 次の Node.js サンプルを使用して、helloworld ディレクトリに index.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. Python の依存関係を指定するために、helloworld ディレクトリに requirements.txt ファイルを作成します。

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

      これにより、サンプルで必要なパッケージが追加されます。

    3. helloworld ディレクトリに、次の Python サンプルを含む main.py ファイルを作成します。

      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.23.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 ディレクトリに、次の Go コードサンプルを含む hello_http.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 コマンドを使用して、新しい空のウェブ プロジェクトを作成します。

      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 ソース デベロッパー ロールで、ソースから Cloud Run リソースをデプロイするために必要な権限を確認してください。

    Cloud Run 関数をデプロイするには、次の操作を行います。

    1. サンプルコードを含むディレクトリで次のコマンドを実行して、関数をデプロイします。

      Node.js

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

      REGION は、関数をデプロイするサービスの Google Cloudリージョンに置き換えます。例: europe-west1

      Python

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

      REGION は、関数をデプロイするサービスの Google Cloudリージョンに置き換えます。例: europe-west1

      Go

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

      REGION は、関数をデプロイするサービスの Google Cloudリージョンに置き換えます。例: europe-west1

      Java

      pom.xml ファイルが含まれるディレクトリで、次のコマンドを実行します。

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

      REGION は、関数をデプロイするサービスの Google Cloudリージョンに置き換えます。例: europe-west1

      Ruby

      gcloud run deploy ruby-http-function \
             --source . \
             --function hello_get \
             --base-image ruby34 \
             --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 dotnet8 \
            --region REGION \
            --allow-unauthenticated
      

      REGION は、関数をデプロイするサービスの Google Cloudリージョンに置き換えます。例: europe-west1

    2. デプロイが完了すると、サービスが実行されている URL が Google Cloud CLI に表示されます。ブラウザで URL を開き、関数の出力を確認します。

    クリーンアップ

    Google Cloud アカウントで追加料金が発生しないようにするには、このクイックスタートでデプロイしたすべてのリソースを削除します。

    リポジトリを削除する

    デプロイされたサービスが使用されていない場合、Cloud Run の料金は発生しません。ただし、コンテナ イメージを Artifact Registry に保存した場合にも料金が発生する可能性があります。Artifact Registry リポジトリを削除するには、Artifact Registry ドキュメントのリポジトリを削除するの手順を行います。

    サービスを削除する

    Cloud Run サービスの費用は、リクエストを受け取るまでは発生しません。Cloud Run サービスを削除するには、次のいずれかの操作を行います。

    コンソール

    サービスを削除するには:

    1. Google Cloud コンソールで Cloud Run に移動します。

      Cloud Run に移動

    2. 削除するサービスをサービスリストで探し、そのチェックボックスをクリックして選択します。

    3. [削除] をクリックします。これにより、サービスのすべてのリビジョンが削除されます。

    gcloud

    サービスを削除するには、次のコマンドを実行します。

    gcloud run services delete SERVICE --region REGION

    次のように置き換えます。

    • SERVICE: サービスの名前。
    • REGION: サービスの Google Cloud リージョン。

    テスト プロジェクトを削除する

    Google Cloud プロジェクトを削除すると、そのプロジェクト内のすべてのリソースに対する課金が停止します。プロジェクト内のすべての Google Cloud リソースを解放する手順は次のとおりです。

      Delete a Google Cloud project:

      gcloud projects delete PROJECT_ID

    次のステップ