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
- 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.
-
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 theresourcemanager.projects.create
permission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
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 theserviceusage.services.enable
permission. Learn how to grant roles. -
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 theresourcemanager.projects.create
permission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
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 theserviceusage.services.enable
permission. Learn how to grant roles. - Instala e inicializa gcloud CLI.
- Actualiza e instala los componentes de
gcloud
:gcloud components update
- Prepara tu entorno de desarrollo.
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
Crea un archivo
index.js
en el directoriohelloworld
con el siguiente contenido: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.
Para crear el archivo de dependencia
package.json
connpm
, 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 archivopackage.json
en el directoriohelloworld
con el siguiente contenido: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
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
".
Crear una función
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.
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
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.