Google Cloud CLI를 사용하여 1세대 Cloud 함수 만들기

이 페이지에서는 Google Cloud CLI를 사용하여 1세대 Cloud 함수를 만들고 배포하는 방법을 보여줍니다.

시작하기 전에

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  3. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  4. API Cloud Functions and Cloud Build 사용 설정

    API 사용 설정

  5. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  6. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  7. API Cloud Functions and Cloud Build 사용 설정

    API 사용 설정

  8. gcloud CLI를 설치하고 초기화합니다.
  9. gcloud 구성요소를 업데이트합니다.
    gcloud components update
  10. 명령 프롬프트가 필요하신가요? Google Cloud Shell을 사용해보세요. Google Cloud Shell 명령줄 환경에는 Google Cloud CLI가 이미 포함되어 있으므로 별도로 설치할 필요가 없습니다. Google Cloud CLI는 Google Compute Engine 가상 머신에도 사전 설치되어 있습니다.

  11. 개발 환경을 준비합니다.

샘플 코드 가져오기

  1. 샘플 저장소를 로컬 머신에 클론합니다.

    Node.js

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

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    Python

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

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    Go

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

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    Java

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

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    C#

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

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    Ruby

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

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

    PHP

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

    또는 zip 파일로 샘플을 다운로드하고 압축을 풀 수 있습니다.

  2. Cloud Functions 샘플 코드가 있는 디렉터리로 변경합니다.

    Node.js

    cd nodejs-docs-samples/functions/helloworld/

    Python

    cd python-docs-samples/functions/helloworld/

    Go

    cd golang-samples/functions/helloworld/

    Java

    cd java-docs-samples/functions/helloworld/helloworld/

    C#

    cd dotnet-docs-samples/functions/helloworld/HelloWorld/

    Ruby

    cd ruby-docs-samples/functions/helloworld/get/

    PHP

    cd php-docs-samples/functions/helloworld_get/

  3. 다음 샘플 코드를 살펴봅니다.

    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

    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

    
    // 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!")
    }
    

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

    C#

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

    Ruby

    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

    PHP

    
    use Psr\Http\Message\ServerRequestInterface;
    
    function helloGet(ServerRequestInterface $request): string
    {
        return 'Hello, World!' . PHP_EOL;
    }
    

함수 배포

HTTP 트리거를 사용하여 함수를 배포하려면 함수가 포함된 디렉터리에서 다음 명령어를 실행합니다.

Node.js

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

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Node.js 버전의 런타임 ID를 지정합니다.

Python

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

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Python 버전의 런타임 ID를 지정합니다.

Go

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

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Go 버전의 런타임 ID를 지정합니다.

Java

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

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Java 버전의 런타임 ID를 지정합니다.

C#

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

--runtime 플래그를 사용하여 함수를 실행할 지원되는 .NET 버전의 런타임 ID를 지정합니다.

Ruby

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

--runtime 플래그를 사용하여 함수를 실행할 지원되는 Ruby 버전의 런타임 ID를 지정합니다.

PHP

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

--runtime 플래그를 사용하여 함수를 실행할 지원되는 PHP 버전의 런타임 ID를 지정합니다.

선택적으로 --allow-unauthenticated 플래그를 사용하여 인증 없이 함수에 도달할 수 있습니다. 이 방법은 테스트에 유용하지만, 공개 API 또는 웹사이트를 만들지 않는 한 프로덕션에서 이 설정을 사용하지 않는 것이 좋습니다. 또한 기업 정책 설정에 따라 작동하지 않을 수 있습니다. 인증이 필요한 함수를 호출하는 방법에 대한 자세한 내용은 호출 인증을 참조하세요.

함수 테스트

  1. 함수를 통해 배포를 완료하면 httpsTriggerurl 속성을 기록해 두거나 다음 명령어를 사용하여 찾을 수 있습니다.

    Node.js

    gcloud functions describe helloGET

    Python

    gcloud functions describe hello_get

    Go

    gcloud functions describe HelloGet

    Java

    gcloud functions describe java-helloworld

    C#

    gcloud functions describe csharp-helloworld

    Ruby

    gcloud functions describe hello_get

    PHP

    gcloud functions describe helloGet

    예를 들면 다음과 같습니다.

    Node.js

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloGET

    Python

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_get

    Go

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/HelloGet

    Java

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/java-helloworld

    C#

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/csharp-helloworld

    Ruby

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_get

    PHP

    https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloGet

  2. 브라우저에서 해당 URL을 방문하면 Hello World! 메시지가 표시됩니다.

함수 삭제

함수를 삭제하려면 다음 명령어를 실행합니다.

Node.js

gcloud functions delete helloGET 

Python

gcloud functions delete hello_get 

Go

gcloud functions delete HelloGet 

Java

gcloud functions delete java-helloworld 

C#

gcloud functions delete csharp-helloworld 

Ruby

gcloud functions delete hello_get 

PHP

gcloud functions delete helloGet 

다음 단계

개발 환경을 설정하고, 처음부터 새 함수를 만들고, 종속 항목을 지정하고, 함수를 배포하고, 함수를 테스트하고, 로그를 보는 방법을 알아보려면 선택한 런타임에 대한 관련 첫 번째 함수가이드를 참조하세요. 이 가이드는 Cloud Functions(1세대)에만 적용됩니다.