クイックスタート: C++ ウェブアプリをビルドして Cloud Run にデプロイする

Cloud Run を使用して、コードサンプルから Google Cloudへ 1 つのコマンドで「Hello World」ウェブ アプリケーションをビルドしてデプロイする方法について学習します。

このクイックスタートの手順に沿って、ソースコードからデプロイすると、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. Verify that billing is enabled for your Google Cloud project.

  4. Install the Google Cloud CLI.

  5. 外部 ID プロバイダ(IdP)を使用している場合は、まずフェデレーション ID を使用して gcloud CLI にログインする必要があります。

  6. gcloud CLI を初期化するには、次のコマンドを実行します。

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

  9. Install the Google Cloud CLI.

  10. 外部 ID プロバイダ(IdP)を使用している場合は、まずフェデレーション ID を使用して gcloud CLI にログインする必要があります。

  11. gcloud CLI を初期化するには、次のコマンドを実行します。

    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. Cloud Build サービス アカウントに次の IAM ロールを付与します。

    クリックして Cloud Build サービス アカウントに必要なロールを表示

    この動作をオーバーライドしない限り、Cloud Build は、ソースコードと Cloud Run リソースのビルドにデフォルトの Cloud Build サービス アカウントとして Compute Engine のデフォルトのサービス アカウントを自動的に使用します。Cloud Build がソースをビルドできるようにするには、プロジェクトの Compute Engine のデフォルトのサービス アカウントに Cloud Run ビルダーroles/run.builder)を付与するよう管理者に依頼します。

      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 とプロジェクト番号を確認する方法については、プロジェクトの作成と管理をご覧ください。

    Compute Engine のデフォルト サービス アカウントに Cloud Run ビルダーのロールを付与すると、反映されるまでに数分かかることがあります。

  16. Cloud Run の料金を確認するか、料金計算ツールで費用を見積もります。
  17. サンプル アプリケーションを作成する

    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」と応答します。ドメイン制限の組織のポリシーが原因でこのメッセージが表示されない場合があります。詳細については、始める前にのセクションをご覧ください。

      デプロイが完了するまで少しお待ちください。正常に完了すると、コマンドラインにサービス 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(大阪)
    • asia-south1(ムンバイ、インド)
    • europe-north1(フィンランド) リーフアイコン 低 CO2
    • europe-north2(ストックホルム) リーフアイコン 低 CO2
    • europe-southwest1(マドリッド) リーフアイコン 低 CO2
    • europe-west1(ベルギー) リーフアイコン 低 CO2
    • europe-west4(オランダ) リーフアイコン 低 CO2
    • europe-west8(ミラノ)
    • europe-west9(パリ) リーフアイコン 低 CO2
    • me-west1(テルアビブ)
    • northamerica-south1(メキシコ)
    • us-central1(アイオワ) リーフアイコン 低 CO2
    • us-east1(サウスカロライナ)
    • us-east4(北バージニア)
    • us-east5(コロンバス)
    • us-south1(ダラス) リーフアイコン 低 CO2
    • us-west1(オレゴン) リーフアイコン 低 CO2

    ティア 2 料金を適用

    • africa-south1(ヨハネスブルグ)
    • asia-east2(香港)
    • asia-northeast3(ソウル、韓国)
    • asia-southeast1(シンガポール)
    • asia-southeast2 (ジャカルタ)
    • asia-south2(デリー、インド)
    • australia-southeast1(シドニー)
    • australia-southeast2(メルボルン)
    • europe-central2(ワルシャワ、ポーランド)
    • europe-west10(ベルリン) リーフアイコン 低 CO2
    • europe-west12(トリノ)
    • europe-west2(ロンドン、イギリス) リーフアイコン 低 CO2
    • europe-west3(フランクフルト、ドイツ)
    • 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 ダッシュボードにリージョンが表示されます。

    クリーンアップ

    Google Cloud アカウントに追加料金が課されるのを回避するには、このクイックスタートでデプロイしたリソースをすべて削除します。

    リポジトリを削除する

    デプロイしたサービスが使用されていない場合、Cloud Run の料金は発生しません。ただし、コンテナ イメージを Artifact Registry に保存した場合にも料金が発生する場合があります。Artifact Registry リポジトリを削除するには、Artifact Registry ドキュメントのリポジトリを削除するの手順を行います。

    サービスを削除する

    Cloud Run サービスの費用は、リクエストを受け取るまでは発生しません。 Cloud Run サービスを削除するには、次のいずれかの手順を行います。

    コンソール

    サービスを削除するには:

    1. Google Cloud コンソールで Cloud Run に移動します。

      Cloud Run に移動

    2. 削除するサービスをサービスリストで探し、そのチェックボックスをクリックして選択します。

    3. [削除] をクリックします。これにより、サービスのすべてのリビジョンが削除されます。

    gcloud

    サービスを削除するには、次のコマンドを実行します。

    gcloud run services delete SERVICE --region REGION

    次のように置き換えます。

    • SERVICE: 実際のサービスの名前。
    • REGION: サービスの Google Cloud リージョン。

    テスト プロジェクトを削除する

    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.

    次のステップ

    コードソースからコンテナをビルドし、リポジトリに push する方法については、以下をご覧ください。