Guía de inicio rápido: desplegar una función de Cloud Run con gcloud CLI

En esta página se muestra cómo desplegar una función HTTP de Cloud Run mediante la CLI de gcloud.

Antes de empezar

  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. Si utilizas un proveedor de identidades (IdP) externo, primero debes iniciar sesión en la CLI de gcloud con tu identidad federada.

  4. Para inicializar gcloud CLI, ejecuta el siguiente comando:

    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. Si utilizas un proveedor de identidades (IdP) externo, primero debes iniciar sesión en la CLI de gcloud con tu identidad federada.

  11. Para inicializar gcloud CLI, ejecuta el siguiente comando:

    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. Para definir el proyecto predeterminado de tu servicio de Cloud Run, sigue estos pasos:
     gcloud config set project PROJECT_ID
    Sustituye PROJECT_ID por el nombre del proyecto que has creado para esta guía de inicio.
  17. Si tu proyecto está sujeto a una política de organización de restricción de dominio que restringe las invocaciones no autenticadas, tendrás que acceder al servicio desplegado tal como se describe en la sección Probar servicios privados.

  18. Asegúrate de que tienes asignado el rol Usuario de cuenta de servicio en la identidad de servicio. De forma predeterminada, la identidad de servicio es la cuenta de servicio predeterminada de Compute Engine.

    Conceder los roles

    Para conceder acceso al recurso de identidad de servicio, usa el comando gcloud iam service-accounts add-iam-policy-binding y sustituye las variables destacadas por los valores correspondientes:

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

    Haz los cambios siguientes:

    • SERVICE_ACCOUNT_EMAIL: la dirección de correo de la cuenta de servicio que usas como identidad de servicio, como:
      • Cuenta de servicio predeterminada de Compute Engine: PROJECT_NUMBER-compute@developer.gserviceaccount.com
      • Una cuenta de servicio que has creado: SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com
    • PRINCIPAL: el identificador de usuario. Normalmente, se trata de la dirección de correo de una cuenta de Google.
  19. Concede a la cuenta de servicio de Cloud Build el siguiente rol de gestión de identidades y accesos.

    Haz clic para ver los roles necesarios de la cuenta de servicio de Cloud Build

    Cloud Build usa automáticamente la cuenta de servicio predeterminada de Compute Engine como cuenta de servicio predeterminada de Cloud Build para compilar tu código fuente y tu recurso de Cloud Run, a menos que anules este comportamiento. Para que Cloud Build compile tus fuentes, pide a tu administrador que conceda el rol Compilador de Cloud Run (roles/run.builder) a la cuenta de servicio predeterminada de Compute Engine de tu proyecto:

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

    Sustituye PROJECT_NUMBER por el número de tu proyecto Google Cloud y PROJECT_ID por el ID de tu proyecto Google Cloud. Para obtener instrucciones detalladas sobre cómo encontrar el ID y el número de tu proyecto, consulta el artículo Crear y gestionar proyectos.

    La concesión del rol de compilador de Cloud Run a la cuenta de servicio predeterminada de Compute Engine tarda un par de minutos en propagarse.

  20. Escribir la función de ejemplo

    Para escribir una solicitud, sigue estos pasos:

    Node.js

    1. Crea un directorio llamado helloworld y cambia a ese directorio:

         mkdir helloworld
         cd helloworld
      

    2. Crea un archivo package.json en el directorio helloworld para especificar las dependencias de 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. Crea un archivo index.js en el directorio helloworld con el siguiente ejemplo 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. Crea un directorio llamado helloworld y cambia a ese directorio:

         mkdir helloworld
         cd helloworld
      

    2. Crea un archivo requirements.txt en el directorio helloworld para especificar las dependencias de Python:

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

      De esta forma, se añaden los paquetes que necesita el ejemplo.

    3. Crea un archivo main.py en el directorio helloworld con el siguiente ejemplo de 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. Crea un directorio llamado helloworld y cambia a ese directorio:

         mkdir helloworld
         cd helloworld
      

    2. Crea un archivo go.mod para declarar el módulo de 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. Crea un archivo hello_http.go en el directorio helloworld con el siguiente código de ejemplo de 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. Crea un directorio llamado helloworld y cambia a ese directorio:

         mkdir helloworld
         cd helloworld
      

    2. Crea la siguiente estructura de proyecto para que contenga el directorio de origen y el archivo de origen:

      mkdir -p ~/helloworld/src/main/java/functions
      touch ~/helloworld/src/main/java/functions/HelloWorld.java
      
    3. Actualiza el archivo HelloWorld.java con el siguiente código de muestra de 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. Crea un archivo pom.xml en el directorio helloworld y añade las siguientes dependencias de 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. Crea un directorio llamado helloworld y cambia a ese directorio:

         mkdir helloworld
         cd helloworld
      

    2. Crea un archivo llamado app.rb y pega el siguiente código en él:

      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. Crea un archivo llamado Gemfile y copia lo siguiente en él:

      source "https://rubygems.org"
      
      gem "base64", "~> 0.2"
      gem "functions_framework", "~> 1.4"
    4. Si no tienes instalada la versión 2.0 o una posterior de Bundler, instala Bundler.

    5. Genera un archivo Gemfile.lock ejecutando el siguiente comando:

      bundle install
      

    PHP

    1. Crea un directorio llamado helloworld y cambia a ese directorio:

         mkdir helloworld
         cd helloworld
      

    2. Crea un archivo llamado index.php y pega el siguiente código en él:

      
      use Psr\Http\Message\ServerRequestInterface;
      
      function helloGet(ServerRequestInterface $request): string
      {
          return 'Hello, World!' . PHP_EOL;
      }
      
    3. Si no usas Cloud Shell, crea un archivo composer.json y pega el siguiente código en él:

      {
          "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. Instala el SDK de.NET.

    2. En la consola, crea un proyecto web vacío con el comando dotnet.

      dotnet new web -o helloworld-csharp
      
    3. Cambia al directorio helloworld-csharp:

    4. Sustituye el código de ejemplo del archivo de proyecto helloworld-csharp.csproj por el siguiente:

      <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. Sustituye el código de ejemplo del archivo Program.cs por el siguiente:

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

    Desplegar la función

    Importante: En esta guía de inicio rápido se da por hecho que tienes el rol de propietario o editor en el proyecto que vas a usar. De lo contrario, consulta los permisos necesarios para implementar un recurso de Cloud Run desde el origen.

    Para implementar tu función de Cloud Run, sigue estos pasos:

    1. Para implementar la función, ejecuta el siguiente comando en el directorio que contiene el código de muestra:

      Node.js

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

      Sustituye REGION por la Google Cloud región del servicio en el que quieras desplegar tu función. Por ejemplo, europe-west1.

      Python

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

      Sustituye REGION por la Google Cloud región del servicio en el que quieras desplegar tu función. Por ejemplo, europe-west1.

      Go

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

      Sustituye REGION por la Google Cloud región del servicio en el que quieras desplegar tu función. Por ejemplo, europe-west1.

      Java

      Ejecuta el siguiente comando en el directorio que contiene el archivo pom.xml:

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

      Sustituye REGION por la Google Cloud región del servicio en el que quieras desplegar tu función. Por ejemplo, europe-west1.

      Ruby

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

      Sustituye REGION por la Google Cloud región del servicio en el que quieras desplegar tu función. Por ejemplo, europe-west1.

      PHP

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

      Sustituye REGION por la Google Cloud región del servicio en el que quieras desplegar tu función. Por ejemplo, europe-west1.

      .NET

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

      Sustituye REGION por la Google Cloud región del servicio en el que quieras desplegar tu función. Por ejemplo, europe-west1.

    2. Cuando se complete el despliegue, la CLI de Google Cloud mostrará una URL en la que se esté ejecutando el servicio. Abre la URL en el navegador para ver el resultado de tu función.

    Limpieza

    Aunque Cloud Run no aplica cargos cuando el servicio no se está usando, es posible que se te cobre por almacenar la imagen de contenedor en Artifact Registry. Puede eliminar su imagen de contenedor o su proyecto Google Cloud para evitar que se le apliquen cargos. Al eliminar tu Google Cloud proyecto, se detendrá la facturación de todos los recursos utilizados en ese proyecto.

      Delete a Google Cloud project:

      gcloud projects delete PROJECT_ID

    Siguientes pasos