Frontend proxying using Nginx

This page shows how to use Nginx as a frontend proxy for your applicationcontainer. This is useful if you want to process requests or responses. You canadd gzip compression, or translate HTTP/2 to HTTP/1 if your applicationcontainers supports only HTTP/1 and you need to use HTTP/2 end-to-end forperformance reasons.

In the example provided in this page, anNginx containerruns on every Cloud Run instance as the main serving container, and itis configured to forward requests to the application container, which runs as asidecar container, as shown in this diagram:

Cloud Run mc hello nginx 1

The most effective way to do frontend proxying in Cloud Run is to deploy the Nginx serverproxy server container and the web app container as a single Cloud Run service:

Cloud Run mc hello nginx 2

This single Cloud Run service accepts requests and delivers them to the ingress (serving) container, whichin this case is the proxy server. The proxy server then sends requests to the web app over thelocalhost networkinterface, which avoids any external network.

Deploying as a single Cloud Run service reduces latencies, service management overhead, and eliminates exposureto external networks. Cloud Run does not directly interact with the sidecar containers, other than tostart or stop them whenever the service is started or stopped.

The web app container and any sidecar containers can be written in different programming languages. For a sample written inPHP, see thePHP nginx samplein GitHub.

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.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.create permission.Learn how to grant roles.
    Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.create permission.Learn how to grant roles.
    Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.

    Go to project selector

  5. Verify that billing is enabled for your Google Cloud project.

  6. Enable the Cloud Run and Secret Manager APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enable permission.Learn how to grant roles.

    Enable the APIs

  7. Install and initialize the gcloud CLI.
  8. Update Google Cloud CLI:gcloud components update
  9. Configure Google Cloud CLI:gcloud init
  10. Authenticate with Google Cloud CLI:gcloud auth login

Permissions required to deploy

You must have ONE of the following:

Configuration overview

These instructions use prebuilt container images, so the only thing required forfrontend proxying is to configure the containers and the service itself.

Configure the Nginx ingress container

The container image isnginxavailable at Docker Hub.It is mostly ready to use as is, except it needs to be configured to run as aproxy service, delivering the proxied requests to the port where the sidecar container islistening onlocalhost. The example on this page also enables gzip compression for requests and responses.

Configuration is provided using a text file mountedat/etc/nginx/conf.d/nginx.conf. Because you can't directly edit files in thecontainer, you must mount a volume at/etc/nginx/conf.d/ that containsthe configuration file. One way to mount a file at a specific location in acontainer running on Cloud Run is to store the file content in aSecret Manager secret, and mount that secret at the selected location.

Copy the following in a file namednginx.conf on the current directory of your local machine.

