빠른 시작: Cloud Run에 C++ 서비스 배포

간단한 Hello World 애플리케이션을 만들고 컨테이너 이미지에 패키징하고 컨테이너 이미지를 Artifact Registry에 업로드한 다음 컨테이너 이미지를 Cloud Run에 배포하는 방법을 알아봅니다. 표시된 언어 외에 다른 언어도 사용할 수 있습니다.

시작하기 전에

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

    프로젝트 선택기로 이동

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

  4. Google Cloud CLI를 설치합니다.
  5. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

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

    프로젝트 선택기로 이동

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

  8. Google Cloud CLI를 설치합니다.
  9. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  10. Cloud Run 서비스의 기본 프로젝트를 설정하려면 다음 명령어를 실행합니다.
     gcloud config set project PROJECT_ID
    PROJECT_ID를 이 빠른 시작에서 만든 프로젝트 이름으로 바꿉니다.
  11. 프로젝트에서 인증되지 않은 호출을 제한하는 도메인 제한 조직 정책이 적용되는 경우 비공개 서비스 테스트의 설명대로 배포된 서비스에 액세스해야 합니다.

샘플 애플리케이션 작성

C++로 애플리케이션을 작성하려면 다음 안내를 따르세요.

  1. helloworld-cpp라는 새 디렉터리를 만들고 이 디렉터리로 이동합니다.

    mkdir helloworld-cpp
    cd helloworld-cpp
    
  2. CMakeLists.txt라는 새 파일을 만들고 이 파일에 다음 코드를 붙여넣습니다.

    cmake_minimum_required(VERSION 3.20)
    
    # Define the project name and where to report bugs.
    set(PACKAGE_BUGREPORT
        "https://github.com/GoogleCloudPlatform/cpp-samples/issues")
    project(cpp-samples-cloud-run-hello-world CXX)
    
    find_package(functions_framework_cpp REQUIRED)
    find_package(Threads)
    
    add_executable(cloud_run_hello cloud_run_hello.cc)
    target_compile_features(cloud_run_hello PRIVATE cxx_std_17)
    target_link_libraries(cloud_run_hello functions-framework-cpp::framework)
    
    include(GNUInstallDirs)
    install(TARGETS cloud_run_hello RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
  3. vcpkg.json라는 새 파일을 만들고 이 파일에 다음 코드를 붙여넣습니다.

    {
      "name": "cpp-samples-cloud-run-hello-world",
      "version-string": "unversioned",
      "homepage": "https://github.com/GoogleCloudPlatform/cpp-samples/",
      "description": [
        "Shows how to deploy a C++ application to Cloud Run."
      ],
      "dependencies": [
        "functions-framework-cpp"
      ]
    }
    
  4. cloud_run_hello.cc라는 새 파일을 만들고 이 파일에 다음 코드를 붙여넣습니다.

    #include <google/cloud/functions/framework.h>
    #include <cstdlib>
    
    namespace gcf = ::google::cloud::functions;
    
    auto hello_world_http() {
      return gcf::MakeFunction([](gcf::HttpRequest const& /*request*/) {
        std::string greeting = "Hello ";
        auto const* target = std::getenv("TARGET");
        greeting += target == nullptr ? "World" : target;
        greeting += "\n";
    
        return gcf::HttpResponse{}
            .set_header("Content-Type", "text/plain")
            .set_payload(greeting);
      });
    }
    
    int main(int argc, char* argv[]) {
      return gcf::Run(argc, argv, hello_world_http());
    }
    

    이 코드는 PORT 환경 변수로 정의된 포트를 리슨하는 기본 웹 서버를 만듭니다.

  5. 소스 파일과 동일한 디렉터리에 Dockerfile이라는 새 파일을 만듭니다. C++ Dockerfile은 PORT 환경 변수에서 정의한 포트를 리슨하는 애플리케이션을 시작합니다.

    # We chose Alpine to build the image because it has good support for creating
    # statically-linked, small programs.
    FROM alpine:3.19 AS build
    
    # Install the typical development tools for C++, and
    # the base OS headers and libraries.
    RUN apk update && \
        apk add \
            build-base \
            cmake \
            curl \
            git \
            gcc \
            g++ \
            libc-dev \
            linux-headers \
            ninja \
            pkgconfig \
            tar \
            unzip \
            zip
    
    # Use `vcpkg`, a package manager for C++, to install
    WORKDIR /usr/local/vcpkg
    ENV VCPKG_FORCE_SYSTEM_BINARIES=1
    RUN curl -sSL "https://github.com/Microsoft/vcpkg/archive/2024.03.25.tar.gz" | \
        tar --strip-components=1 -zxf - \
        && ./bootstrap-vcpkg.sh -disableMetrics
    
    # Copy the source code to /v/source and compile it.
    COPY . /v/source
    WORKDIR /v/source
    
    # Run the CMake configuration step, setting the options to create
    # a statically linked C++ program
    RUN cmake -S/v/source -B/v/binary -GNinja \
        -DCMAKE_TOOLCHAIN_FILE=/usr/local/vcpkg/scripts/buildsystems/vcpkg.cmake \
        -DCMAKE_BUILD_TYPE=Release
    
    # Compile the binary and strip it to reduce its size.
    RUN cmake --build /v/binary
    RUN strip /v/binary/cloud_run_hello
    
    # Create the final deployment image, using `scratch` (the empty Docker image)
    # as the starting point. Effectively we create an image that only contains
    # our program.
    FROM scratch AS cloud-run-hello
    WORKDIR /r
    
    # Copy the program from the previously created stage and the shared libraries it
    # depends on.
    COPY --from=build /v/binary/cloud_run_hello /r
    COPY --from=build /lib/ld-musl-x86_64.so.1 /lib/ld-musl-x86_64.so.1
    COPY --from=build /usr/lib/libstdc++.so.6 /usr/lib/libstdc++.so.6
    COPY --from=build /usr/lib/libgcc_s.so.1 /usr/lib/libgcc_s.so.1
    
    # Make the program the entry point.
    ENTRYPOINT [ "/r/cloud_run_hello" ]

앱이 완료되어 배포할 준비가 되었습니다.

소스에서 Cloud Run에 배포

중요: 이 빠른 시작에서는 빠른 시작에 사용 중인 프로젝트에 소유자 역할이나 편집자 역할이 있다고 가정합니다. 그렇지 않은 경우 필요한 권한은 Cloud Run 배포 권한, Cloud Build 권한, Artifact Registry 권한을 참조하세요.

Cloud Build를 사용하여 소스 코드에서 이미지를 만든 다음 배포합니다.

  1. 소스 디렉터리에서 Cloud Build를 사용하여 서비스의 Docker 이미지를 만듭니다.

    gcloud builds submit --machine-type=e2_highcpu_32 --tag gcr.io/PROJECT_ID/cloud-run-hello-world
  2. 다음 명령어를 사용하여 이미지를 배포합니다.

    gcloud run deploy --image=gcr.io/PROJECT_ID/cloud-run-hello-world

    API를 사용 설정하라는 메시지가 표시되면 y로 답하여 사용 설정합니다.

    1. 소스 코드 위치를 입력하라는 메시지가 표시되면 Enter 키를 눌러 현재 폴더를 배포합니다.

    2. 서비스 이름을 입력하라는 메시지가 표시되면 Enter 키를 눌러 기본 이름(예: helloworld)을 수락합니다.

    3. Artifact Registry API를 사용 설정하거나 Artifact Registry 저장소 만들기를 허용하라는 메시지가 표시되면 y를 눌러 응답합니다.

    4. 리전을 입력하라는 메시지가 표시되면 리전(예: us-central1)을 선택합니다.

    5. 인증되지 않은 호출 허용 메시지가 표시되면 y로 응답합니다.

    그런 다음 배포가 완료될 때까지 잠시 기다립니다. 성공하면 명령줄에 서비스 URL이 표시됩니다.

  3. 웹브라우저에서 서비스 URL을 열고 배포한 서비스로 이동합니다.

Cloud Run 위치

Cloud Run은 리전을 기반으로 합니다. 즉, Cloud Run 서비스를 실행하는 인프라가 특정 리전에 위치해 있으며 해당 리전 내의 모든 영역에서 중복으로 사용할 수 있도록 Google이 관리합니다.

Cloud Run 서비스를 실행하는 리전을 선택하는 데 있어 중요한 기준은 지연 시간, 가용성 또는 내구성 요구사항입니다. 일반적으로 사용자와 가장 가까운 리전을 선택할 수 있지만 Cloud Run 서비스에서 사용하는 다른 Google Cloud 제품 위치도 고려해야 합니다. 여러 위치에서 Google Cloud 제품을 함께 사용하면 서비스 지연 시간과 비용에 영향을 미칠 수 있습니다.

Cloud Run은 다음 리전에서 사용할 수 있습니다.

등급 1 가격 적용

  • asia-east1(타이완)
  • asia-northeast1(도쿄)
  • asia-northeast2(오사카)
  • europe-north1(핀란드) 잎 아이콘 낮은 CO2
  • europe-southwest1(마드리드)
  • europe-west1(벨기에) 잎 아이콘 낮은 CO2
  • europe-west4(네덜란드)
  • europe-west8(밀라노)
  • europe-west9(파리) 잎 아이콘 낮은 CO2
  • me-west1(텔아비브)
  • us-central1(아이오와) 잎 아이콘 낮은 CO2
  • us-east1(사우스캐롤라이나)
  • us-east4(북 버지니아)
  • us-east5(콜럼버스)
  • us-south1(댈러스)
  • us-west1(오리건) 잎 아이콘 낮은 CO2

등급 2 가격 적용

  • africa-south1(요하네스버그)
  • asia-east2(홍콩)
  • asia-northeast3(대한민국 서울)
  • asia-southeast1(싱가포르)
  • asia-southeast2 (자카르타)
  • asia-south1(인도 뭄바이)
  • asia-south2(인도 델리)
  • australia-southeast1(시드니)
  • australia-southeast2(멜버른)
  • europe-central2(폴란드 바르샤바)
  • europe-west10(베를린)
  • europe-west12(토리노)
  • europe-west2(영국 런던) 잎 아이콘 낮은 CO2
  • europe-west3(독일 프랑크푸르트) 잎 아이콘 낮은 CO2
  • europe-west6(스위스 취리히) 잎 아이콘 낮은 CO2
  • me-central1(도하)
  • me-central2(담맘)
  • northamerica-northeast1(몬트리올) 잎 아이콘 낮은 CO2
  • northamerica-northeast2(토론토) 잎 아이콘 낮은 CO2
  • southamerica-east1(브라질 상파울루) 잎 아이콘 낮은 CO2
  • southamerica-west1(칠레 산티아고) 잎 아이콘 낮은 CO2
  • us-west2(로스앤젤레스)
  • us-west3(솔트레이크시티)
  • us-west4(라스베이거스)

Cloud Run 서비스를 이미 만들었다면 Google Cloud 콘솔의 Cloud Run 대시보드에서 리전을 확인할 수 있습니다.

축하합니다. 소스 코드의 컨테이너 이미지를 Cloud Run으로 배포했습니다. Cloud Run은 수신된 요청을 처리하기 위해 컨테이너 이미지를 자동으로 수평 확장한 후 수요가 감소하면 수평 축소합니다. 요청 처리 도중 소비한 CPU, 메모리, 네트워킹에 대해서만 비용을 지불하면 됩니다.

삭제

테스트 프로젝트 삭제

Cloud Run에서는 서비스를 사용하지 않을 때 비용이 청구되지 않지만 Artifact Registry에 컨테이너 이미지를 저장하는 데 요금이 청구될 수 있습니다. 비용이 청구되지 않도록 컨테이너 이미지를 삭제하거나 Google Cloud 프로젝트를 삭제할 수 있습니다. Google Cloud 프로젝트를 삭제하면 프로젝트 내에서 사용되는 모든 리소스에 대한 비용 청구가 중지됩니다.

  1. Google Cloud 콘솔에서 리소스 관리 페이지로 이동합니다.

    리소스 관리로 이동

  2. 프로젝트 목록에서 삭제할 프로젝트를 선택하고 삭제를 클릭합니다.
  3. 대화상자에서 프로젝트 ID를 입력한 후 종료를 클릭하여 프로젝트를 삭제합니다.

다음 단계

코드 소스에서 컨테이너를 빌드하고 저장소로 푸시하는 방법에 대한 자세한 내용은 다음을 참조하세요.