Set up header and query parameter-based routing for the classic Application Load Balancer

This page includes two examples for classic Application Load Balancer:

To configure traffic management for the global external Application Load Balancer and theregional external Application Load Balancer, see the following pages:

Before you begin

Set up query parameter-based routing

This example demonstrates using query parameters to do A/B testing by matchingon the query string.

Add two backend instance groups

For routing to be useful, you must have multiple backends.

To set up two backends, your VMs need to be in two instance groups. This guidedescribes how to create managed instance groups with Linux VMs that haveApache running and then set up load balancing.

The managed instance groups provide VMs running the backend servers ofan external HTTP load balancer. For demonstration purposes, backends serve theirown hostnames.

For simplicity, the backends reside in the same region. If you want amulti-region setup, you must have an instance template setup for the secondregion.

Console

  1. Create an instance template. In the Google Cloud console, go totheInstance templates page.

    Go to Instance templates

    1. ClickCreate instance template.
    2. ForName, enterlb-backend-template.
    3. Ensure that theBoot disk is set to a Debian image, such asDebian GNU/Linux 12 (bookworm). These instructions use commands thatare only available on Debian, such asapt-get.
    4. ClickAdvanced options.
    5. ClickNetworking and configure the following field:
      1. ForNetwork tags, enterallow-health-check.
    6. ClickManagement. Enter the following script into theStartup script field.

      #! /bin/bashapt-get updateapt-get install apache2 -ya2ensite default-ssla2enmod sslvm_hostname="$(curl -H "Metadata-Flavor:Google" \http://metadata.google.internal/computeMetadata/v1/instance/name)"echo "Page served from: $vm_hostname" | \tee /var/www/html/index.htmlsystemctl restart apache2
    7. ClickCreate.

  2. Create a managed instance group. Go to theInstance groups page in the Google Cloud console.

    Go to Instance groups

    1. ClickCreate instance group.
    2. SelectNew managed instance group (stateless). For moreinformation, seeStateless or stateful MIGs.
    3. ForName, enterfirst-example-ig.
    4. UnderLocation, selectSingle zone.
    5. ForRegion, select your preferred region. This example usesus-east1.
    6. ForZone, selectus-east1-b.
    7. UnderInstance template, select the instance templatelb-backend-template.
    8. UnderMaximum number of instances, enter2.
    9. UnderAutoscaling mode, selectOff:do not autoscale.
    10. ClickCreate.

Create another managed instance group like this one. Name the second onesecond-example-ig, and base it on thelb-backend-template template.

gcloud

  1. Create an instance template.

    gcloud compute instance-templates create lb-backend-template \   --region=us-east1 \   --network=default \   --subnet=default \   --tags=allow-health-check \   --image-family=debian-12 \   --image-project=debian-cloud \   --metadata=startup-script='#! /bin/bash     apt-get update     apt-get install apache2 -y     a2ensite default-ssl     a2enmod ssl     vm_hostname="$(curl -H "Metadata-Flavor:Google" \     http://metadata.google.internal/computeMetadata/v1/instance/name)"     echo "Page served from: $vm_hostname" | \     tee /var/www/html/index.html     systemctl restart apache2'
  2. Create the first managed instance group based on the template.

    gcloud compute instance-groups managed create first-example-ig \   --template=lb-backend-template --size=2 --zone=us-east1-b
  3. Create the second managed instance group based on the template.

    gcloud compute instance-groups managed create second-example-ig \   --template=lb-backend-template --size=2 --zone=us-east1-c

Configuring a firewall rule

In this example, you create thefw-allow-health-check firewall rule.This is an ingress rule that allows traffic from the Google Cloud healthchecking systems (130.211.0.0/22 and35.191.0.0/16). This example uses thetarget tagallow-health-check to identify the VMs.

Console

  1. In the Google Cloud console, go to theFirewall policies page.
    Go to Firewall policies
  2. ClickCreate firewall rule to create the second firewall rule:
  3. Enter aName offw-allow-health-check.
  4. UnderNetwork, selectDefault.
  5. UnderTargets, selectSpecified target tags.
  6. Populate theTarget tags field withallow-health-check.
  7. SetSource filter toIPv4 ranges.
  8. SetSource IPv4 ranges to130.211.0.0/22 and35.191.0.0/16.
  9. UnderProtocols and ports, selectSpecified protocols and ports.
  10. Select theTCP checkbox and enter80 for the portnumbers.
  11. ClickCreate.

gcloud

gcloud compute firewall-rules create fw-allow-health-check \    --network=default \    --action=allow \    --direction=ingress \    --source-ranges=130.211.0.0/22,35.191.0.0/16 \    --target-tags=allow-health-check \    --rules=tcp

Reserving an external IP address

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

Console

  1. Go to the External IP addresses page in the Google Cloud console.
    Go to the External IP addresses page
  2. ClickReserve static address to reserve an IPv4 address.
  3. Assign aName oflb-ipv4-1.
  4. Set the Network tier toStandard.
  5. Set theIP version toIPv4.
  6. Set theType toGlobal.
  7. ClickReserve.
  8. Ensure that theType is set toGlobal.
  9. ClickReserve.

gcloud

gcloud compute addresses create lb-ipv4-1 \    --ip-version=IPV4 \    --network-tier=PREMIUM \    --global

Note the IPv4 address that was reserved:

gcloud compute addresses describe lb-ipv4-1 \    --format="get(address)" \    --global

Setting up the load balancer backends

Console

The Google Cloud console is currently unsupported for setting upheader-based and parameter-based routing. Usegcloud or the API instead.

gcloud

  1. Create ahealth check.
        gcloud compute health-checks create http http-basic-check \        --port 80
  2. Create the firstbackend service.
    • For a global external Application Load Balancer, use the gcloud CLI command withload-balancing-scheme=EXTERNAL_MANAGED. This setting offersadvanced traffic management capability.
    • For an classic Application Load Balancer, useload-balancing-scheme=EXTERNAL.
        gcloud compute backend-services create service-a \        --load-balancing-scheme=LOAD_BALANCING_SCHEME \        --global-health-checks \        --protocol HTTP \        --health-checks http-basic-check \        --global
  3. Create the secondbackend service.
        gcloud compute backend-services create service-b \        --load-balancing-scheme=LOAD_BALANCING_SCHEME \        --global-health-checks \        --protocol HTTP \        --health-checks http-basic-check \        --global
  4. Add your first instance group as the backend to the first backend service.
        gcloud compute backend-services add-backend service-a \        --balancing-mode=UTILIZATION \        --max-utilization=0.8 \        --capacity-scaler=1 \        --instance-group=first-example-ig \        --instance-group-zone=us-east1-b \        --global
  5. Add your second instance group as the backend to the second backend service.
        gcloud compute backend-services add-backend service-b \        --balancing-mode=UTILIZATION \        --max-utilization=0.8 \        --capacity-scaler=1 \        --instance-group=second-example-ig \        --instance-group-zone=us-east1-c \        --global

Creating the URL map

Console

The Google Cloud console is currently unsupported for setting upheader-based and parameter-based routing. Usegcloud or the API instead.

gcloud

  1. Create a YAML file/tmp/web-map-http.yaml. ReplacePROJECT_ID with your project ID.

    defaultService:https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/service-ahostRules:-hosts:-'*'pathMatcher:path-matcher-1name:web-map-httppathMatchers:-defaultService:https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/service-aname:path-matcher-1routeRules:-matchRules:-prefixMatch:/queryParameterMatches:-name:ABTestexactMatch:Apriority:0service:https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/service-a-matchRules:-prefixMatch:/queryParameterMatches:-name:ABTestexactMatch:Bpriority:1service:https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/service-bselfLink:https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/urlMaps/web-map-httptests:-description:Test routing for query ABTest with Ahost:example.compath:/?ABTest=Aservice:https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/service-aexpectedOutputUrl:http://example.com/?ABTest=A-description:Test routing for query ABTest with Bhost:example.compath:/?ABTest=Bservice:https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/service-bexpectedOutputUrl:http://example.com/?ABTest=B
  2. Validate the URL map.

    gcloud compute url-maps validate --source /tmp/web-map-http.yaml

    If the tests pass and the command outputs a success message,save the changes to the URL map.

  3. Update the URL map.

    gcloud compute url-maps import web-map-http \   --source /tmp/web-map-http.yaml \   --global

Creating the target proxy and forwarding rule

Console

The Google Cloud console is currently unsupported for setting upheader-based and parameter-based routing. Usegcloud or the API instead.

gcloud

  1. Create a target HTTP proxy to route requests to your URL map.
        gcloud compute target-http-proxies create http-lb-proxy \        --url-map web-map-http
  2. Create a global forwarding rule to route incoming requests to the proxy.
    • For a global external Application Load Balancer, use the gcloud CLI command withload-balancing-scheme=EXTERNAL_MANAGED. This setting offersadvanced traffic management capability.
    • For an classic Application Load Balancer, useload-balancing-scheme=EXTERNAL.
        gcloud compute forwarding-rules create http-content-rule \        --load-balancing-scheme=LOAD_BALANCING_SCHEME \        --network-tier=PREMIUM \        --address=lb-ipv4-1 \        --global \        --target-http-proxy=http-lb-proxy \        --ports=80

Testing

Note the IPv4 address that was reserved:

gcloud compute addresses describe lb-ipv4-1 \    --format="get(address)" \    --global

Test this setup by running:

curl http://IP_ADDRESS?ABTest=A
curl http://IP_ADDRESS?ABTest=B

In a browser, openhttp://IP_ADDRESS?ABTest=Aandhttp://IP_ADDRESS?ABTest=B.

Set up HTTP header-based routing

This example demonstrates adding and removing HTTP headers to dointelligent routing.

Before you begin

You can use an existing external Application Load Balancer or create a new one.

You can use this feature with any of thesupported backendtypes. This example assumes that you'reusing VMs in an instance group.

To set up a simple load balancer, see the query parameter-based example above.

Updating the URL map

Console

The Google Cloud console is currently unsupported for setting upheader-based and parameter-based routing. Usegcloud or the API instead.

gcloud

  1. This example demonstrates using HTTP request headers to do A/B testing bymatching on values in the request's HTTP headers.

    Create a YAML file/tmp/web-map-http.yaml. ReplacePROJECT_ID with your project ID.

    defaultService:https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/service-akind:compute#urlMapname:web-map-httphostRules:-hosts:-'*'pathMatcher:path-matcher-1pathMatchers:-defaultService:https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/service-aname:path-matcher-1routeRules:-matchRules:-prefixMatch:/headerMatches:-headerName:ABTestexactMatch:Apriority:0service:https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/service-a-matchRules:-prefixMatch:/headerMatches:-headerName:ABTestexactMatch:Bpriority:1service:https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/service-btests:-description:Test routing for query ABTest with Ahost:example.compath:/headers:-name:ABTestvalue:Aservice:https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/service-a-description:Test routing for query ABTest with Bhost:example.compath:/headers:-name:ABTestvalue:Bservice:https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/service-b
  2. Validate the URL map.

    gcloud compute url-maps validate --source /tmp/web-map-http.yaml

    If the tests pass and the command outputs a success message,save the changes to the URL map.

  3. Update the URL map.

    gcloud compute url-maps import web-map-http \   --source /tmp/web-map-http.yaml \   --global

Testing

Using the IPv4 address of the associated load balancer, test this setup byrunning:

curl http://IP_ADDRESS -H "ABTest: A"
curl http://IP_ADDRESS -H "ABTest: B"

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.