Panduan memulai: Men-deploy fungsi Cloud Run menggunakan gcloud CLI

Halaman ini menunjukkan cara men-deploy fungsi HTTP Cloud Run menggunakan gcloud CLI.

Sebelum memulai

  1. Login ke akun Google Cloud Anda. Jika Anda baru menggunakan Google Cloud, buat akun untuk mengevaluasi performa produk kami dalam skenario dunia nyata. Pelanggan baru juga mendapatkan kredit gratis senilai $300 untuk menjalankan, menguji, dan men-deploy workload.
  2. Instal Google Cloud CLI.

  3. Jika Anda menggunakan penyedia identitas (IdP) eksternal, Anda harus login ke gcloud CLI dengan identitas gabungan Anda terlebih dahulu.

  4. Untuk melakukan inisialisasi gcloud CLI, jalankan perintah berikut:

    gcloud init
  5. Buat atau pilih Google Cloud project.

    Peran yang diperlukan untuk memilih atau membuat project

    • Pilih project: Memilih project tidak memerlukan peran IAM tertentu—Anda dapat memilih project mana pun yang telah diberi peran.
    • Membuat project: Untuk membuat project, Anda memerlukan peran Pembuat Project (roles/resourcemanager.projectCreator), yang berisi izin resourcemanager.projects.create. Pelajari cara memberikan peran.
    • Buat Google Cloud project:

      gcloud projects create PROJECT_ID

      Ganti PROJECT_ID dengan nama untuk Google Cloud project yang Anda buat.

    • Pilih project Google Cloud yang Anda buat:

      gcloud config set project PROJECT_ID

      Ganti PROJECT_ID dengan nama project Google Cloud Anda.

  6. Jika Anda menggunakan project yang sudah ada untuk panduan ini, pastikan Anda memiliki izin yang diperlukan untuk menyelesaikan panduan ini. Jika berhasil membuat project baru, berarti Anda sudah memiliki izin yang diperlukan.

  7. Verifikasi bahwa penagihan diaktifkan untuk project Google Cloud Anda.

  8. Aktifkan Artifact Registry API, Cloud Build API, Cloud Run Admin API, dan Cloud Logging API:

    Peran yang diperlukan untuk mengaktifkan API

    Untuk mengaktifkan API, Anda memerlukan peran IAM Service Usage Admin (roles/serviceusage.serviceUsageAdmin), yang berisi izin serviceusage.services.enable. Pelajari cara memberikan peran.

    gcloud services enable artifactregistry.googleapis.com cloudbuild.googleapis.com run.googleapis.com logging.googleapis.com
  9. Instal Google Cloud CLI.

  10. Jika Anda menggunakan penyedia identitas (IdP) eksternal, Anda harus login ke gcloud CLI dengan identitas gabungan Anda terlebih dahulu.

  11. Untuk melakukan inisialisasi gcloud CLI, jalankan perintah berikut:

    gcloud init
  12. Buat atau pilih Google Cloud project.

    Peran yang diperlukan untuk memilih atau membuat project

    • Pilih project: Memilih project tidak memerlukan peran IAM tertentu—Anda dapat memilih project mana pun yang telah diberi peran.
    • Membuat project: Untuk membuat project, Anda memerlukan peran Pembuat Project (roles/resourcemanager.projectCreator), yang berisi izin resourcemanager.projects.create. Pelajari cara memberikan peran.
    • Buat Google Cloud project:

      gcloud projects create PROJECT_ID

      Ganti PROJECT_ID dengan nama untuk Google Cloud project yang Anda buat.

    • Pilih project Google Cloud yang Anda buat:

      gcloud config set project PROJECT_ID

      Ganti PROJECT_ID dengan nama project Google Cloud Anda.

  13. Jika Anda menggunakan project yang sudah ada untuk panduan ini, pastikan Anda memiliki izin yang diperlukan untuk menyelesaikan panduan ini. Jika berhasil membuat project baru, berarti Anda sudah memiliki izin yang diperlukan.

  14. Verifikasi bahwa penagihan diaktifkan untuk project Google Cloud Anda.

  15. Aktifkan Artifact Registry API, Cloud Build API, Cloud Run Admin API, dan Cloud Logging API:

    Peran yang diperlukan untuk mengaktifkan API

    Untuk mengaktifkan API, Anda memerlukan peran IAM Service Usage Admin (roles/serviceusage.serviceUsageAdmin), yang berisi izin serviceusage.services.enable. Pelajari cara memberikan peran.

    gcloud services enable artifactregistry.googleapis.com cloudbuild.googleapis.com run.googleapis.com logging.googleapis.com
  16. Guna menetapkan project default untuk layanan Cloud Run Anda:
     gcloud config set project PROJECT_ID
    Ganti PROJECT_ID dengan nama project yang Anda buat untuk panduan memulai ini.
  17. Jika Anda dikenai kebijakan organisasi pembatasan domain yang membatasi pemanggilan yang tidak diautentikasi untuk project, Anda perlu mengakses layanan yang di-deploy seperti yang dijelaskan di bagian Menguji layanan pribadi.

  18. Tinjau harga Cloud Run atau perkirakan biaya dengan kalkulator harga.

