Creare una funzione Cloud Run (1ª gen.) utilizzando Google Cloud CLI

Questa pagina mostra come creare ed eseguire il deployment di una funzione Cloud Run di 1ª generazione utilizzando la Google Cloud CLI.

Prima di iniziare

  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. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Functions and Cloud Build APIs.

    Enable the APIs

  5. Installa e inizializza la gcloud CLI.
  6. Aggiorna i componenti gcloud:
    gcloud components update
  7. Hai bisogno di un prompt dei comandi? Puoi utilizzare Google Cloud Shell. un ambiente a riga di comando che include già Google Cloud CLI, pertanto non è necessario installarlo. Google Cloud CLI è preinstallato anche nelle macchine virtuali di Google Compute Engine.

  8. Prepara l'ambiente di sviluppo.

    Vai alla guida alla configurazione di Node.js

    Vai alla guida alla configurazione di Python

    Vai alla guida alla configurazione di Go

    Vai alla guida alla configurazione di Java

    Vai alla guida alla configurazione di .NET

    Vai alla guida alla configurazione di Ruby

    Vai a Utilizzo di PHP su Google Cloud

recupera il codice campione

  1. Clona il repository di esempio sulla tua macchina locale:

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

    In alternativa, puoi scaricare l'esempio come file ZIP ed estrarlo.

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

    In alternativa, puoi scaricare l'esempio come file ZIP ed estrarlo.

    git clone https://github.com/GoogleCloudPlatform/golang-samples.git

    In alternativa, puoi scaricare l'esempio come file ZIP ed estrarlo.

    git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git

    In alternativa, puoi scaricare l'esempio come file ZIP ed estrarlo.

    git clone https://github.com/GoogleCloudPlatform/dotnet-docs-samples.git

    In alternativa, puoi scaricare l'esempio come file ZIP ed estrarlo.

    git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples.git

    In alternativa, puoi scaricare l'esempio come file ZIP ed estrarlo.

    git clone https://github.com/GoogleCloudPlatform/php-docs-samples.git

    In alternativa, puoi scaricare l'esempio come file ZIP ed estrarlo.

  2. Passa alla directory che contiene il codice di esempio delle funzioni Cloud Run:

    cd nodejs-docs-samples/functions/helloworld/
    cd python-docs-samples/functions/helloworld/
    cd golang-samples/functions/helloworld/
    cd java-docs-samples/functions/helloworld/helloworld/
    cd dotnet-docs-samples/functions/helloworld/HelloWorld/
    cd ruby-docs-samples/functions/helloworld/get/
    cd php-docs-samples/functions/helloworld_get/

  3. Dai un'occhiata al codice di esempio:

    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!');
    });
    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!"
    
    
    
    // Package helloworld provides a set of Cloud Functions samples.
    package helloworld
    
    import (
    	"fmt"
    	"net/http"
    )
    
    // HelloGet is an HTTP Cloud Function.
    func HelloGet(w http.ResponseWriter, r *http.Request) {
    	fmt.Fprint(w, "Hello, World!")
    }
    
    
    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!");
      }
    }
    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);
        }
    }
    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
    
    use Psr\Http\Message\ServerRequestInterface;
    
    function helloGet(ServerRequestInterface $request): string
    {
        return 'Hello, World!' . PHP_EOL;
    }
    

Esegui il deployment di una funzione

Per il deployment della funzione con un trigger HTTP, esegui questo comando nella directory contenente la funzione:

gcloud functions deploy helloGET \
--runtime nodejs22 --trigger-http

Utilizza il flag --runtime per specificare l'ID runtime di una versione di Node.js supportata per eseguire la funzione.

gcloud functions deploy hello_get \
--runtime python312 --trigger-http

Utilizza il flag --runtime per specificare l'ID runtime di una versione di Python supportata per eseguire la funzione.

gcloud functions deploy HelloGet \
--runtime go122 --trigger-http

Utilizza il flag --runtime per specificare l'ID runtime di una versione Go supportata per eseguire la funzione.

gcloud functions deploy java-helloworld \
--entry-point functions.HelloWorld \
--runtime java21 \
--memory 512MB --trigger-http

Utilizza il flag --runtime per specificare l'ID runtime di una versione Java supportata per eseguire la funzione.

gcloud functions deploy csharp-helloworld \
--entry-point HelloWorld.Function \
--runtime dotnet8 --trigger-http

Utilizza il flag --runtime per specificare l'ID runtime di una versione .NET supportata per eseguire la funzione.

gcloud functions deploy hello_get --runtime ruby33 --trigger-http

Utilizza il flag --runtime per specificare l'ID runtime di una versione di Ruby supportata per eseguire la funzione.

 gcloud functions deploy helloGet --runtime php83 --trigger-http

Utilizza il flag --runtime per specificare l'ID runtime di una versione PHP supportata per eseguire la funzione.

Facoltativamente, puoi utilizzare il flag --allow-unauthenticated per raggiungere la funzione senza autenticazione. Questa opzione è utile per i test, ma non consigliamo di utilizzarla in produzione, a meno che non tu stia creando un'API o un sito web pubblici. Inoltre, potrebbe non funzionare per te, a seconda delle impostazioni dei criteri aziendali. Consulta la sezione Autenticazione per le chiamate per informazioni dettagliate su come richiamare una funzione che richiede l'autenticazione.

testa la funzione

  1. Al termine del deployment della funzione, annota la proprietà url di httpsTrigger o cercala utilizzando il seguente comando:

    gcloud functions describe helloGET --format="value(httpsTrigger.url)"
    gcloud functions describe hello_get --format="value(httpsTrigger.url)"
    gcloud functions describe HelloGet --format="value(httpsTrigger.url)"
    gcloud functions describe java-helloworld --format="value(httpsTrigger.url)"
    gcloud functions describe csharp-helloworld --format="value(httpsTrigger.url)"
    gcloud functions describe hello_get --format="value(httpsTrigger.url)"
    gcloud functions describe helloGet --format="value(httpsTrigger.url)"

    Dovrebbe avere il seguente aspetto:

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloGET
    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_get
    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/HelloGet
    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/java-helloworld
    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/csharp-helloworld
    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_get
    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloGet

  2. Accedi all'URL dal browser. Dovresti vedere un messaggio Hello World!.

Elimina la funzione

Per eliminare la funzione, esegui il seguente comando:

gcloud functions delete helloGET 
gcloud functions delete hello_get 
gcloud functions delete HelloGet 
gcloud functions delete java-helloworld 
gcloud functions delete csharp-helloworld 
gcloud functions delete hello_get 
gcloud functions delete helloGet 

Passaggi successivi

Consulta la guida La tua prima funzione pertinente per il runtime di tua scelta per scoprire come configurare il tuo ambiente di sviluppo, creare una nuova funzione da zero, specificare le dipendenze, eseguire il deployment della funzione, testarla e visualizzare i log. Tieni presente che queste guide sono solo per le funzioni Cloud Run (1ª gen.):