מדריך למתחילים: פריסת פונקציה ב-Cloud Run באמצעות ה-CLI של gcloud

בדף הזה מוסבר איך לפרוס פונקציה של Cloud Run מסוג HTTP באמצעות ה-CLI של gcloud.

לפני שמתחילים

  1. נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  2. התקינו את ה-CLI של Google Cloud.

  3. אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  4. כדי לאתחל את ה-CLI של gcloud, הריצו את הפקודה הבאה:

    gcloud init
  5. יוצרים או בוחרים Google Cloud פרויקט.

    תפקידים שנדרשים כדי לבחור או ליצור פרויקט

    • Select a project: כדי לבחור פרויקט לא צריך תפקיד IAM ספציפי – אפשר לבחור כל פרויקט שקיבלתם בו תפקיד.
    • יצירת פרויקט: כדי ליצור פרויקט, צריך את התפקיד Project Creator (יצירת פרויקטים) (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. מפעילים את ממשקי ה-API של Artifact Registry,‏ Cloud Build,‏ Cloud Run Admin ו-Cloud Logging:

    תפקידים שנדרשים להפעלת ממשקי API

    כדי להפעיל ממשקי API, צריך את תפקיד ה-IAM 'אדמין של Service Usage' (roles/serviceusage.serviceUsageAdmin), שכולל את ההרשאה serviceusage.services.enable. איך מקצים תפקידים

    gcloud services enable artifactregistry.googleapis.com cloudbuild.googleapis.com run.googleapis.com logging.googleapis.com
  9. התקינו את ה-CLI של Google Cloud.

  10. אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  11. כדי לאתחל את ה-CLI של gcloud, הריצו את הפקודה הבאה:

    gcloud init
  12. יוצרים או בוחרים Google Cloud פרויקט.

    תפקידים שנדרשים כדי לבחור או ליצור פרויקט

    • Select a project: כדי לבחור פרויקט לא צריך תפקיד IAM ספציפי – אפשר לבחור כל פרויקט שקיבלתם בו תפקיד.
    • יצירת פרויקט: כדי ליצור פרויקט, צריך את התפקיד Project Creator (יצירת פרויקטים) (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. מפעילים את ממשקי ה-API של Artifact Registry,‏ Cloud Build,‏ Cloud Run Admin ו-Cloud Logging:

    תפקידים שנדרשים להפעלת ממשקי API

    כדי להפעיל ממשקי API, צריך את תפקיד ה-IAM 'אדמין של Service Usage' (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 או להשתמש במחשבון התמחור כדי לקבל הערכה של העלויות.

התפקידים הנדרשים

כדי לקבל את ההרשאות שדרושות להשלמת המדריך הזה, אתם צריכים לבקש מהאדמין להקצות לכם את תפקידי ה-IAM הבאים:

להסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

יכול להיות שאפשר לקבל את ההרשאות הנדרשות גם באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש.

נותנים לחשבון השירות ב-Cloud Build גישה לפרויקט

כברירת מחדל, Cloud Build משתמש בחשבון השירות שמוגדר כברירת מחדל ב-Compute Engine כחשבון השירות שמוגדר כברירת מחדל ב-Cloud Build כדי לבנות את קוד המקור ואת משאב Cloud Run, אלא אם משנים את ההתנהגות הזו.

כדי ש-Cloud Build יוכל לבנות את המקורות, צריך להקצות לחשבון השירות של Cloud Build את התפקיד Cloud Run Builder‏ (roles/run.builder) בפרויקט:

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

מחליפים את PROJECT_ID במזהה הפרויקט שלכם ב- Google Cloudואת SERVICE_ACCOUNT_EMAIL_ADDRESS בכתובת האימייל של חשבון השירות של Cloud Build. אם אתם משתמשים בחשבון השירות שמוגדר כברירת מחדל ב-Compute Engine כחשבון השירות ב-Cloud Build, אתם צריכים להשתמש בפורמט הבא עבור כתובת האימייל בחשבון השירות:

PROJECT_NUMBER-compute@developer.gserviceaccount.com

מחליפים את PROJECT_NUMBER במספר הפרויקט ב- Google Cloud.

הוראות מפורטות לאיתור מזהה הפרויקט ומספר הפרויקט זמינות במאמר יצירה וניהול של פרויקטים.

לוקח כמה דקות עד שההרשאה של התפקיד Cloud Run builder מתעדכנת.

כתיבת פונקציית הדוגמה

כדי לכתוב בקשה:

Node.js

  1. יוצרים ספרייה חדשה בשם helloworld ועוברים אליה:

       mkdir helloworld
       cd helloworld
    

  2. יוצרים קובץ package.json בספרייה helloworld כדי לציין תלויות של 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. יוצרים קובץ index.js בתיקייה helloworld עם הדוגמה הבאה של Node.js:

    import { http } from '@google-cloud/functions-framework';
    // Register an HTTP function with the Functions Framework that executes
    // when you make an HTTP request to the deployed function's endpoint.
    http('helloGET', (req, res) => {
      res.send('Hello World!');
    });

Python

  1. יוצרים ספרייה חדשה בשם helloworld ועוברים אליה:

       mkdir helloworld
       cd helloworld
    

  2. יוצרים קובץ requirements.txt בספרייה helloworld כדי לציין יחסי תלות של Python:

    functions-framework==3.9.2
    Flask==3.1.3; python_version >= '3.9'
    google-cloud-error-reporting==1.11.1
    MarkupSafe==2.1.3
    

    הפעולה הזו מוסיפה חבילות שדרושות לדוגמה.

  3. יוצרים קובץ main.py בספרייה helloworld עם דוגמת 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!"
    
    

המשך

  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.15.0 // indirect
    )
    
  3. יוצרים קובץ hello_http.go בספרייה helloworld עם דוגמת קוד 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. מעדכנים את הקובץ HelloWorld.java באמצעות דוגמת הקוד הבאה ב-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. יוצרים קובץ pom.xml בספרייה helloworld ומוסיפים את יחסי התלות הבאים של 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. אם לא מותקנת אצלכם גרסה 2.0 של Bundler או גרסה מתקדמת יותר, צריך להתקין את 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:

  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.

    המשך

    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 php85 \
           --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 מציג כתובת URL שבה השירות פועל. פותחים את כתובת ה-URL בדפדפן כדי לראות את הפלט של הפונקציה.

הסרת המשאבים

כדי להימנע מחיובים נוספים בחשבון Google Cloud , מוחקים את כל המשאבים שהצבתם באמצעות המדריך הזה.

מחיקת המאגר

ב-Cloud Run לא מחייבים אתכם כשהשירות שפרסתם לא נמצא בשימוש. עם זאת, יכול להיות שעדיין תחויבו על אחסון קובץ האימג' של הקונטיינר ב-Artifact Registry. כדי למחוק מאגרי Artifact Registry, פועלים לפי השלבים שמפורטים במאמר מחיקת מאגרים במסמכי התיעוד של Artifact Registry.

מחיקת השירות

שירותי Cloud Run לא צוברים עלויות עד שהם מקבלים בקשות. כדי למחוק את שירות Cloud Run, פועלים לפי אחד מהשלבים הבאים:

המסוף

כדי למחוק שירות:

  1. נכנסים לדף Services של Cloud Run במסוף Google Cloud :

    כניסה ל-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

המאמרים הבאים