快速入門:建構並部署 C++ 網頁應用程式至 Cloud Run

瞭解如何在 Cloud Run 使用單一指令,依據程式碼範例建構及部署「Hello World」網頁應用程式。 Google Cloud

只要按照本快速入門課程的步驟操作,Cloud Run 就會在您從原始碼部署時自動建構 Dockerfile。

事前準備

  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. Install the Google Cloud CLI.

  5. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  6. To initialize the gcloud CLI, run the following command:

    gcloud init
  7. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  8. Make sure that billing is enabled for your Google Cloud project.

  9. Install the Google Cloud CLI.

  10. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  11. To initialize the gcloud CLI, run the following command:

    gcloud init
  12. 如要為 Cloud Run 服務設定預設專案,請按照下列步驟操作:
     gcloud config set project PROJECT_ID
    請將 PROJECT_ID 替換為您的 Google Cloud 專案 ID。
  13. 如果您適用網域限制組織政策,且該政策限制專案的未經驗證叫用,您就必須按照「測試私人服務」一節的說明存取已部署的服務。

  14. 啟用 Cloud Run Admin API 和 Cloud Build API:

    gcloud services enable run.googleapis.com \
        cloudbuild.googleapis.com

    啟用 Cloud Run Admin API 後,系統會自動建立 Compute Engine 預設服務帳戶。

  15. 將下列 IAM 角色授予 Cloud Build 服務帳戶。

    按一下即可查看 Cloud Build 服務帳戶的必要角色

    除非您覆寫這項行為,否則 Cloud Build 會自動使用 Compute Engine 預設服務帳戶做為預設 Cloud Build 服務帳戶,以便建構您的原始碼和 Cloud Run 資源。如要讓 Cloud Build 建構來源,請要求管理員將 Cloud Run 建構工具 (roles/run.builder) 授予專案的 Compute Engine 預設服務帳戶:

      gcloud projects add-iam-policy-binding PROJECT_ID \
          --member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com \
          --role=roles/run.builder
      

    請將 PROJECT_NUMBER 替換為您的 Google Cloud專案編號,並將 PROJECT_ID 替換為您的 Google Cloud專案 ID。如需查看如何找出專案 ID 和專案編號的詳細操作說明,請參閱「建立及管理專案」。

    將 Cloud Run 建構工具角色授予 Compute Engine 預設服務帳戶後,需要幾分鐘的時間才能套用

編寫範例應用程式

如要使用 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.21 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.04.26.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 Run 資源所需的權限。

使用 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 鍵接受預設名稱,例如 helloworld

    2. 如果系統提示您在專案中啟用其他 API (例如 Artifact Registry API),請按下 y 回應。

    3. 系統提示時,請選取所需的地區,例如 europe-west1

    4. 如果系統提示您在指定區域建立存放區,請按下 y 回應。

    5. 如果系統提示您允許未經驗證的叫用,請回覆 y。如果有網域限制機構政策禁止顯示這項提示,您可能不會看到這項提示;詳情請參閱「開始前」一節。

    然後稍等片刻,等待部署成功。成功完成後,指令列會顯示服務網址。

  3. 在網路瀏覽器中開啟服務網址,以造訪您所部署的服務。

Cloud Run 位置

Cloud Run 具有「地區性」,這表示執行 Cloud Run 服務的基礎架構位於特定地區,並由 Google 代管,可為該地區內所有區域提供備援功能。

選擇 Cloud Run 服務的執行地區時,請將延遲時間、可用性或耐用性需求做為主要考量。一般而言,您可以選擇最靠近使用者的地區,但您應考量 Cloud Run 服務所使用的其他 Google Cloud產品位置。使用分散在不同位置的 Google Cloud 產品,可能會影響服務的延遲時間和費用。

Cloud Run 可在下列地區使用:

採用級別 1 定價

採用級別 2 定價

如果您已建立 Cloud Run 服務,即可在 Google Cloud 控制台的 Cloud Run 資訊主頁中查看地區。

清除所用資源

移除測試專案

雖然 Cloud Run 在服務未用時不會產生費用,但將容器映像檔儲存於 Artifact Registry 仍可能會產生費用。您可以刪除容器映像檔或刪除 Google Cloud 專案,以免產生費用。刪除 Google Cloud 專案後,系統就會停止對專案使用的所有資源收取費用。

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

後續步驟

如要進一步瞭解如何從程式碼來源建構容器,並推送至存放區,請參閱: