Guia de início rápido: implantar uma função no Cloud Run usando a gcloud CLI

Esta página mostra como usar o Cloud Run para implantar uma função HTTP usando a gcloud CLI.

Antes de começar

  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. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Verifique se a cobrança está ativada para o seu projeto do Google Cloud.

  4. Enable the Artifact Registry, Cloud Build, Cloud Run Admin API, and Cloud Logging APIs.

    Enable the APIs

  5. Install the Google Cloud CLI.
  6. To initialize the gcloud CLI, run the following command:

    gcloud init
  7. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  8. Verifique se a cobrança está ativada para o seu projeto do Google Cloud.

  9. Enable the Artifact Registry, Cloud Build, Cloud Run Admin API, and Cloud Logging APIs.

    Enable the APIs

  10. Install the Google Cloud CLI.
  11. To initialize the gcloud CLI, run the following command:

    gcloud init
  12. Para definir o projeto padrão do serviço do Cloud Run:
     gcloud config set project PROJECT_ID
    Substitua PROJECT_ID pelo nome do projeto que você criou para este guia de início rápido.
  13. Se você precisa seguir uma política da organização de restrição de domínio que restringe invocações não autenticadas para seu projeto, será necessário acessar o serviço implantado, conforme descrito em Como testar serviços particulares.

  14. Para que o Cloud Build consiga criar suas origens, conceda o papel Conta de serviço do Cloud Build para a conta de serviço padrão do Compute Engine. Basta executar o comando a seguir:

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

    Substitua PROJECT_NUMBER pelo número do projeto do Google Cloud e PROJECT_ID pelo ID do projeto do Google Cloud.

    O número e o ID do projeto estão disponíveis na página Olá! do console do Google Cloud.

Escrever a função de exemplo

Para escrever um aplicativo, siga estas etapas:

Node.js

  1. Crie um novo diretório com o nome helloworld e altere o diretório nele:

       mkdir helloworld
       cd helloworld
    

  2. Crie um arquivo package.json no diretório helloworld para especificar as dependências do 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. Crie um arquivo index.js no diretório helloworld com o seguinte exemplo de 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. Crie um novo diretório com o nome helloworld e altere o diretório nele:

       mkdir helloworld
       cd helloworld
    

  2. Crie um arquivo requirements.txt no diretório helloworld para especificar dependências do Python:

    functions-framework==3.5.0
    flask==3.0.3
    google-cloud-error-reporting==1.9.1
    MarkupSafe==2.1.3
    

    Isso adiciona os pacotes necessários para a amostra.

  3. Crie um arquivo main.py no diretório helloworld com o seguinte exemplo em 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. Crie um novo diretório com o nome helloworld e altere o diretório nele:

       mkdir helloworld
       cd helloworld
    

  2. Crie um arquivo go.mod para declarar o módulo go:

    module github.com/GoogleCloudPlatform/golang-samples/functions/helloworld
    
    go 1.21
    
    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
    	go.uber.org/multierr v1.11.0 // indirect
    	go.uber.org/zap v1.27.0 // indirect
    	golang.org/x/time v0.5.0 // indirect
    )
    

    Você pode criar o arquivo go.mod diretamente no formato conforme mostrado ou inicializá-lo a partir do diretório do projeto com:

       go mod init github.com/GoogleCloudPlatform/golang-samples/functions/functionsv2/helloworld/go.mod
    
  3. Crie um arquivo hello_http.go no diretório helloworld com o exemplo de código Go a seguir:

    
    // 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. Crie um novo diretório com o nome helloworld e altere o diretório nele:

       mkdir helloworld
       cd helloworld
    

  2. Crie a seguinte estrutura do projeto para conter o diretório de origem e o arquivo de origem.

    mkdir -p ~/helloworld/src/main/java/functions
    touch ~/helloworld/src/main/java/functions/HelloWorld.java
    
  3. Atualize o arquivo HelloWorld.java com o seguinte exemplo de código 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. Crie um arquivo pom.xml no diretório helloworld e adicione as seguintes dependências do 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>
    

.NET

  1. Instale o SDK do .NET 6.0. Este guia de início rápido só funciona com o .NET versão 6.

  2. No console, crie um novo projeto da Web vazio usando o comando dotnet.

    dotnet new web -o helloworld-csharp
    
  3. Altere o diretório para helloworld-csharp:

  4. Substitua o exemplo de código no arquivo do projeto helloworld-csharp.csproj pelo seguinte:

    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net6.0</TargetFramework>
      </PropertyGroup>
    
      <ItemGroup>
        <PackageReference Include="Google.Cloud.Functions.Hosting" Version="2.2.1" />
      </ItemGroup>
    </Project>
  5. Substitua o exemplo de código no arquivo Program.cs pelo seguinte:

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

implantar a função

Importante: este guia de início rápido pressupõe que você tenha papéis de proprietário ou editor no projeto que está usando para este guia. Caso contrário, consulte o papel de desenvolvedor de origem do Cloud Run para ter acesso às permissões necessárias para implantar um recurso do Cloud Run a partir da origem.

Para implantar a função do Cloud Run, siga estas etapas:

  1. Implante a função executando o seguinte comando no diretório contém o exemplo de código:

    Node.js

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

    Substitua REGION pela região do Google Cloud do serviço em que você quer implantar a função. Por exemplo, us-central1.

    Python

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

    Substitua REGION pela região do Google Cloud do serviço em que você quer implantar a função. Por exemplo, us-central1.

    Go

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

    Substitua REGION pela região do Google Cloud do serviço em que você quer implantar a função. Por exemplo, us-central1.

    Java

    Execute o seguinte comando no diretório que contém o arquivo pom.xml:

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

    Substitua REGION pela região do Google Cloud do serviço em que você quer implantar a função. Por exemplo, us-central1.

    .NET

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

    Substitua REGION pela região do Google Cloud do serviço em que você quer implantar a função. Por exemplo, us-central1.

  2. Quando a implantação for concluída, a CLI do Google Cloud vai mostrar um URL em que o serviço está em execução. Abra o URL em seu navegador para ver a saída da sua função.

Para aprender a adicionar gatilhos do Eventarc à função, consulte o guia Implantar uma função para mais instruções.

Limpar

Ainda que o Cloud Run não gere custos quando o serviço não estiver em uso, é possível que receba cobranças pelo armazenamento da imagem do contêiner no Artifact Registry. É possível excluir sua imagem de contêiner ou excluir seu projeto do Google Cloud para evitar cobranças. A exclusão do projeto do Google Cloud interrompe o faturamento de todos os recursos usados no projeto.

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

A seguir