Frontend proxying using Nginx Stay organized with collections Save and categorize content based on your preferences.
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:
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:
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
- 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.
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
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.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.createpermission.Learn how to grant roles.
Verify that billing is enabled for your Google Cloud project.
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
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.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.createpermission.Learn how to grant roles.
Verify that billing is enabled for your Google Cloud project.
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.enablepermission.Learn how to grant roles.- Install and initialize the gcloud CLI.
- Update Google Cloud CLI:
gcloud components update - Configure Google Cloud CLI:
gcloud init - Authenticate with Google Cloud CLI:
gcloud auth login
Permissions required to deploy
You must have ONE of the following:
- Both theCloud Run Admin andService Account User roles
- Any custom role that includes thisspecific list of permissions
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:
- Assign
nginxto listen at the same Cloud Run default port8080,located onlocalhost. - Apply gzip compression for performance enhancement.
- Instruct
proxy_passto 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
Go to theSecret Manager page of the Google Cloud console:
ClickCreate secret.
In the
nameform field, enternginx_config.Upload the
nginx.conffile located atmulti-container/hello-nginx-sample/nginx.confas the secret value.Keep the defaults (
Google-owned and Google-managed encryption key, etc).ClickCreate secret.
Grant the project compute service account access to this new secret. To do this, go to theIAM page in the Google Cloud console:
Locate the principal service account with name:
Compute Engine default service accountand clickEdit principal.ClickAdd another role and selectSecret Manager Secret Accessor.
ClickSave.
gcloud
In a terminal, use the following command to create a new
nginx_configsecret in Secret Manager:gcloudsecretscreatenginx_config--replication-policy='automatic'--data-file='./nginx.conf'
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'
Verify that your secret was created by running
gcloud 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
If you are creating a new service, skip this step.If you are updating an existing service, download itsYAML configuration:
gcloudrunservicesdescribeSERVICE--formatexport>service.yamlIn
service.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:8080Thenginx 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:8888Thehello 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.confSpecify 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.
Deploy the service
Console
Go to theCloud Run page in the Google Cloud console:
SelectServices from the menu, and clickDeploy container to display theCreate service form.
- SelectDeploy one revision from an existing container image and enter
nginxasContainer image URL. - In theService name field, supply a name for your service, for example,
hello-mc. - From theRegion list, select a location to deploy to, for example,
us-west1. - UnderAuthentication, selectAllow public access.If you don't have permissions (Cloud Run Admin role) to selectthis, the service will deploy and require authentication.
- SelectDeploy one revision from an existing container image and enter
ClickContainer(s), Volumes, Networking, Security to expand the configuration form.
- Click theVolumes tab.
- ClickAdd volume.
- From theVolume type list, selectSecret.
- In theVolume name field, enter
nginx-conf-secret. - In theSecret field, enternginx_config.
- UnderSpecified paths for secret versions, specifydefault.conf as the path andlatest as the version.
- ClickCreate to create the secret volume.
Click theContainers tab to display theEdit container form.
- ClickSettings, then underResources, change memory to256MiB and CPU to1 CPU.
- ClickVolume mounts.
- ClickMount volume.
- Selectnginx-conf-secret from the name list.
- ForMount path, enteretc/nginx/conf.d.
- ClickDone to complete configuration for the first container.
ClickAdd container to add the sidecar container and display theNew container form.
- Select the default container image URLus-docker.pkg.dev/cloudrun/container/hello
- Click theSettings tab, then underResources, change memory to256MiB and CPU to1 CPU.
- ClickVariables & Secrets.
- ClickAdd variable.
- EnterPORT as the new environment variable name and8888 as the value.
- ClickDone.
Navigate to theEdit container form for the first container (
nginx).- Click theSettings tab.
- UnderContainer start up order, select
nginxfrom theDepends on list. This means thenginxcontainer starts up only after thehellocontainer starts up successfully. - 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
In a terminal, clone the sample app repository to your local machine:
gitclonehttps://github.com/GoogleCloudPlatform/cloud-run-samples
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.