Crear y desplegar una función HTTP de Cloud Run con Node.js (1.ª gen.)

En esta guía se explica cómo escribir una función de Cloud Run con el entorno de ejecución Node.js. Hay dos tipos de funciones de Cloud Run:

  • Una función HTTP, que se invoca desde solicitudes HTTP estándar.
  • Una función basada en eventos que se usa para gestionar eventos de tu infraestructura de Cloud, como mensajes de un tema de Pub/Sub o cambios en un segmento de Cloud Storage.

En el ejemplo se muestra cómo crear una función HTTP sencilla.

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

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Functions and Cloud Build APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Functions and Cloud Build APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  8. Instala e inicializa gcloud CLI.
  9. Actualiza e instala los componentes de gcloud:
    gcloud components update
  10. Prepara tu entorno de desarrollo.

    Ir a la guía de configuración de Node.js

  11. Crear una función

    1. Crea un directorio en tu sistema local para el código de la función:

      Linux o Mac OS X

      mkdir ~/helloworld
      cd ~/helloworld
      

      Windows

      mkdir %HOMEPATH%\helloworld
      cd %HOMEPATH%\helloworld
      
    2. Crea un archivo index.js en el directorio helloworld con el siguiente contenido:

      const functions = require('@google-cloud/functions-framework');
      const escapeHtml = require('escape-html');
      
      /**
       * Responds to an HTTP request using data from the request body parsed according
       * to the "content-type" header.
       *
       * @param {Object} req Cloud Function request context.
       * @param {Object} res Cloud Function response context.
       */
      functions.http('helloHttp', (req, res) => {
        res.send(`Hello ${escapeHtml(req.query.name || req.body.name || 'World')}!`);
      });

      Esta función de ejemplo toma un nombre proporcionado en la solicitud HTTP y devuelve un saludo o "Hello World!" si no se proporciona ningún nombre.

    Especificar dependencias

    Las dependencias de Node.js se almacenan en un archivo llamado package.json. Puedes crear este archivo manualmente o con el comando npm.

    • Para crear el archivo de dependencia package.json con npm, ejecuta estos comandos:

      npm init
      npm install c8 gaxios mocha sinon supertest wait-port --save-dev
      npm install @google-cloud/functions-framework escape-html
      
    • Si prefieres crear el archivo package.json manualmente, crea un archivo package.json en el directorio helloworld con el siguiente contenido:

      {
        "name": "nodejs-docs-samples-functions-hello-world-http",
        "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": {
          "unit-test": "c8 mocha -p -j 2 test/index.test.js test/*unit*test.js test/*integration*test.js --timeout=6000 --exit",
          "system-test": "c8 mocha -p -j 2 test/*system*test.js --timeout=600000 --exit",
          "all-test": "npm run unit-test && npm run system-test",
          "test": "npm -- run unit-test"
        },
        "dependencies": {
          "@google-cloud/functions-framework": "^3.1.0",
          "escape-html": "^1.0.3"
        },
        "devDependencies": {
          "c8": "^10.0.0",
          "gaxios": "^6.0.0",
          "mocha": "^10.0.0",
          "sinon": "^18.0.0",
          "supertest": "^7.0.0",
          "wait-port": "^1.0.4"
        }
      }
      

    Desplegar la función

    Para desplegar la función con un activador HTTP, ejecuta el siguiente comando en el directorio helloworld:

    gcloud functions deploy helloHttp --no-gen2 --runtime nodejs20 --trigger-http --allow-unauthenticated
    

    La marca --allow-unauthenticated te permite acceder a la función sin autenticación. Para requerir autenticación, omite la marca.

    Probar función

    1. Cuando la función termine de implementarse, anota la propiedad httpsTrigger.url o búscala con el siguiente comando:

      gcloud functions describe helloHttp
      

      Debería tener este aspecto:

      https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloHttp
    2. Visita esta URL en tu navegador. Debería aparecer el mensaje "Hello World!".

      Prueba a enviar un nombre en la solicitud HTTP. Por ejemplo, puedes usar la siguiente URL:

      https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloHttp?name=NAME

      Debería aparecer el mensaje "Hola NAME".

    Ver registros

    Los registros de las funciones de Cloud Run se pueden ver con la CLI de Google Cloud y en la interfaz de usuario de Cloud Logging.

    Usar la herramienta de línea de comandos

    Para ver los registros de tu función con gcloud CLI, usa el comando logs read, seguido del nombre de la función:

    gcloud functions logs read helloHttp

    La salida debería ser similar a la siguiente:

    LEVEL  NAME       EXECUTION_ID  TIME_UTC                 LOG
    D      helloHttp  rvb9j0axfclb  2019-09-18 22:06:25.983  Function execution started
    D      helloHttp  rvb9j0axfclb  2019-09-18 22:06:26.001  Function execution took 19 ms, finished with status code: 200

    Usar el panel de control de Logging

    También puedes ver los registros de las funciones de Cloud Run desde la Google Cloud consola.