server{#Listenatport8080listen8080;#Serveratlocalhostserver_name_;#Enablesgzipcompressiontomakeourappfastergzipon;location/{#Passesinitialrequeststoport8080to`hello`containeratport8888proxy_passhttp://127.0.0.1:8888;}}

In the configuration, do the following:

  • Assignnginx to listen at the same Cloud Run default port8080,located onlocalhost.
  • Apply gzip compression for performance enhancement.
  • Instructproxy_pass to deliver any requests to this ingress container tothe web app sidecar container at localhost port8888.

Create a secret with the content of thenginx.conf file.

Console

  1. Go to theSecret Manager page of the Google Cloud console:

    Go to Secret Manager

  2. ClickCreate secret.

  3. In thename form field, enternginx_config.

  4. Upload thenginx.conf file located atmulti-container/hello-nginx-sample/nginx.conf as the secret value.

  5. Keep the defaults (Google-owned and Google-managed encryption key, etc).

  6. ClickCreate secret.

  7. Grant the project compute service account access to this new secret. To do this, go to theIAM page in the Google Cloud console:

    Go to IAM

  8. Locate the principal service account with name:Compute Engine default service account and clickEdit principal.

  9. ClickAdd another role and selectSecret Manager Secret Accessor.

  10. ClickSave.

gcloud

  1. In a terminal, use the following command to create a newnginx_config secret in Secret Manager:

    gcloudsecretscreatenginx_config--replication-policy='automatic'--data-file='./nginx.conf'

  2. Grant the project compute service account access to this new secret using the command

    exportPROJECT_NUMBER=$(gcloudprojectsdescribe$(gcloudconfigget-valueproject)--format='value(projectNumber)')gcloudsecretsadd-iam-policy-bindingnginx_config--member=serviceAccount:$PROJECT_NUMBER-compute@developer.gserviceaccount.com--role='roles/secretmanager.secretAccessor'

  3. Verify that your secret was created by runninggcloud secrets list.

About the web app sidecar sample image

These instructions use the sample container image atus-docker.pkg.dev/cloudrun/container/hello. You need tospecify the port number the container will listen on andlocalhost as the host, as described underSpecify sidecar container configuration, as described in the following sections.

Configure the multi-container service

You can use the Google Cloud console or theCloud Run YAML file to configure a Cloud Run servicewith more than one container.

In the service configuration, specify the Nginx proxy server as ingress (serving) container,the port it will listen on, whether it accepts HTTP 1 or HTTP 2 requests, and thecontainer start order. The ingress container (proxy server) depends on theweb app sidecar, so the web app sidecar must be started first.

These configurations are shown in the next few sections.

Add YAML metadata

Console

Navigate toDeploy the service for the full console instructions.

YAML

  1. If you are creating a new service, skip this step.If you are updating an existing service, download itsYAML configuration:

    gcloudrunservicesdescribeSERVICE--formatexport>service.yaml
  2. Inservice.yaml, add the following:

    metadata:name:"MC_SERVICE_NAME"labels:cloud.googleapis.com/location:"REGION"annotations:#RequiredtouseCloudRunmulti-containers(previewfeature)run.googleapis.com/launch-stage:BETArun.googleapis.com/description:sampletutorialservice#Externallyavailablerun.googleapis.com/ingress:all

The section describes the revision of the service, which includes properties that could vary from revision to revision.

Specify container start-up order

Console

Navigate toDeploy the service for the full console instructions.

YAML

Inservice.yaml, append the following:

spec:template:metadata:annotations:#Definescontainerstartuporderwithinmulti-containerservice.#Belowrequireshellocontainertospinupbeforenginxcontainer,#whichdependsonthehellocontainer.#https://cloud.google.com/run/docs/configuring/containers#container-orderingrun.googleapis.com/container-dependencies:"{nginx: [hello]}"

Note thecontainer-dependencies annotation that tells Cloud Run to wait for the hello container to start upbefore starting the nginx container. Otherwise, if the nginx container starts first, it could try to proxy a web request to the web app container that isn't ready, which would generate web error responses.

Each container can optionally have a name property defined for it, that can be used to refer to it in other directives.The serving container runs the proxy server, namednginx. This is the container that Cloud Run delivers incoming requests toso you must specify the version ofHTTP and container port to deliver them to.

Specify serving container configuration

Console

Navigate toDeploy the service for the full console instructions.

YAML

Inservice.yaml file, append the following:

spec:containers:#A)Servingingresscontainer"nginx"listeningatPORT8080#Mainentrypointofmulti-containerservice.#Sourceisstoredinnginx_configsecretinSecretManager.#AnypingstothiscontainerwillproxyovertohellocontaineratPORT8888.#https://cloud.google.com/run/docs/container-contract#port-image:nginxname:nginxports:-name:http1containerPort:8080resources:limits:cpu:500mmemory:256Mi#Referencingdeclaredvolumebelow,#Declaringvolumetomountincurrentingresscontainer'sfilesystem#https://cloud.google.com/run/docs/reference/rest/v2/Container#volumemountvolumeMounts:-name:nginx-conf-secretreadOnly:truemountPath:/etc/nginx/conf.d/startupProbe:timeoutSeconds:240periodSeconds:240failureThreshold:1tcpSocket:port:8080

Thenginx server requires a configuration file in the/etc/nginx/conf.d/ directory. To do this, mount a volume containing the file at that location. ThevolumeMount section specifies a volume calledconfiguration to be placed there. The volume itself is defined in its own section later in the file.

Specify sidecar container configuration

Console

Navigate toDeploy the service for the full console instructions.

YAML

Inservice.yaml, append the following:

-image:us-docker.pkg.dev/cloudrun/container/helloname:helloenv:-name:PORTvalue:"8888"resources:limits:cpu:1000mmemory:512MistartupProbe:timeoutSeconds:240periodSeconds:240failureThreshold:1tcpSocket:port:8888

Thehello application also needs configuration information. It listens for incoming requests at the port specified in thePORT environment variable. That name and value are specified in theenv section.

Specify the secret volume

Console

Navigate toDeploy the service for the full console instructions.

YAML

Inservice.yaml file, append the following:

volumes:-name:nginx-conf-secretsecret:secretName:nginx_configitems:-key:latestpath:default.conf

Specify the configurationvolume mounted in thevolumeMount section. It contains a single file callednginx.conf whose contents are definedas the value of the secret namednginx-conf-secret.

Note: For another example that deploys multiple containers, see the sidecars section of thedeployment page.

Deploy the service

Console

  1. Go to theCloud Run page in the Google Cloud console:

    Go to Cloud Run

  2. SelectServices from the menu, and clickDeploy container to display theCreate service form.

    1. SelectDeploy one revision from an existing container image and enternginx asContainer image URL.
    2. In theService name field, supply a name for your service, for example,hello-mc.
    3. From theRegion list, select a location to deploy to, for example,us-west1.
    4. UnderAuthentication, selectAllow public access.If you don't have permissions (Cloud Run Admin role) to selectthis, the service will deploy and require authentication.
  3. ClickContainer(s), Volumes, Networking, Security to expand the configuration form.

    1. Click theVolumes tab.
    2. ClickAdd volume.
    3. From theVolume type list, selectSecret.
    4. In theVolume name field, enternginx-conf-secret.
    5. In theSecret field, enternginx_config.
    6. UnderSpecified paths for secret versions, specifydefault.conf as the path andlatest as the version.
    7. ClickCreate to create the secret volume.
  4. Click theContainers tab to display theEdit container form.

    1. ClickSettings, then underResources, change memory to256MiB and CPU to1 CPU.
    2. ClickVolume mounts.
    3. ClickMount volume.
    4. Selectnginx-conf-secret from the name list.
    5. ForMount path, enteretc/nginx/conf.d.
    6. ClickDone to complete configuration for the first container.
  5. ClickAdd container to add the sidecar container and display theNew container form.

    1. Select the default container image URLus-docker.pkg.dev/cloudrun/container/hello
    2. Click theSettings tab, then underResources, change memory to256MiB and CPU to1 CPU.
    3. ClickVariables & Secrets.
    4. ClickAdd variable.
    5. EnterPORT as the new environment variable name and8888 as the value.
    6. ClickDone.
  6. Navigate to theEdit container form for the first container (nginx).

    1. Click theSettings tab.
    2. UnderContainer start up order, selectnginx from theDepends on list. This means thenginx container starts up only after thehello container starts up successfully.
    3. ClickCreate and wait for your service to deploy.

YAML

To deploy the proxy server container and web app container as a single service:

gcloudrunservicesreplaceservice.yaml

Verify the deployed service

To verify successful deployment copy the generated Cloud Run URLand open it in a browser, or use this command to send an authenticated request:

curl--header"Authorization: Bearer$(gcloudauthprint-identity-token)"SERVICE_URL

You should be greeted with a nginx proxy thathas successfully ported to the hello sidecar container with response status200.

Try this yourself

To follow along with this tutorial:

gcloud

  1. In a terminal, clone the sample app repository to your local machine:

    gitclonehttps://github.com/GoogleCloudPlatform/cloud-run-samples

  2. Change to the directory that contains the Cloud Run sample code:

    cdcloud-run-samples/multi-container/hello-nginx-sample/

What's next

To explore more about using sidecars in a Cloud Run service:

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-17 UTC.