快速入门:将 C++ 服务部署到 Cloud Run

了解如何创建简单的 Hello World 应用,将该应用打包到容器映像中,然后将该容器映像上传到 Artifact Registry 并部署到 Cloud Run。除了所示语言之外,您还可以使用其他语言。

准备工作

  1. 登录您的 Google Cloud 账号。如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $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());
    }
    

    此代码会创建一个基本 Web 服务器,以侦听由 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

    然后等待部署完成。成功完成时,命令行会显示服务网址。

  3. 在 Web 浏览器中打开该服务网址,访问部署的服务。

Cloud Run 位置

Cloud Run 是区域级的,这意味着运行 Cloud Run 服务的基础架构位于特定区域,并且由 Google 代管,以便在该区域内的所有可用区以冗余方式提供。

选择用于运行 Cloud Run 服务的区域时,主要考虑该区域能否满足您的延迟时间、可用性或耐用性要求。通常,您可以选择距离用户最近的区域,但除此之外,您还应该考虑 Cloud Run 服务使用的其他 Google Cloud 产品的位置。跨多个位置使用 Google Cloud 产品可能会影响服务的延迟时间和费用。

Cloud Run 可在以下区域使用:

基于层级 1 价格

基于层级 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(英国伦敦) 叶形图标 二氧化碳排放量低
  • europe-west3(德国法兰克福) 叶形图标 二氧化碳排放量低
  • europe-west6(瑞士苏黎世) 叶形图标 二氧化碳排放量低
  • me-central1(多哈)
  • me-central2(达曼)
  • northamerica-northeast1(蒙特利尔) 叶形图标 二氧化碳排放量低
  • northamerica-northeast2(多伦多) 叶形图标 二氧化碳排放量低
  • southamerica-east1(巴西圣保罗) 叶形图标 二氧化碳排放量低
  • southamerica-west1(智利圣地亚哥) 叶形图标 二氧化碳排放量低
  • 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,然后点击关闭以删除项目。

后续步骤

如需详细了解如何使用代码源构建容器并推送到代码库,请参阅: