Set up a classic Application Load Balancer with Cloud Run, App Engine, or Cloud Run functions

This page shows you how to create anexternal Application Load Balancerto route requests toserverless backends. Here the term serverless refers tothe following serverless compute products:

  • App Engine
  • Cloud Run functions
  • Cloud Run

Serverless NEGsallow you to useGoogle Cloud serverless appswithexternal Application Load Balancers. After youconfigure a load balancer with the serverless NEG backend, requests to the loadbalancer are routed to the serverless app backend.

To learn more about serverless NEGs, read theServerless NEGsoverview.

Before you begin

  1. Deploy an App Engine, Cloud Run functions, or Cloud Run service.
  2. If you haven't already done so, install the Google Cloud CLI.
  3. Configure permissions.
  4. Add an SSL certificate resource.

Deploy an App Engine, Cloud Run functions, or Cloud Run service

The instructions on this page assume you already have aCloud Run, Cloud Run functions,or App Engine service running.

For the example on this page, we have used theCloud Run Pythonquickstart to deploy a Cloud Runservice in theus-central1 region. The rest of this page shows you how to setup an external Application Load Balancer that uses a serverless NEG backend to route requests tothis service.

If you haven't already deployed a serverless app, or if you want to try aserverless NEG with a sample app, use one of the following quickstarts. You cancreate a serverless app in any region, but you must use thesame region lateron to create the serverless NEG and load balancer.

Cloud Run

To create a simple Hello World application, package it into a container image,and then deploy the container image to Cloud Run, seeQuickstart: Build and Deploy.

If you already have a sample container uploaded to the Container Registry, seeQuickstart: Deploy a Prebuilt Sample Container.

Cloud Run functions

SeeCloud Run functions: Python Quickstart.

App Engine

See the following App Engine quickstart guides for Python 3:

Install the Google Cloud CLI

Install the Google Cloud CLI. Seegcloud Overview forconceptual and installation information about the tool.

If you haven't run the gcloud CLI previously, first rungcloud init to initialize your gcloud directory.

Configure permissions

To follow this guide, you need to create a serverless NEG and create an externalHTTP(S) load balancer in a project. You should be either a projectowner oreditor, or you should have the followingCompute Engine IAM roles:

TaskRequired Role
Create load balancer and networking componentsNetwork Admin
Create and modify NEGsCompute Instance Admin
Create and modify SSL certificatesSecurity Admin

Optional: Use BYOIP addresses

With bring your own IP (BYOIP), you can import your own public addresses toGoogle Cloud to use the addresses with Google Cloud resources. Forexample, if you import your own IPv4 addresses, you can assign one to theforwarding rule when you configure your load balancer. When you follow theinstructions in this document tocreate the load balancer, provide the BYOIP address as theIP address.

For more information about using BYOIP, seeBring your own IP addresses.

Reserve an external IP address

Now that your services are up and running, set up aglobal static external IPaddress that your customers useto reach your load balancer.

Note: This step is required for this example, and recommended in general,because a static external IP address provides a single address to point yourserverless app to. Reserving an IP address is also essential if you are using acustom domain for your serverless app (also required for Google-managed SSLcertificates). With a custom domain, you will need to update your DNS recordsto point your domain to this IP address.

Console

  1. In the Google Cloud console, go to theExternal IP addresses page.

    Go to External IP addresses

  2. ClickReserve external static IP address.

  3. ForName, enterexample-ip.

  4. ForNetwork service tier, selectPremium.

  5. ForIP version, selectIPv4.

  6. ForType, selectGlobal.

  7. ClickReserve.

gcloud

gcloud compute addresses createEXAMPLE_IP \    --network-tier=PREMIUM \    --ip-version=IPV4 \    --global

Note the IPv4 address that was reserved:

gcloud compute addresses describeEXAMPLE_IP \    --format="get(address)" \    --global

ReplaceEXAMPLE_IP with the name of the IP address.

Create an SSL certificate resource

To create anHTTPS load balancer, you must add an SSL certificateresource to the load balancer's front end. Create an SSL certificate resourceusing either aGoogle-managed SSLcertificateor aself-managed SSL certificate.

  • Google-managed certificates. Using Google-managed certificates isrecommended because Google Cloud obtains, manages, and renews thesecertificates automatically. To create a Google-managed certificate,you must have a domain and the DNS records for that domain in order forthe certificate to be provisioned.

    Additionally, you need to update the domain's DNS A record to point tothe load balancer's IP address created in the previous step.If you have multiple domains in a Google-managed certificate, you mustupdate DNS records for all the domains and subdomains to point to your loadbalancer's IP address. For detailed instructions, seeUsing Google-managedcertificates.

  • Self-signed certificates. If you do not want to set up a domain at thistime, you can use a self-signed SSL certificate for testing.

Warning: Don't use a self-signed certificate for production purposes.

This example assumes that you have already created an SSL certificate resource.

If you want to test this process without creating an SSL certificateresource (or a domain as required by Google-managed certificates), youcan still use the instructions on this page to set up an HTTP loadbalancer instead.

Create the load balancer

In the following diagram, the load balancer uses a serverless NEG backendto direct requests to a serverless Cloud Run service. For thisexample, we have used theCloud Run Pythonquickstart to deploy a Cloud Run service.

External Application Load Balancer architecture for a Cloud Run application.
External Application Load Balancer architecture for a Cloud Run application (click to enlarge).

Because health checks are not supported for backend services with serverless NEGbackends, you don't need to create a firewall rule allowing health checksif the load balancer has only serverless NEG backends.

Console

Select the load balancer type

  1. In the Google Cloud console, go to theLoad balancing page.

    Go to Load balancing

  2. ClickCreate load balancer.
  3. ForType of load balancer, selectApplication Load Balancer (HTTP/HTTPS) and clickNext.
  4. ForPublic facing or internal, selectPublic facing (external) and clickNext.
  5. ForGlobal or single region deployment, selectBest for global workloads and clickNext.
  6. ForLoad balancer generation, selectClassic Application Load Balancer and clickNext.
  7. ClickConfigure.

Basic configuration

  1. For the name of the load balancer, enterserverless-lb.
  2. Keep the window open to continue.

Frontend configuration

  1. ClickFrontend configuration.
  2. ForName, enter a name.
  3. To create an HTTPS load balancer, you must have anSSL certificate (gcloud compute ssl-certificates list).

    We recommend using a Google-managed certificate as describedpreviously.

  4. To configure an external Application Load Balancer, fill in the fields as follows.

    Verify the following options are configured with these values:

    PropertyValue (type a value or select an option as specified)
    ProtocolHTTPS
    Network Service TierPremium
    IP versionIPv4
    IP addressexample-ip
    Port443
    CertificateSelect an existing SSL certificate or create a new certificate.

    To create an HTTPS load balancer, you must have anSSL certificate resource to use in the HTTPS proxy. You can create an SSL certificate resource using either a Google-managed SSL certificate or a self-managed SSL certificate.
    To create a Google-managed certificate, you must have a domain. The domain's A record must resolve to the load balancer IP address that you created earlier in this procedure. Using Google-managed certificates is recommended because Google Cloud obtains, manages, and renews these certificates automatically. If you do not have a domain, you can use a self-signed SSL certificate for testing.
    Optional: Enable HTTP to HTTPS Redirect Use this checkbox to enable HTTP to HTTPS redirects.

    Enabling this checkbox creates an additional partial HTTP load balancer that uses the same IP address as your HTTPS load balancer and redirects HTTP requests to your load balancer's HTTPS frontend.

    This checkbox can only be selected when the HTTPS protocol is selected and a reserved IP address is used.

    If you want to test this process without setting up an SSL certificate resource (or a domain as required by Google-managed certificates), you can set up an HTTP load balancer.

    To create an HTTP load balancer, verify that the following options are configured with these values:

    PropertyValue (type a value or select an option as specified)
    ProtocolHTTP
    Network Service TierPremium
    IP versionIPv4
    IP addressexample-ip
    Port80
  5. ClickDone.

Backend configuration

  1. ClickBackend configuration.
  2. In theBackend services & backend buckets list, clickCreate a backend service.
  3. ForName, enter a name.
  4. InBackend type, selectServerless network endpoint group.
  5. LeaveProtocol unchanged. This parameter is ignored.
  6. In theBackends section, forNew backend, selectCreate Serverless network endpoint group.
  7. ForName, enter a name.
  8. InRegion, selectus-central1, and then selectCloud Run.
  9. SelectSelect service name.
  10. In theService list, select theCloud Run service that you want to create a load balancer for.
  11. ClickCreate.
  12. In theNew backend section, clickDone.
  13. ClickCreate.

Routing rules

Routing rules determine how your traffic is directed. To configure routing, you'll set up host rules and path matchers, which are configuration components of an external Application Load Balancer'sURL map.

  1. ClickHost and path rules.

  2. Retain the default hosts and paths. For this example, all requests go to the backend service created in the previous step.

Reviewing the configuration

  1. ClickReview and finalize.
  2. Review all the settings.
  3. Optional: ClickEquivalent Code to view the REST API request that will be used to create the load balancer.
  4. ClickCreate.
  5. Wait for the load balancer to be created.
  6. Click the name of the load balancer (serverless-lb).
  7. Note the IP address of the load balancer for the next task. It's referred to asIP_ADDRESS.
When you use the Google Cloud console to create an HTTP(S) load balancer with a serverless NEG backend, logging is enabled by default. You can use thegcloud compute backend-services update command to disable logging if needed.

gcloud

  1. Create a serverless NEG for your serverless app.

    To create a serverless NEG with a Cloud Run service:

       gcloud compute network-endpoint-groups createSERVERLESS_NEG_NAME \       --region=us-central1 \       --network-endpoint-type=serverless  \       --cloud-run-service=CLOUD_RUN_SERVICE_NAME
    For more options, see thegcloud reference guide forgcloud compute network-endpoint-groups create.
  2. Create a backend service.
       gcloud compute backend-services createBACKEND_SERVICE_NAME \       --load-balancing-scheme=EXTERNAL \       --global
  3. Add the serverless NEG as a backend to the backend service:
       gcloud compute backend-services add-backendBACKEND_SERVICE_NAME \       --global \       --network-endpoint-group=SERVERLESS_NEG_NAME \       --network-endpoint-group-region=us-central1
  4. Create a URL map to route incoming requests to the backend service:
       gcloud compute url-maps createURL_MAP_NAME \       --default-serviceBACKEND_SERVICE_NAME

    This example URL map only targets one backend service representing a single serverless app, so we don't need to set up host rules or path matchers. If you have more than one backend service, you can use host rules to direct requests to different services based on the host name, and you can set up path matchers to direct requests to different services based on the request path.

  5. Perform this step only if you want to create an HTTPS load balancer. This is not required for HTTP load balancers. To create an HTTPS load balancer, you must have anSSL certificate resource to use in the HTTPS target proxy. You can create an SSL certificate resource using either a Google-managed SSL certificate or a self-managed SSL certificate. Using Google-managed certificates is recommended because Google Cloud obtains, manages, and renews these certificates automatically.

    To create a Google-managed certificate, you must have a domain. If you do not have a domain, you can use a self-signed SSL certificate for testing.

    To create a Google-managed SSL certificate resource:
       gcloud compute ssl-certificates createSSL_CERTIFICATE_NAME \       --domainsDOMAIN
    To create a self-managed SSL certificate resource:
       gcloud compute ssl-certificates createSSL_CERTIFICATE_NAME \       --certificateCRT_FILE_PATH \       --private-keyKEY_FILE_PATH
  6. Create a target HTTP(S) proxy to route requests to your URL map.

    For an HTTP load balancer, create an HTTP target proxy:

       gcloud compute target-http-proxies createTARGET_HTTP_PROXY_NAME \       --url-map=URL_MAP_NAME

    For an HTTPS load balancer, create an HTTPS target proxy. The proxy is the portion of the load balancer that holds the SSL certificate for HTTPS Load Balancing, so you also load your certificate in this step.

       gcloud compute target-https-proxies createTARGET_HTTPS_PROXY_NAME \      --ssl-certificates=SSL_CERTIFICATE_NAME \      --url-map=URL_MAP_NAME
  7. Create a forwarding rule to route incoming requests to the proxy.

    For an HTTP load balancer:

       gcloud compute forwarding-rules createHTTP_FORWARDING_RULE_NAME \       --load-balancing-scheme=EXTERNAL \       --network-tier=PREMIUM \       --address=EXAMPLE_IP \       --target-http-proxy=TARGET_HTTP_PROXY_NAME \       --global \       --ports=80

    For an HTTPS load balancer:

       gcloud compute forwarding-rules createHTTPS_FORWARDING_RULE_NAME \       --load-balancing-scheme=EXTERNAL \       --network-tier=PREMIUM \       --address=EXAMPLE_IP \       --target-https-proxy=TARGET_HTTPS_PROXY_NAME \       --global \       --ports=443

Connect your domain to your load balancer

After the load balancer is created, note the IP address that is associated withthe load balancer—for example,30.90.80.100. To point your domain to yourload balancer, create anA record by using your domain registration service. Ifyou added multiple domains to your SSL certificate, you must add anA recordfor each one, all pointing to the load balancer's IP address. For example, tocreateA records forwww.example.com andexample.com, use the following:

NAME                  TYPE     DATAwww                   A        30.90.80.100@                     A        30.90.80.100

If you use Cloud DNS as your DNS provider, seeAdd, modify, and delete records.

Test the load balancer

Now that you have configured your load balancer, you can start sendingtraffic to the load balancer's IP address. If you configured a domain, you cansend traffic to the domain name as well. However, DNS propagation can take timeto complete so you can start by using the IP address for testing.

  1. In the Google Cloud console, go to theLoad balancing page.

    Go to Load balancing

  2. Click on the load balancer you just created.

  3. Note theIP Address of the load balancer.

  4. For anHTTP load balancer, you can test your load balancerusing a web browser by going tohttp://IP_ADDRESS.ReplaceIP_ADDRESS with theload balancer's IP address. You should be directed to thehelloworld service homepage.

  5. For anHTTPS load balancer, you can test your load balancerusing a web browser by going tohttps://IP_ADDRESS.ReplaceIP_ADDRESS with theload balancer's IP address. You should be directed to thehelloworld service homepage.
    If that does not work and you are using a Google-managed certificate,confirm that your certificate resource's status is ACTIVE. For moreinformation, seeGoogle-managed SSL certificate resourcestatus.
    If you used a self-signed certificate for testing, your browser displaysa warning. You must explicitly instruct your browser to accept aself-signed certificate. Click through the warning to see the actual page.

Restrict ingress on default endpoint

Without the proper ingress settings, users can use your serverless application'sdefault URL to bypass the load balancer, Cloud Armor securitypolicies, SSL certificates, and private keys that are passed through the loadbalancer.

Ensure external traffic only reaches your serverless application from the loadbalancer by using setting ingress to "Internal and Cloud Load Balancing".

Additionally, you candisable the default URLfor Cloud Run.

Additional configuration options

This section expands on the configuration example to provide alternative andadditional configuration options. All of the tasks are optional. You can performthem in any order.

Set up multi-region load balancing

Note: For serverless NEGs, multi-region load balancing is supported only if theserverless NEG points to a Cloud Run or aCloud Run functions service. Multi-region load balancing with outlierdetection isn't supported with App Engine because you can't deploy aproject's App Engine in multiple regions.

In the example described earlier on this page, we have only oneCloud Run service serving as the backend in theus-central1 region. Because the serverless NEG can point to only one endpointat a time, load balancing is not performed across multiple regions. Theexternal Application Load Balancer serves as the frontend only, and it proxies traffic to thespecifiedhelloworld app endpoint. However, you might want to serve yourCloud Run app from more than one region to improve end-user latency.

If a backend service has several serverless NEGs attached to it, the loadbalancer balances traffic by forwarding requests to the serverless NEG in theclosest available region. However, backend services can only contain oneserverless NEGper region. To make your Cloud Runservice available from multiple regions, you need to set up cross-regionrouting. You should be able to use a single URL scheme that works anywhere inthe world, yet serves user requests from the region closest to the user.

To set up multi-region serving, you will need to use the Premium network tier toensure that all the regional Cloud Run deployments are compatibleand ready to serve traffic from any region.

To set up a multi-region load balancer:

  1. Set up two Cloud Run services in different regions. Let's assumethat you have deployed two Cloud Run services: one to a region inthe US, and another to a region in Europe.
  2. Create an external Application Load Balancer with the following setup:
    1. Set up a global backend service with two serverless NEGs:
      1. Create the first NEG in the same region as theCloud Run service deployed in the US.
      2. Create the second NEG in the same region as theCloud Run service deployed in Europe.
    2. Set up your frontend configuration with the PremiumNetwork Service Tier.

The resulting setup is shown in the following diagram.

Multi-region routing for serverless applications.
Multi-region routing for serverless applications

This section builds on the load-balancer setup described earlier on this page,in which you created one serverless NEG in theus-central1 region that pointsto a Cloud Run service in the same region. It alsoassumes that you've created a second Cloud Run service intheeurope-west1 region. The second serverless NEG that you create will pointto this Cloud Run service in theeurope-west1 region.

In this example, you will complete the following steps:

  1. Create a second serverless NEG in theeurope-west1 region.
  2. Attach the second serverless NEG to the backend service.

To add a second serverless NEG to an existing backend service, follow these steps.

Console

  1. In the Google Cloud console, go to theLoad balancing page.

    Go to Load balancing

  2. Click the name of the load balancer whose backend service you want toedit.

  3. On theLoad balancer details page, clickEdit.

  4. On theEdit global external Application Load Balancer page, clickBackend configuration.

  5. On theBackend configuration page, clickEdit for the backend service thatyou want to modify.

  6. In theBackends section, clickAdd a backend.

  7. In theServerless network endpoint groups list, selectCreateServerless network endpoint group.

  8. Enter a name for the serverless NEG.

  9. ForRegion, selecteurope-west1.

  10. ForServerless network endpoint group type, selectCloud Run, andthen do the following:

    1. Select theSelect Service option.
    2. In theService list, select the Cloud Runservice that you want to create a load balancer for.
  11. ClickCreate.

  12. On theNew backend page, clickDone.

  13. ClickSave.

  14. To update the backend service, clickUpdate.

  15. To update the load balancer, on theEdit global external Application Load Balancer page, clickUpdate.

gcloud

  1. Create a second serverless NEG in the same region in which theCloud Run service is deployed.

    gcloud compute network-endpoint-groups createSERVERLESS_NEG_NAME_2 \  --region=europe-west1 \  --network-endpoint-type=SERVERLESS \  --cloud-run-service=CLOUD_RUN_SERVICE_2

    Replace the following:

    • SERVERLESS_NEG_NAME_2: the name of the secondserverless NEG
    • CLOUD_RUN_SERVICE_2: the name of theCloud Run service
  2. Add the second serverless NEG as a backend to the backend service.

    gcloud compute backend-services add-backendBACKEND_SERVICE_NAME \  --global \  --network-endpoint-group=SERVERLESS_NEG_NAME_2 \  --network-endpoint-group-region=europe-west1

    Replace the following:

    • BACKEND_SERVICE_NAME: the name of the backendservice
    • SERVERLESS_NEG_NAME_2: the name of the secondserverless NEG

Use an authenticated Pub/Sub push subscription with a multi-region Cloud Run deployment

For authenticated push requests, Cloud Run expects aregion-specific audience field by default. In case of a multi-regionCloud Run deployment, if the push request is routed to aCloud Run service in a different region, the JWT tokenverification fails due to an audience mismatch.

To work around this region-specific restriction:

  1. Configure acustom audiencethat's the same for service deployments in different regions.
  2. Configure the Pub/Sub push messages to use the custom audience as theaudience in the JWT token.

Set up regional routing

A common reason for serving applications from multipleregions is to meet data locality requirements. For example, you might want toensure that requests made by European users are always served from a regionlocated in Europe. To set this up you need a URL schema with separate URLs forEU and non-EU users, and direct your EU users to the EU URLs.

In such a scenario, you would use the URL map to route requests from specificURLs to their corresponding regions. With such a setup, requests meant for oneregion are never delivered to a different region. This provides isolationbetween regions. On the other hand, when a region fails, requests are not routedto a different region. So this setup does not increase your service'savailability.

To set up regional routing, you will need to use the Premium network tier sothat you can combine different regions in a single forwarding rule.

To set up a load balancer with regional routing:

  1. Set up two Cloud Run services in different regions. Let's assume you havedeployed two Cloud Run services: hello-world-eu to a region in Europe,and hello-world-us to a region in the US.
  2. Create an external Application Load Balancer with the following setup:
    1. Set up a backend service with a serverless NEG in Europe. The serverlessNEG must be created in the same region as the Cloud Run servicedeployed in Europe.
    2. Set up a second backend service with another serverless NEG in theUS. This serverless NEG must be created in the same region as the CloudRun service deployed in the US.
    3. Set up your URL map with the appropriate host and path rules so thatone set of URLs routes to the European backend service while all therequests route to the US backend service.
    4. Set up your frontend configuration with the Premium network tier.

The rest of the setup can be the same as described previously. Your resultingsetup should look like this:

Regional routing for serverless applications without failover.
Regional routing for serverless applications without failover

Use a URL mask

When creating a serverless NEG, instead of selecting a specific Cloud Runservice, you can use a URL mask to point to multiple services serving at thesame domain. A URL mask is a template of your URL schema. The serverless NEGwill use this template to extract the service name from the incomingrequest's URL and map the request to the appropriate service.

URL masks are particularly useful if your service ismapped to a customdomain rather than the default address thatGoogle Cloud provides for the deployed service. A URL mask allows you totarget multiple services and versions with a single rule even when yourapplication is using a custom URL pattern.

If you haven't already done so, make sure you readServerless NEGs overview:URL Masks.

Construct a URL mask

To construct a URL mask for your load balancer, start with the URL of yourservice. For this example, we will use a sample serverless app running athttps://example.com/login. This is the URL where the app'slogin servicewill be served.

  1. Remove thehttp orhttps from the URL. You are left withexample.com/login.
  2. Replace the service name with a placeholder for the URL mask.
    1. Cloud Run: Replace the Cloud Run service name with theplaceholder<service>. If the Cloud Run service has a tag associated with it,replace the tag name with the placeholder<tag>.In this example, the URL mask you are left with is,example.com/<service>.
    2. Cloud Run functions: Replace the function name with the placeholder<function>.In this example, the URL mask you are left with is,example.com/<function>.
    3. App Engine: Replace the service name with the placeholder<service>.If the service has a version associated with it, replace the version withthe placeholder<version>.In this example, the URL mask you are left with is,example.com/<service>.
    4. API Gateway: Replace the gateway name with the placeholder<gateway>.In this example, the URL mask you are left with is,example.com/<gateway>.
  3. (Optional) If the service name (or function, version, or tag) can beextracted from the path portion of the URL,the domain can be omitted. Thepath part of the URL mask is distinguishedby the first/ character. If a/ is not present in the URL mask,the mask is understood to represent the host only. Therefore, for thisexample, the URL mask can be reduced to/<service>,/<gateway>, or/<function>.

    Similarly, if the service name can be extracted from the host part of theURL, you can omit the path altogether from the URL mask.

    You can also omitany host or subdomain components that come before the first placeholder aswell as any path components that come after the last placeholder. In suchcases, the placeholder captures the required information for the component.

Here are a few more examples that demonstrate these rules:

Cloud Run

This table assumes that you have a custom domain calledexample.com andall your Cloud Run services are being mappedto this domain by using an external Application Load Balancer.

Service, Tag nameCustom domain URLURL mask
service: loginhttps://login-home.example.com/web<service>-home.example.com
service: loginhttps://example.com/login/webexample.com/<service> or /<service>
service: login, tag: testhttps://test.login.example.com/web<tag>.<service>.example.com
service: login, tag: testhttps://example.com/home/login/testexample.com/home/<service>/<tag> or /home/<service>/<tag>
service: login, tag: testhttps://test.example.com/home/login/web<tag>.example.com/home/<service>

Cloud Run functions

This table assumes that you have a custom domain calledexample.com andall your Cloud Run functions services are being mappedto this domain.

Function NameCustom domain URLURL Mask
loginhttps://example.com/login/<function>
loginhttps://example.com/home/login/home/<function>
loginhttps://login.example.com<function>.example.com
loginhttps://login.home.example.com<function>.home.example.com

App Engine

This table assumes that you have a custom domain calledexample.com andall your App Engine services are being mappedto this domain.

Service name, versionCustom domain URLURL mask
service: loginhttps://login.example.com/web<service>.example.com
service: loginhttps://example.com/home/login/webexample.com/home/<service>, or /home/<service>
service: login, version: testhttps://test.example.com/login/web<version>.example.com/<service>
service: login, version: testhttps://example.com/login/testexample.com/<service>/<version>

API Gateway

This table assumes that you have a custom domain calledexample.com andall your API Gatewayservices are beingmapped to this domain.

Gateway nameAPI Gateway(Preview) custom domain URLURL mask
loginhttps://example.com/login/<gateway>
loginhttps://example.com/home/login/home/<gateway>
loginhttps://login.example.com<gateway>.example.com
loginhttps://login.home.example.com<gateway>.home.example.com

Create a serverless NEG with a URL mask

Console

For a new load balancer, you can use the same end-to-end process asdescribed previously in this topic. When configuring the backend service,instead of selecting a specific service, enter a URL mask.

If you have an existing load balancer, you can edit the backend configurationand have the serverless NEG point to a URL mask instead of a specific service.

To add a URL mask-based serverless NEG to an existing backend service:

  1. Go to the Load balancing page in the Google Cloud console.
    Go to the Load balancing page
  2. Click the name of the load balancer whose backend service you want toedit.
  3. On theLoad balancer details page, clickEdit.
  4. On theEdit global external Application Load Balancer page, clickBackend configuration.
  5. On theBackend configuration page, clickEdit for thebackend service you want to modify.
  6. ClickAdd backend.
  7. SelectCreate Serverless network endpoint group.
    1. For theName, enterhelloworld-serverless-neg.
    2. UnderRegion, selectus-central1.
    3. UnderServerless network endpoint group type, select theplatform where your serverless apps (or services or functions)were created.
      1. SelectUse URL Mask.
      2. Enter a URL mask. For instructions on how to create a URL mask,seeConstructing a URL mask.
      3. ClickCreate.
  8. In theNew backend section, clickDone.
  9. ClickUpdate.

gcloud: Cloud Run

To create a Serverless NEG with a sample URL mask ofexample.com/<service>:

gcloud compute network-endpoint-groups create helloworld-neg-mask \  --region=us-central1 \  --network-endpoint-type=serverless \  --cloud-run-url-mask="example.com/<service>"

gcloud: Cloud Run functions

To create a Serverless NEG with a sample URL mask ofexample.com/<service>:

gcloud compute network-endpoint-groups create helloworld-neg-mask \ --region=us-central1 \ --network-endpoint-type=serverless \ --cloud-function-url-mask="example.com/<service>"

gcloud: App Engine

To create a Serverless NEG with a sample URL mask ofexample.com/<service>:

gcloud compute network-endpoint-groups create helloworld-neg-mask \  --region=us-central1 \  --network-endpoint-type=serverless \  --app-engine-url-mask="example.com/<service>"

gcloud: API Gateway

To create a Serverless NEG with a sample URL mask ofexample.com/<gateway>:

gcloud beta compute network-endpoint-groups create helloworld-neg-mask \  --region=us-central1 \  --network-endpoint-type=serverless \  --serverless-deployment-platform=apigateway.googleapis.com \  --serverless-deployment-resource=my-gateway \  --serverless-deployment-url-mask="example.com/<gateway>"

To learn how the load balancer handles issues with URL mask mismatches, seeTroubleshooting issues with serverlessNEGs.

Move your custom domain to be served by the external Application Load Balancer

If your serverless compute apps are being mapped to custom domains, you mightwant to update your DNS records so that traffic sent to the existingCloud Run, Cloud Run functions,API Gateway, or App Engine custom domain URLsis routed through the load balancer instead.

For example, if you have a custom domain calledexample.com and all your CloudRun services are mapped to this domain, you should update the DNS record forexample.com to point to the load balancer's IP address.

Before updating the DNS records, you can test your configuration locally byforcing local DNS resolution of the custom domain to theload balancer's IPaddress. To test locally, either modify the/etc/hosts/ file onyour local machine to pointexample.com to the load balancer's IP address, or,use thecurl --resolve flag to forcecurl to use the load balancer's IPaddress for the request.

When the DNS record forexample.com resolves to the HTTP(S) load balancer's IPaddress, requests sent toexample.com begin to be routed via the loadbalancer. The load balancer dispatches them to the relevant backend serviceaccording to its URL map. Additionally, if the backend service is configured witha URL mask, the serverless NEG uses the mask to route the request to theappropriate Cloud Run, Cloud Run functions,API Gateway, or App Engine service.

Note: If you useGoogle-managedcertificates, migrating an existingservice to an external Application Load Balancer may incursome downtime, typically less than an hour. This is because the SSL certificatefor your external Application Load Balancer won't be provisioned until you update your DNS recordsto point to the load balancer's IP address.

Enable Cloud CDN

EnablingCloud CDN for your Cloud Run serviceallows you to optimize content delivery by caching content close to your users.

You can enable Cloud CDN on backend services used byglobal external Application Load Balancers by using thegcloud computebackend-services updatecommand.

gcloud compute backend-services update helloworld-backend-service
--enable-cdn
--global

Cloud CDN is supported for backend services withCloud Run, Cloud Run functions,API Gateway,and App Engine backends.

Enable IAP on the external Application Load Balancer

Note: IAP isn't compatible with Cloud CDN.

You can configure IAP to beenabled or disabled (default). If enabled, you must provide values foroauth2-client-id andoauth2-client-secret.

To enable IAP, update the backend serviceto include the--iap=enabled flag with theoauth2-client-id andoauth2-client-secret.

gcloud compute backend-services updateBACKEND_SERVICE_NAME \    --iap=enabled,oauth2-client-id=ID,oauth2-client-secret=SECRET \    --global

Optionally, you canenable IAPfor a Compute Engine resource by using the Google Cloud console,gcloud CLI, or API.

Enable Google Cloud Armor

Cloud Armor is a security product that providesprotection against distributed denial-of-service (DDoS) attacks to allGCLB proxy load balancers. Cloud Armor also provides configurable securitypolicies to services accessed through an external Application Load Balancer. To learn aboutCloud Armor security policies for external Application Load Balancers, seeCloud Armor security policy overview.

Optional: Configure a default backend security policy. The default security policy throttles traffic over a user-configured threshold. For more information about default security policies, see theRate limiting overview.

  1. To opt out of the Cloud Armor default security policy, selectNone in theCloud Armor backend security policy list.
  2. To configure the Cloud Armor default security policy, selectDefault security policy in theCloud Armor backend security policy list.
  3. In thePolicy name field, accept the automatically generated name or enter a name for your security policy.
  4. In theRequest count field, accept the default request count or enter an integer between1 and10,000.
  5. In theInterval field, select an interval.
  6. In theEnforce on key field, choose one of the following values:All,IP address, orX-Forwarded-For IP address. For more information about these options, seeIdentifying clients for rate limiting.

Enable logging and monitoring

You can enable, disable, and view logs for an external Application Load Balancerbackend service. When using the Google Cloud console, logging is enabled by defaultfor backend services with serverless NEG backends. You can usegcloud todisable logging for each backend service as needed. For instructions, seeLogging.

The load balancer also exports monitoring data to Cloud Monitoring.Monitoring metrics can be used to evaluate a load balancer's configuration,usage, and performance. Metrics can also be used to troubleshoot problemsand improve resource utilization and user experience. For instructions, seeMonitoring.

Delete a serverless NEG

A network endpoint group cannot be deleted if it is attached to a backendservice. Before you delete a NEG, ensure that it is detached from thebackend service.

Console

  1. To make sure the serverless NEG you want to delete is not currentlyin use by any backend service, go to theBackend services tab in theLoad balancing advanced menu.
    Go to the Backend services tab
  2. If the serverless NEG is currently in use:
    1. Click the name of the backend service using the serverless NEG.
    2. ClickEdit.
    3. From the list ofBackends, click to remove the serverless NEGbackend from the backend service.
    4. ClickSave.
  3. Go to theNetwork endpoint group page in the Google Cloud console.
    Go to the Network Endpoint Group page
  4. Select the checkbox for the serverless NEG you want to delete.
  5. ClickDelete.
  6. ClickDelete again to confirm.

gcloud

To remove a serverless NEG from a backend service, you must specifythe region where the NEG was created. You must also specify the--globalflag becausehelloworld-backend-service is a global resource.

gcloud compute backend-services remove-backend helloworld-backend-service \    --network-endpoint-group=helloworld-serverless-neg \    --network-endpoint-group-region=us-central1 \    --global

To delete the serverless NEG:

gcloud compute network-endpoint-groups delete helloworld-serverless-neg \    --region=us-central1

What's next

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-15 UTC.