Peran yang diperlukan

Untuk mendapatkan izin yang Anda perlukan untuk menyelesaikan panduan memulai ini, minta administrator untuk memberi Anda peran IAM berikut:

Untuk mengetahui informasi selengkapnya tentang pemberian peran, lihat Mengelola akses ke project, folder, dan organisasi.

Anda mungkin juga bisa mendapatkan izin yang diperlukan melalui peran khusus atau peran bawaan lainnya.

Memberi akun layanan Cloud Build akses ke project Anda

Cloud Build otomatis menggunakan akun layanan default Compute Engine sebagai akun layanan Cloud Build default untuk membangun kode sumber dan resource Cloud Run Anda, kecuali jika Anda mengganti perilaku ini.

Agar Cloud Build dapat membangun sumber Anda, berikan peran Cloud Run Builder (roles/run.builder) di project Anda kepada akun layanan Cloud Build:

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

Ganti PROJECT_ID dengan project ID Google Cloud Anda dan SERVICE_ACCOUNT_EMAIL_ADDRESS dengan alamat email akun layanan Cloud Build. Jika Anda menggunakan akun layanan default Compute Engine sebagai akun layanan Cloud Build, gunakan format berikut untuk alamat email akun layanan:

PROJECT_NUMBER-compute@developer.gserviceaccount.com

Ganti PROJECT_NUMBER dengan nomor project Google Cloud Anda.

Untuk mengetahui petunjuk mendetail tentang cara menemukan project ID dan nomor project Anda, lihat Membuat dan mengelola project.

Pemberian peran builder Cloud Run memerlukan waktu beberapa menit untuk diterapkan.

Menulis fungsi contoh

Untuk menulis surat permohonan, ikuti langkah-langkah berikut:

Node.js

  1. Buat sebuah direktori baru bernama helloworld dan ubah ke direktori tersebut:

       mkdir helloworld
       cd helloworld
    

  2. Buat file package.json di direktori helloworld untuk menentukan dependensi 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. Buat file index.js di direktori helloworld dengan contoh Node.js berikut:

    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. Buat sebuah direktori baru bernama helloworld dan ubah ke direktori tersebut:

       mkdir helloworld
       cd helloworld
    

  2. Buat file requirements.txt di direktori helloworld, untuk menentukan dependensi Python:

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

    Langkah ini akan menambahkan paket yang dibutuhkan oleh contoh.

  3. Buat file main.py di direktori helloworld dengan contoh Python berikut:

    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. Buat sebuah direktori baru bernama helloworld dan ubah ke direktori tersebut:

       mkdir helloworld
       cd helloworld
    

  2. Buat file go.mod untuk mendeklarasikan go module:

    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. Buat file hello_http.go di direktori helloworld dengan contoh kode Go berikut:

    
    // 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. Buat sebuah direktori baru bernama helloworld dan ubah ke direktori tersebut:

       mkdir helloworld
       cd helloworld
    

  2. Buat struktur project berikut untuk memuat direktori sumber dan file sumber:

    mkdir -p ~/helloworld/src/main/java/functions
    touch ~/helloworld/src/main/java/functions/HelloWorld.java
    
  3. Perbarui file HelloWorld.java dengan contoh kode Java berikut:

    
    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. Buat file pom.xml di direktori helloworld, lalu tambahkan dependensi Java berikut:

    <?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. Buat sebuah direktori baru bernama helloworld dan ubah ke direktori tersebut:

       mkdir helloworld
       cd helloworld
    

  2. Buat file bernama app.rb lalu tempelkan kode berikut ke dalamnya:

    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. Buat file bernama Gemfile dan salin kode berikut ke dalamnya:

    source "https://rubygems.org"
    
    gem "base64", "~> 0.2"
    gem "functions_framework", "~> 1.4"
  4. Jika Anda belum menginstal Bundler 2.0 atau yang lebih baru, instal Bundler.

  5. Buat file Gemfile.lock dengan menjalankan:

    bundle install
    

