Stay organized with collections Save and categorize content based on your preferences.

Deploy a C++ service to Cloud Run

Learn how to create a simple Hello World application, package it into a container image, upload the container image to Container Registry, and then deploy the container image to Cloud Run. You can use other languages in addition to the ones shown.

Before you begin

  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 Cloud project. Learn how to check if billing is enabled on a project.

  4. Install and initialize the Google Cloud CLI.
  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project.

  7. Install and initialize the Google Cloud CLI.
    1. To set the default project for your Cloud Run service:
       gcloud config set project PROJECT_ID
      Replace PROJECT_ID with the name of the project you created for this quickstart.

Write the sample application

To write an application in C++:

  1. Create a new directory named helloworld-cpp and change directory into it:

    mkdir helloworld-cpp
    cd helloworld-cpp
    
  2. Create a new file named CMakeLists.txt and paste the following code into it:

    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. Create a new file named vcpkg.json and paste the following code into it:

    {
      "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. Create a new file named cloud_run_hello.cc and paste the following code into it:

    #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());
    }
    

    This code creates a basic web server that listens on the port defined by the PORT environment variable.

  5. Create a new file named Dockerfile in the same directory as the source files. The C++ Dockerfile starts the application listening on the port defined by the PORT environment variable:

    # We chose Alpine to build the image because it has good support for creating
    # statically-linked, small programs.
    FROM alpine:3.16 AS base
    
    # Create separate targets for each phase, this allows us to cache intermediate
    # stages when using Google Cloud Build, and makes the final deployment stage
    # small as it contains only what is needed.
    FROM base AS devtools
    
    # 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/2022.09.27.tar.gz" | \
        tar --strip-components=1 -zxf - \
        && ./bootstrap-vcpkg.sh -disableMetrics
    
    # Copy the source code to /v/source and compile it.
    FROM devtools AS build
    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" ]

Your app is finished and ready to be deployed.

Deploy to Cloud Run from source

Important: This quickstart assumes that you have owner or editor roles in the project you are using for the quickstart. Otherwise, refer to Cloud Run deployment permissions, Cloud Build permissions, and Artifact Registry permissions for the permissions required.

Use Cloud Build to create an image from the source code, and then deploy it.

  1. In the source directory, use Cloud Build to create a docker image for your service

    gcloud builds submit --machine-type=e2_highcpu_32 --tag gcr.io/PROJECT_ID/cloud-run-hello-world
  2. Deploy the image using the following command:

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

    If prompted to enable the API, Reply y to enable.

    1. When you are prompted for the source code location, press Enter to deploy the current folder.

    2. When you are prompted for the service name, press Enter to accept the default name, helloworld.

    3. If you are prompted to enable the Artifact Registry API, respond by pressing y.

    4. When you are prompted for region: select the region of your choice, for example us-central1.

    5. You will be prompted to allow unauthenticated invocations: respond y .

    Then wait a few moments until the deployment is complete. On success, the command line displays the service URL.

  3. Visit your deployed service by opening the service URL in a web browser.

Cloud Run locations

Cloud Run is regional, which means the infrastructure that runs your Cloud Run services is located in a specific region and is managed by Google to be redundantly available across all the zones within that region.

Meeting your latency, availability, or durability requirements are primary factors for selecting the region where your Cloud Run services are run. You can generally select the region nearest to your users but you should consider the location of the other Google Cloud products that are used by your Cloud Run service. Using Google Cloud products together across multiple locations can affect your service's latency as well as cost.

Cloud Run is available in the following regions:

Subject to Tier 1 pricing

  • asia-east1 (Taiwan)
  • asia-northeast1 (Tokyo)
  • asia-northeast2 (Osaka)
  • europe-north1 (Finland) leaf icon Low CO2
  • europe-southwest1 (Madrid) leaf icon Low CO2
  • europe-west1 (Belgium) leaf icon Low CO2
  • europe-west4 (Netherlands)
  • europe-west8 (Milan)
  • europe-west9 (Paris) leaf icon Low CO2
  • me-west1 (Israel)
  • us-central1 (Iowa) leaf icon Low CO2
  • us-east1 (South Carolina)
  • us-east4 (Northern Virginia)
  • us-east5 (Columbus)
  • us-south1 (Dallas)
  • us-west1 (Oregon) leaf icon Low CO2

Subject to Tier 2 pricing

  • asia-east2 (Hong Kong)
  • asia-northeast3 (Seoul, South Korea)
  • asia-southeast1 (Singapore)
  • asia-southeast2 (Jakarta)
  • asia-south1 (Mumbai, India)
  • asia-south2 (Delhi, India)
  • australia-southeast1 (Sydney)
  • australia-southeast2 (Melbourne)
  • europe-central2 (Warsaw, Poland)
  • europe-west2 (London, UK)
  • europe-west3 (Frankfurt, Germany)
  • europe-west6 (Zurich, Switzerland) leaf icon Low CO2
  • northamerica-northeast1 (Montreal) leaf icon Low CO2
  • northamerica-northeast2 (Toronto) leaf icon Low CO2
  • southamerica-east1 (Sao Paulo, Brazil) leaf icon Low CO2
  • southamerica-west1 (Santiago, Chile)
  • us-west2 (Los Angeles)
  • us-west3 (Salt Lake City)
  • us-west4 (Las Vegas)

If you already created a Cloud Run service, you can view the region in the Cloud Run dashboard in the Google Cloud console.

Congratulations! You have just deployed a container image from source code to Cloud Run. Cloud Run automatically and horizontally scales out your container image to handle the received requests, then scales in when demand decreases. You only pay for the CPU, memory, and networking consumed during request handling.

Clean up

Remove your test project

While Cloud Run does not charge when the service is not in use, you might still be charged for storing the container image in Artifact Registry. You can delete your container image or delete your Cloud project to avoid incurring charges. Deleting your Cloud project stops billing for all the resources used within that project.

  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.

What's next

For more information on building a container from code source and pushing to a repository, see: