Kurzanleitung: Cloud Run-Funktion mit der gcloud CLI bereitstellen

Auf dieser Seite wird gezeigt, wie Sie eine HTTP-Cloud Run-Funktion mit der gcloud CLI bereitstellen.

Hinweise

  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. Wenn Sie einen externen Identitätsanbieter (IdP) verwenden, müssen Sie sich zuerst mit Ihrer föderierten Identität in der gcloud CLI anmelden.

  4. Führen Sie folgenden Befehl aus, um die gcloud CLI zu initialisieren:

    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, [email protected].
    • ROLE: the IAM role that you grant to your user account.
  9. Install the Google Cloud CLI.

  10. Wenn Sie einen externen Identitätsanbieter (IdP) verwenden, müssen Sie sich zuerst mit Ihrer föderierten Identität in der gcloud CLI anmelden.

  11. Führen Sie folgenden Befehl aus, um die gcloud CLI zu initialisieren:

    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, [email protected].
    • ROLE: the IAM role that you grant to your user account.
  16. So legen Sie das Standardprojekt für Ihren Cloud Run-Dienst fest:
     gcloud config set project PROJECT_ID
    Ersetzen Sie PROJECT_ID durch den Namen des Projekts, das Sie für diese Kurzanleitung erstellt haben.
  17. Wenn Sie einer Domaineinschränkung zur Organisation nicht eingeschränkter Aufrufe für Ihr Projekt unterliegen, müssen Sie auf Ihren bereitgestellten Dienst zugreifen, wie unter Private Dienste testen beschrieben.

  18. Achten Sie darauf, dass Sie die Rolle „Dienstkontonutzer“ für die Dienstidentität haben. Standardmäßig ist die Dienstidentität das Compute Engine-Standarddienstkonto.

    Rollen zuweisen

    Verwenden Sie den Befehl gcloud iam service-accounts add-iam-policy-binding, um Zugriff auf die Dienstidentitätsressource zu gewähren. Ersetzen Sie dabei die markierten Variablen durch die entsprechenden Werte:

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

    Ersetzen Sie Folgendes:

    • SERVICE_ACCOUNT_EMAIL: Die E-Mail-Adresse des Dienstkontos, das Sie als Dienstidentität verwenden, z. B.:
      • Das Compute Engine-Standarddienstkonto: PROJECT_NUMBER[email protected]
      • Ein von Ihnen erstelltes Dienstkonto: SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com
    • PRINCIPAL: die Nutzer-ID. Dies ist in der Regel die E‑Mail-Adresse eines Google-Kontos.
  19. Weisen Sie dem Cloud Build-Dienstkonto die folgende IAM-Rolle zu.

    Klicken, um die erforderlichen Rollen für das Cloud Build-Dienstkonto aufzurufen

    Cloud Build verwendet automatisch das Compute Engine-Standarddienstkonto als Standard-Cloud Build-Dienstkonto zum Erstellen Ihres Quellcodes und Ihrer Cloud Run-Ressource, sofern Sie dieses Verhalten nicht überschreiben. Damit Cloud Build Ihre Quellen erstellen kann, bitten Sie Ihren Administrator, dem Compute Engine-Standarddienstkonto in Ihrem Projekt die Rolle Cloud Run Builder (roles/run.builder) zuzuweisen:

      gcloud projects add-iam-policy-binding PROJECT_ID \
          --member=serviceAccount:PROJECT_NUMBER[email protected] \
          --role=roles/run.builder
      

    Ersetzen Sie PROJECT_NUMBER durch die Google CloudProjektnummer und PROJECT_ID durch die Google CloudProjekt-ID. Eine detaillierte Anleitung zum Ermitteln der Projekt-ID und der Projektnummer finden Sie unter Projekte erstellen und verwalten.

    Es dauert einige Minuten, bis die Zuweisung der Rolle „Cloud Run-Builder“ für das Compute Engine-Standarddienstkonto übertragen wurde.

  20. Beispielfunktion schreiben

    So schreiben Sie eine Bewerbung:

    Node.js

    1. Erstellen Sie ein neues Verzeichnis mit dem Namen helloworld und ersetzen Sie das aktuelle Verzeichnis durch dieses Verzeichnis:

         mkdir helloworld
         cd helloworld
      

    2. Erstellen Sie im Verzeichnis helloworld eine package.json-Datei, um Node.js-Abhängigkeiten anzugeben:

      {
        "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. Erstellen Sie im Verzeichnis helloworld eine index.js-Datei mit dem folgenden Node.js-Beispiel:

      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. Erstellen Sie ein neues Verzeichnis mit dem Namen helloworld und ersetzen Sie das aktuelle Verzeichnis durch dieses Verzeichnis:

         mkdir helloworld
         cd helloworld
      

    2. Erstellen Sie im Verzeichnis helloworld eine requirements.txt-Datei, um Python-Abhängigkeiten anzugeben:

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

      Dadurch werden für das Beispiel erforderliche Pakete hinzugefügt.

    3. Erstellen Sie im Verzeichnis helloworld eine main.py-Datei mit dem folgenden Python-Beispiel:

      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. Erstellen Sie ein neues Verzeichnis mit dem Namen helloworld und ersetzen Sie das aktuelle Verzeichnis durch dieses Verzeichnis:

         mkdir helloworld
         cd helloworld
      

    2. Erstellen Sie eine go.mod-Datei, um das Go-Modul zu deklarieren:

      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. Erstellen Sie im Verzeichnis helloworld eine hello_http.go-Datei mit dem folgenden Go-Codebeispiel:

      
      // 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. Erstellen Sie ein neues Verzeichnis mit dem Namen helloworld und ersetzen Sie das aktuelle Verzeichnis durch dieses Verzeichnis:

         mkdir helloworld
         cd helloworld
      

    2. Erstellen Sie die folgende Projektstruktur, die das Quellverzeichnis und die Quelldatei enthält.

      mkdir -p ~/helloworld/src/main/java/functions
      touch ~/helloworld/src/main/java/functions/HelloWorld.java
      
    3. Aktualisieren Sie die Datei HelloWorld.java mit dem folgenden Java-Codebeispiel:

      
      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. Erstellen Sie im Verzeichnis helloworld eine pom.xml-Datei und fügen Sie die folgenden Java-Abhängigkeiten hinzu:

      <?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. Erstellen Sie ein neues Verzeichnis mit dem Namen helloworld und ersetzen Sie das aktuelle Verzeichnis durch dieses Verzeichnis:

         mkdir helloworld
         cd helloworld
      

    2. Erstellen Sie eine Datei mit dem Namen app.rb und fügen Sie den folgenden Code in diese ein:

      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. Erstellen Sie eine Datei namens Gemfile und kopieren Sie Folgendes hinein:

      source "https://rubygems.org"
      
      gem "base64", "~> 0.2"
      gem "functions_framework", "~> 1.4"
    4. Wenn Bundler 2.0 oder höher nicht installiert ist, installieren Sie Bundler.

    5. Erstellen Sie mit diesem Befehl eine Gemfile.lock-Datei:

      bundle install
      

    PHP

    1. Erstellen Sie ein neues Verzeichnis mit dem Namen helloworld und ersetzen Sie das aktuelle Verzeichnis durch dieses Verzeichnis:

         mkdir helloworld
         cd helloworld
      

    2. Erstellen Sie eine Datei mit dem Namen index.php und fügen Sie den folgenden Code in diese ein:

      
      use Psr\Http\Message\ServerRequestInterface;
      
      function helloGet(ServerRequestInterface $request): string
      {
          return 'Hello, World!' . PHP_EOL;
      }
      
    3. Wenn Sie Cloud Shell nicht verwenden, erstellen Sie eine composer.json-Datei und fügen Sie den folgenden Code ein:

      {
          "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. Installieren Sie das .NET SDK.

    2. Erstellen Sie über die Konsole mit dem Befehl "dotnet" ein neues, leeres Webprojekt.

      dotnet new web -o helloworld-csharp
      
    3. Ändern Sie das Verzeichnis in helloworld-csharp:

    4. Ersetzen Sie den Beispielcode in der Projektdatei helloworld-csharp.csproj durch Folgendes:

      <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. Ersetzen Sie den Beispielcode in der Datei Program.cs durch Folgendes:

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

    Funktion implementieren

    Wichtig: In dieser Kurzanleitung wird davon ausgegangen, dass Sie Inhaber- oder Bearbeiterrollen in dem Projekt haben, das Sie für die Kurzanleitung verwenden. Andernfalls finden Sie die erforderlichen Berechtigungen für die Bereitstellung einer Cloud Run-Ressource aus der Quelle unter Rolle „Cloud Run-Quellenentwickler“.

    So stellen Sie Ihre Cloud Run-Funktion bereit:

    1. Stellen Sie die Funktion bereit, indem Sie den folgenden Befehl in dem Verzeichnis ausführen, das den Beispielcode enthält:

      Node.js

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

      Ersetzen Sie REGION durch die Google Cloud Region des Dienstes, in der Sie die Funktion bereitstellen möchten. Beispiel: europe-west1

      Python

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

      Ersetzen Sie REGION durch die Google Cloud Region des Dienstes, in der Sie die Funktion bereitstellen möchten. Beispiel: europe-west1

      Go

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

      Ersetzen Sie REGION durch die Google Cloud Region des Dienstes, in der Sie die Funktion bereitstellen möchten. Beispiel: europe-west1

      Java

      Führen Sie den folgenden Befehl in dem Verzeichnis aus, das die Datei pom.xml enthält:

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

      Ersetzen Sie REGION durch die Google Cloud Region des Dienstes, in der Sie die Funktion bereitstellen möchten. Beispiel: europe-west1

      Ruby

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

      Ersetzen Sie REGION durch die Google Cloud Region des Dienstes, in der Sie die Funktion bereitstellen möchten. Beispiel: europe-west1

      PHP

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

      Ersetzen Sie REGION durch die Google Cloud Region des Dienstes, in der Sie die Funktion bereitstellen möchten. Beispiel: europe-west1

      .NET

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

      Ersetzen Sie REGION durch die Google Cloud Region des Dienstes, in der Sie die Funktion bereitstellen möchten. Beispiel: europe-west1

    2. Wenn die Bereitstellung abgeschlossen ist, wird in der Google Cloud CLI eine URL angezeigt, unter der der Dienst ausgeführt wird. Öffnen Sie die URL in Ihrem Browser, um die Ausgabe Ihrer Funktion zu sehen.

    Bereinigen

    Während für Cloud Run keine Kosten anfallen, wenn der Dienst nicht verwendet wird, wird Ihnen dennoch das Speichern des Container-Images in Artifact Registry möglicherweise in Rechnung gestellt. Sie können das Container-Image löschen oder Ihr Google Cloud -Projekt löschen, um Kosten zu vermeiden. Durch das Löschen des Google Cloud -Projekts wird die Abrechnung für alle in diesem Projekt verwendeten Ressourcen beendet.

      Delete a Google Cloud project:

      gcloud projects delete PROJECT_ID

    Nächste Schritte