PHP

  1. Buat sebuah direktori baru bernama helloworld dan ubah ke direktori tersebut:

       mkdir helloworld
       cd helloworld
    

  2. Buat file bernama index.php lalu tempelkan kode berikut ke dalamnya:

    
    use Psr\Http\Message\ServerRequestInterface;
    
    function helloGet(ServerRequestInterface $request): string
    {
        return 'Hello, World!' . PHP_EOL;
    }
    
  3. Jika Anda tidak menggunakan Cloud Shell, buat file composer.json dan tempelkan kode berikut ke dalamnya:

    {
        "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. Instal .NET SDK.

  2. Dari konsol, buat project web kosong baru menggunakan perintah dotnet.

    dotnet new web -o helloworld-csharp
    
  3. Ubah direktori menjadi helloworld-csharp:

  4. Ganti kode contoh di file project helloworld-csharp.csproj dengan kode berikut:

    <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. Ganti kode contoh dalam file Program.cs dengan kode berikut:

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

Men-deploy fungsi

Untuk men-deploy fungsi Cloud Run, ikuti langkah-langkah berikut:

  1. Deploy fungsi dengan menjalankan perintah berikut di direktori yang berisi kode contoh:

    Node.js

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

    Ganti REGION dengan Google Cloud region layanan tempat Anda ingin men-deploy fungsi. Contoh, europe-west1.

    Python

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

    Ganti REGION dengan Google Cloud region layanan tempat Anda ingin men-deploy fungsi. Contoh, europe-west1.

    Go

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

    Ganti REGION dengan Google Cloud region layanan tempat Anda ingin men-deploy fungsi. Contoh, europe-west1.

    Java

    Jalankan perintah berikut di direktori yang berisi file pom.xml:

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

    Ganti REGION dengan Google Cloud region layanan tempat Anda ingin men-deploy fungsi. Contoh, europe-west1.

    Ruby

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

    Ganti REGION dengan Google Cloud region layanan tempat Anda ingin men-deploy fungsi. Contoh, europe-west1.

    PHP

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

    Ganti REGION dengan Google Cloud region layanan tempat Anda ingin men-deploy fungsi. Contoh, europe-west1.

    .NET

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

    Ganti REGION dengan Google Cloud region layanan tempat Anda ingin men-deploy fungsi. Contoh, europe-west1.

  2. Setelah deployment selesai, Google Cloud CLI akan menampilkan URL tempat layanan berjalan. Buka URL di browser untuk melihat output fungsi Anda.

Pembersihan

Untuk menghindari biaya tambahan pada akun Google Cloud Anda, hapus semua resource yang Anda deploy dengan panduan memulai ini.

Menghapus repositori Anda

Cloud Run tidak mengenakan biaya saat layanan yang di-deploy tidak digunakan. Namun, Anda mungkin tetap dikenai biaya atas penyimpanan image container di Artifact Registry. Untuk menghapus repositori Artifact Registry, ikuti langkah-langkah di Menghapus repositori dalam dokumentasi Artifact Registry.

Menghapus layanan Anda

Layanan Cloud Run tidak menimbulkan biaya hingga menerima permintaan. Untuk menghapus layanan Cloud Run, ikuti salah satu langkah berikut:

Konsol

Untuk menghapus layanan:

  1. Di konsol Google Cloud , buka halaman Services Cloud Run:

    Buka Cloud Run

  2. Temukan layanan yang ingin Anda hapus dalam daftar layanan, lalu klik kotak centang layanan tersebut untuk memilihnya.

  3. Klik Hapus. Tindakan ini akan menghapus semua revisi layanan.

gcloud

Untuk menghapus layanan, jalankan perintah berikut:

gcloud run services delete SERVICE --region REGION

Ganti kode berikut:

  • SERVICE: nama layanan Anda.
  • REGION: Google Cloud region layanan.

Menghapus project pengujian Anda

Menghapus project Google Cloud akan menghentikan penagihan untuk semua resource dalam project tersebut. Untuk melepaskan semua Google Cloud resource di project Anda, ikuti langkah-langkah berikut:

    Menghapus Google Cloud project:

    gcloud projects delete PROJECT_ID

Langkah berikutnya