Request routing to a multi-region classic Application Load Balancer

This guide demonstrates how to create a Google Cloud HTTPS load balancer that:

  • Selects backend services based on the request URL paths.
  • Routes requests to backends that are close to the clients (multi-region loadbalancing).

Before you start, make sure that you are familiar withExternal Application Load Balancer concepts.

For a simplified example, seeSetting up anexternal Application Load Balancer with a Compute Enginebackend. For advanced routing,such as HTTP rewrites and redirects, seeTraffic managementfor external Application Load Balancers.

Overview

This guide provides instructions for creating a load balancer that directstraffic based on the path in the request URL and balances traffic acrossmultiple regions. You create eight total Compute Engine instances in US(in zone us-central1-b) and EU (in zone eu-west1-b) regions. You then create aload balancer that routes traffic to these instances.

After you complete the instructions, your load balancer is configured as follows:

  • Traffic containing a URL path that starts with/video is routed to onebackend service.
  • Traffic with a URL path that doesn't match this pattern is routed to anotherbackend service.

In this how-to document, you create the configuration that is illustrated in thefollowing diagram:

Multi-regional HTTPS Load Balancing
Multi-regional HTTPS Load Balancing (click to enlarge)

The sequence of events in the diagram is:

  1. A client accesses thehttps://www.example.com/video/concert URL, sendinga content request to the external IP address defined in the forwarding rule.The request can use IPv4 or IPv6; there are forwarding rules forboth protocols.
  2. A forwarding rule directs the request to the target HTTPS proxy.
  3. The target proxy uses the rules set out in the URL map to determine whichbackend service receives the request. A request that contains/video, likehttps://www.example.com/video/concert, is sent tovideo-backend-service.Any other URL path is sent to the default service,web-backend-service.
  4. The load balancer determines which of the backend service's instance groupsshould serve the request, based on their loading and proximity to the client,and directs the request to an instance in that group.
  5. The instance serves the content requested by each user. Thevideo instancesserve video content, while thewww instances serve all other content.

In this example, the load balancer accepts HTTPS requests from clients andproxies these requests as HTTP to the backends. You can also configure a loadbalancer to accept HTTP requests, as well as to use HTTPS when proxying requeststo backends.

Before you begin

These instructions require aproject.If you do not already have a project, set one up now.These instructions guide you through creating acustom mode Virtual Private Cloud (VPC) network.You must also set up custom firewall rules to allow traffic to reach the instances.

If you prefer to work from the command line, install thegcloud command-linetool. Seegcloud Overview for conceptual and installationinformation about the tool.

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

Permissions

To complete the steps in this guide, you must have permission to createCompute Engine instances in a project. You must have either a projectowner or editor role, or you must havethe followingCompute Engine IAM roles:

TaskRequired Role
Create instancesCompute Instance Admin
Add and remove firewall rulesSecurity Admin
Create load balancer componentsNetwork Admin
Create a project (Optional)Project Creator

For more information, see the following guides:

Setup

Optional: Creating a new project

We recommend that users with theresourcemanager.projects.create permissioncreate a new project before following the rest of this how-to. This simplifiescleanup at the end of the guide.

Configuring a network and subnets

In this example, use the following VPC network, regions, andsubnets:

  • Network: The network is acustom mode VPCnetwork namedlb-network.

  • Subnets in two different regions:

    • us-subnet uses10.1.10.0/24 for its primary IP range and islocated in theus-central1 region.
    • eu-subnet uses10.1.11.0/24 for its primary IP range and islocated in theeurope-west1 region.

To create the example network and subnet, follow these steps:

Console

  1. In the Google Cloud console, go to theVPC networks page.

    Go to VPC networks

  2. ClickCreate VPC network.

  3. Enter aName oflb-network.

  4. In theSubnets section, create the first subnet:

    • Set theSubnet creation mode toCustom.
    • In theNew subnet section, enter the following information:
      • Name:us-subnet
      • Region:us-central1
      • IP address range:10.1.10.0/24
      • ClickDone.
  5. Still in theSubnets section, clickAdd subnet and create thesecond subnet:

    • In theNew subnet section, enter the following information:
      • Name:eu-subnet
      • Region:europe-west1
      • IP address range:10.1.11.0/24
      • ClickDone.
  6. ClickCreate.

gcloud

  1. Create the custom VPC network:

    gcloud compute networks create lb-network --subnet-mode=custom
  2. Create theus-subnet:

    gcloud compute networks subnets create us-subnet \  --network=lb-network \  --range=10.1.10.0/24 \  --region=us-central1
  3. Create theeu-subnet:

    gcloud compute networks subnets create eu-subnet \  --network=lb-network \  --range=10.1.11.0/24 \  --region=europe-west1

Configuring firewall rules

Thedefault deny ingress rule blocksincoming traffic to the backend instances, including traffic from the load balancer andGoogle Cloud health checking systems. You must create new firewall rules tooverride the default rule and allow traffic to reach your instances.

In this example, you create the following firewall rules:

  • fw-allow-ssh: An ingress rule, applicable to the instances being loadbalanced, that allows incoming SSH connectivity on TCP port 22 from anyaddress. You can choose a more restrictive source IP range for this rule; forexample, you can specify just the IP ranges of the system from which you willinitiating SSH sessions. This example uses the target tagallow-ssh toidentify the backend VMs to which it should apply.

  • fw-allow-health-check-and-proxy: An ingress rule, applicable to theinstances being load balanced, that allows traffic from the load balancer andGoogle Cloud health checking systems (130.211.0.0/22and35.191.0.0/16). This example uses the target tagallow-health-check toidentify the backend VMs to which it should apply.

Console

  1. In the Google Cloud console, go to theFirewall policies page.

    Go to Firewall policies

  2. ClickCreate firewall rule to create the first firewall rule:

    1. Enter aName offw-allow-ssh.
    2. UnderNetwork, selectlb-network.
    3. UnderTargets, selectSpecified target tags.
    4. Populate theTarget tags field withallow-ssh.
    5. SetSource filter toIPv4 ranges.
    6. SetSource IPv4 ranges to0.0.0.0/0.
    7. UnderProtocols and ports, selectSpecified protocols and ports.
    8. Select theTCP checkbox and enter22 for the port number.
    9. ClickCreate.
  3. ClickCreate firewall rule to create the second firewall rule:

    1. Enter aName offw-allow-health-check-and-proxy.
    2. UnderNetwork, selectlb-network.
    3. UnderTargets, selectSpecified target tags.
    4. Populate theTarget tags field withallow-health-check.
    5. SetSource filter toIPv4 ranges.
    6. SetSource IPv4 ranges to130.211.0.0/22 and35.191.0.0/16.
    7. UnderProtocols and ports, selectSpecified protocols and ports.
    8. Select theTCP checkbox and enter80,443 for the portnumbers.
    9. ClickCreate.

gcloud

  1. Create thefw-allow-ssh firewall rule to allow SSH connectivity toVMs with the network tagallow-ssh. When you omitsource-ranges,Google Cloudinterprets the rule to mean anysource.

    gcloud compute firewall-rules create fw-allow-ssh \    --network=lb-network \    --action=allow \    --direction=ingress \    --target-tags=allow-ssh \    --rules=tcp:22
  2. Create thefw-allow-health-check-and-proxy rule to allowthe load balancer and Google Cloud health checks to communicate withbackend instances on TCP port80 and443:

    gcloud compute firewall-rules create fw-allow-health-check-and-proxy \    --network=lb-network \    --action=allow \    --direction=ingress \    --target-tags=allow-health-check \    --source-ranges=130.211.0.0/22,35.191.0.0/16 \    --rules=tcp:80,tcp:443

Creating instances

To set up a load balancer with a Compute Engine backend, your VMs needto be in instance groups. This guide describes how to create a managedinstance group with Linux VMs that have Apache running.

The managed instance group provides VMs running the backend servers ofan external HTTPS load balancer. For demonstration purposes, backendsserve their own hostnames.

In this example, you create eight virtual machine instances (VMs): four to servevideo content and four to serve all other content. You use astartupscript to install Apache web server softwarewith a unique home page for each instance. Note that you can use any web serveron your VMs; Apache is installed in this example as a convenience.

Console

Create an instance template.

  1. In the Google Cloud console, go to theInstance templates page.

    Go to Instance templates

    1. ClickCreate instance template.
    2. ForName, entervideo-us-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 fields:
      1. ForNetwork tags, enterallow-health-check andallow-ssh.
      2. ForNetwork interfaces, select the following:
        • Network:lb-network
        • Subnet:us-subnet
    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)"mkdir -p /var/www/html/videoecho "Page served from: $vm_hostname" | \tee /var/www/html/index.html /var/www/html/video/index.htmlsystemctl restart apache2
    7. ClickCreate.

  2. Create a managed instance group. In the Google Cloud console, go to theInstance groups page.

    Go to Instance groups

    1. ClickCreate instance group.
    2. SelectNew managed instance group (stateless). For moreinformation, seeStateless or stateful MIGs.
    3. ForName, enterig-video-us.
    4. UnderLocation, selectSingle zone.
    5. ForRegion, select your preferred region. This example usesus-central1.
    6. ForZone, selectus-central1-b.
    7. UnderInstance template, selectvideo-us-template.
    8. UnderAutoscaling mode, selectOff:do not autoscale.
    9. UnderMaximum number of instances, enter2.
    10. ClickCreate.
Note: Because the external Application Load Balancer is a proxy, youdon't need to selectAllow HTTPS traffic underFirewall.

gcloud

  1. Create an instance template.

    gcloud compute instance-templates create video-us-template \   --region=us-central1 \   --network=lb-network \   --subnet=us-subnet \   --tags=allow-health-check,allow-ssh \   --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)"     mkdir -p /var/www/html/video     echo "Page served from: $vm_hostname" | \     tee /var/www/html/index.html /var/www/html/video/index.html     systemctl restart apache2'
  2. Create a managed instance group based on the template.

    gcloud compute instance-groups managed create ig-video-us \   --template=video-us-template --size=2 --zone=us-central1-b

Repeat this procedure four times for the four instance groups. Make sure tochange the instance group name, template name, region, and zone for eachinstance group, as follows:

Adding a named port to the instance group

For each instance group, define an HTTP service and map a port nameto the relevant port. Once configured, the load balancing service forwardstraffic to the named port.

Console

  1. In the Google Cloud console, go to theInstance groups page.

    Go to Instance groups

  2. Click the name of your instance group (for exampleig-video-us)and clickEdit Group.

  3. ClickSpecify port name mapping.

  4. ClickAdd item.

  5. For the port name, enterhttp. For the port number, enter80.

  6. ClickSave.

Repeat this step for each instance group.

gcloud

gcloud compute instance-groups unmanaged set-named-ports ig-video-us \    --named-ports http:80 \    --zone us-central1-b
gcloud compute instance-groups unmanaged set-named-ports ig-www-us \    --named-ports http:80 \    --zone us-central1-b
gcloud compute instance-groups unmanaged set-named-ports ig-video-eu \    --named-ports http:80 \    --zone europe-west1-b
gcloud compute instance-groups unmanaged set-named-ports ig-www-eu \    --named-ports http:80 \    --zone europe-west1-b

Reserving external IP addresses

Now that your instances are up and running, set up the services needed for loadbalancing. In this section, you create twoglobal static external IP addresses that your customers use to reach your load balancer.

Console

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

    Go to External IP addresses

  2. ClickReserve static address to reserve an IPv4 address.

  3. Assign aName oflb-ipv4-1.

  4. Set the Network tier toPremium.

  5. SetIP version toIPv4.

  6. Set theType toGlobal.

  7. ClickReserve.

  8. ClickReserve static address again to reserve an IPv6 address.

  9. Assign aName oflb-ipv6-1.

  10. Set the Network Tier toPremium.

  11. SetIP version toIPv6.

  12. Ensure that theType is set toGlobal.

    In this example, the load balancer usesPremium Tier networking.A load balancer using Standard Tier networking would instead use regional IPaddresses. IPv6 addresses are not available with Standard Tier.

  13. ClickReserve.

gcloud

  1. Reserve an IPv4 address:

    gcloud compute addresses create lb-ipv4-1 \  --ip-version=IPV4 \  --network-tier=PREMIUM \  --global
  2. Reserve an IPv6 address:

    gcloud compute addresses create lb-ipv6-1 \  --ip-version=IPV6 \  --network-tier=PREMIUM \  --global

Configuring the load balancing resources

Load balancer functionality involves several connected resources.In this section, you set up and connect the resources. They areas follows:

  • Named ports,which the load balancer uses to direct traffic to your instance groups.
  • AHealth check, which pollsyour instances to see if they are healthy. The load balancer only sendstraffic to healthy instances.
  • Backend services, which keep track ofcapacity, session affinity, and health check status. Backend services directrequests to backend VMs or endpoints based on capacity and instance health.
  • AURL map, which the load balancer usesto to direct requests to specific backend services based on the host and pathof the request URL.
  • AnSSL certificate resource.SSL certificate resources contain SSL certificate information that the loadbalancer uses to terminate TLS when HTTPS clients connect to it. You can usemultiple SSL certificates,which can be any combination ofmanaged or self-managed SSL certificates.You must create an SSL certificate resource for each certificate you use.
  • Atarget HTTPS proxy, which the loadbalancer uses to associate your URL map and SSL certificates with your globalforwarding rules.
  • Twoglobal forwarding rules,one each for IPv4 and IPv6, which hold the global external IP addressresources. Global forwarding rules forward the incoming request to thetarget proxy.

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 theName of the load balancer, enterweb-map.
  2. Keep the window open to continue.

Configure the backend service and health check for thewww instances

The load balancer requires two backend services and a health check to serviceboth of them. In this example, the load balancer terminates HTTPS requestsfrom the client and uses HTTP to communicate with the backends. To do this,you specify HTTP for the backend protocols and health checks.

  1. ClickBackend configuration.
  2. In theCreate or select a backend service drop-down menu, hold the mouse pointeroverBackend services, and then selectCreate a backend service.
  3. Set theName of the backend service toweb-backend-service.
  4. Ensure that theBackend type is set toInstance group.
  5. In theProtocol drop-down menu, selectHTTP.
  6. In theNamed port field, enterhttp.
  7. Configure the health check for thewww instances:
    1. In theHealth check list, clickCreate a health check.
    2. In theName field, enterhttp-basic-check-www.
    3. In theProtocol list, selectHTTP.
    4. In thePort field, enter80.
    5. ClickCreate.
  8. UnderBackends, setInstance group toig-www-us.
  9. For traffic between the load balancer and the instances, setPortnumbers to80.
  10. Leave the default values for the remaining fields.
  11. ClickDone at the bottom of theNew backend window.
  12. ClickAdd backend and repeat steps, but select instance groupig-www-eu.
  13. Keep the window open to continue.

Configure the backend service and health check for thevideo instances

  1. Repeat the earlier steps to configure the backend service and healthcheck, but name the second backend servicevideo-backend-service andassign theig-video-us andig-video-eu instance groups to it.
  2. Follow the same steps to create a health check, but name the health checkhttp-basic-check-video. Health check names must be unique.

Configure host and path rules

The host and path rules configure the load balancer's URL map resource.

  1. In the left column of the screen, clickHost and path rules.
  2. The first row hasweb-backend-service in the right-hand column andis already populated with the default ruleAny unmatched (default) forHosts andPaths.
  3. Ensure that there is a second row withvideo-backend-service in the right-hand column.If it does not exist, clickAdd host and path rule, and then selectvideo-backend-servicefrom the drop-down menu in the right column. Populate the other columns as follows:
    1. SetHosts to*.
    2. In thePaths field:
      1. Enter/video, and then press the Tab key.
      2. Enter/video/*, and then press the Tab key.

Configure the frontend

The frontend configuration section configures several resources for the loadbalancer, including the forwarding rules and SSL certificates. In addition,it allows you to select the protocol used between the client and the load balancer.

In this example, you are using HTTPS between the client and the load balancer,so you need one or more SSL certificate resources to configure the proxy.SeeSSL Certificatesfor information on how to create SSL certificate resources. We recommendusing a Google-managed certificate.

Warning: Donot use a self-signed certificate for production purposes.
  1. In the left panel of theCreate global external Application Load Balancer page, clickFrontend configuration.
  2. In theName field, enterhttps-content-rule.
  3. In theProtocol field, selectHTTPS.
  4. Keep the window open to continue.

Configure the IPv4 forwarding rule

  1. SetIP version toIPv4.
  2. InIP address, selectlb-ipv4-1, which you created earlier.
  3. Ensure that thePort is set to443, to allow HTTPS traffic.
  4. Click theCertificate drop-down list.
    1. If you already have aself-managed SSL certificateresourceand you want to use it as the primary SSL certificate, select itfrom the drop-down menu.
    2. Otherwise, selectCreate a new certificate.
    3. Fill in aName ofwww-ssl-cert.
    4. SelectUpload my certificate orCreate Google managedcertificate. To create a Google-managed certificate, you must havea domain. If you do not have a domain, you can upload your owncertificate for testing purposes.
    5. If you selectedUpload my certificate, completethese steps.
      1. In thePublic key certificate field, do one of the following:
        • Click theUpload button and select your PEM-formatted certificatefile.
        • Copy and paste the contents of a PEM-formatted certificate. Thecontents must start with-----BEGIN CERTIFICATE----- and endwith-----END CERTIFICATE-----.
      2. For theCertificate chain field, do one of the following:
        • Click theUpload button and select your CA's certificate file.This file should include intermediate CA certificates as well asthe root CA certificate.
        • Copy and paste the contents of a certificate chain. Each certificatein the chain must be PEM-formatted, starting with-----BEGIN CERTIFICATE----- and terminating with-----END CERTIFICATE-----. Google Cloud does not validatethe certificate chain for you — validation is yourresponsibility.
        • If you omit the Certificate chain, your certificate should be signedby a publicly trusted CA that your clients would automatically trust.
      3. For thePrivate key certificate field, do one of the following:
        • Click theUpload button and select your private key. Your privatekey must be PEM-formatted and not protected with a passphrase.
        • Copy and paste the contents of a PEM-formatted private key. RSAprivate keys must start with-----BEGIN RSA PRIVATE KEY----- andend with-----END RSA PRIVATE KEY-----. ECDSA private keysmust start with-----BEGIN EC PRIVATE KEY----- and end with-----END EC PRIVATE KEY-----.
      4. ClickCreate.
    6. If you selectedCreate Google managed certificate,enter aDomain.
  5. To add certificate resources in addition tothe primary SSL certificate resource:
    1. ClickAdd certificate.
    2. Select a certificate from theCertificates list or clickCreate a new certificate and follow the instructions above.
  6. UnderQUIC negotiation, select one of the following options:
    • Automatic (Default) Allows Google to control when QUIC isnegotiated. Currently, when you selectAutomatic, QUIC isdisabled. By selecting this option, you are allowing Google toautomatically enable QUIC negotiations and HTTP/3 in the future forthis load balancer.Ingcloud and the API, this option is calledNONE.
    • Enabled Allows the load balancer to negotiate QUIC with clients.
    • Disabled Prevents the load balancer from negotiating QUIC withclients.
  7. ClickDone.
  8. Keep the window open to continue.

Configure the IPv6 forwarding rule

  1. ClickAdd frontend IP and port.
  2. Enter aName ofhttps-content-ipv6-rule.
  3. In theProtocol field, selectHTTPS if you want to use HTTPSbetween the client and the load balancer. SelectHTTP if you want HTTPbetween the client and the load balancer.
  4. SetIP version toIPv6.
  5. InIP, selectlb-ipv6-1, which you created earlier.
  6. The defaultPort of443 is required.
  7. If you already have an SSL certificate resourceyou want to use, select it from theCertificate drop-down menu. Ifnot, selectCreate a new certificate.
    1. Fill in aName ofwww-ssl-cert.
    2. In the appropriate fields upload yourPublic key certificate (.crt file),Certificate chain (.csr file), andPrivate key (.key file).
    3. ClickCreate.
  8. To add certificate resources in addition to theprimary SSL certificate resource:
    1. ClickAdd certificate.
    2. Select a certificate from theCertificates list or clickCreate a new certificate and follow the instructions above.
  9. UnderQUIC negotiation, select one of the following options:
    • Automatic (Default) Allows Google to control when QUIC isnegotiated. Currently, when you selectAutomatic, QUIC is disabled.By selecting this option, you are allowing Google to automaticallyenable QUIC negotiations and HTTP/3 in the future for this load balancer.Ingcloud and the API, this option is calledNONE.
    • Enabled Allows load balancer to negotiate QUIC with clients.
    • Disabled Prevents load balancer from negotiating QUIC with clients.
  10. ClickDone.

Reviewing and finalizing

  1. In the left panel of theCreate global external Application Load Balancer page, clickReview and finalize.
  2. Compare your settings to what you intended to create.
  3. If everything looks correct, clickCreate to create your external Application Load Balancer.

gcloud

  1. Create ahealth check.Use thegcloud command for HTTP if you are using HTTP between theload balancer and the backends.

    gcloud compute health-checks create http http-basic-check \    --port 80
  2. Create abackend servicefor each content provider.

    Set the--protocol field toHTTPbecause we are using HTTP to go to the instances. Use thehttp-basic-check health check we created earlier as the healthcheck.

    • 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 video-backend-service \    --load-balancing-scheme=LOAD_BALANCING_SCHEME \    --global-health-checks \    --protocol=HTTP \    --port-name=http \    --health-checks=http-basic-check \    --global
    gcloud compute backend-services create web-backend-service \    --load-balancing-scheme=LOAD_BALANCING_SCHEME \    --global-health-checks \    --protocol=HTTP \    --port-name=http \    --health-checks=http-basic-check \    --global
  3. Add your instance groups as backends to the backend services. A backenddefines the capacity (maximum backend utilization or maximum queriesper second)of the instance groups it contains. In this example, setbalancing-mode to the valueUTILIZATION,max-utilization to0.8,andcapacity-scaler to1. Setcapacity-scaler to0 ifyou wish to drain a backend service.

    Add theig-video-us instance group:

    gcloud compute backend-services add-backend video-backend-service \    --balancing-mode=UTILIZATION \    --max-utilization=0.8 \    --capacity-scaler=1 \    --instance-group=ig-video-us \    --instance-group-zone=us-central1-b \    --global

    Add theig-video-eu instance group:

    gcloud compute backend-services add-backend video-backend-service \    --balancing-mode=UTILIZATION \    --max-utilization=0.8 \    --capacity-scaler=1 \    --instance-group=ig-video-eu \    --instance-group-zone=europe-west1-b \    --global

    Add theig-www-us instance group:

    gcloud compute backend-services add-backend web-backend-service \    --balancing-mode=UTILIZATION \    --max-utilization=0.8 \    --capacity-scaler=1 \    --instance-group=ig-www-us \    --instance-group-zone=us-central1-b \    --global

    Add theig-www-eu instance group:

    gcloud compute backend-services add-backend web-backend-service \    --balancing-mode=UTILIZATION \    --max-utilization=0.8 \    --capacity-scaler=1 \    --instance-group=ig-www-eu \    --instance-group-zone=europe-west1-b \    --global
  4. Create a URL map to route the incoming requests to the appropriate backendservices. In this case, the request path mappings defined via the--path-rules flag split traffic according to the URL path in eachrequest to your site. Traffic that does not match an entry in the--path-rules list is sent to the entry in the--default-service flag.

    1. Create a URL map:

      gcloud compute url-maps create web-map \    --default-service web-backend-service
    2. Add a path matcher to your URL map and define your request pathmappings:

      gcloud compute url-maps add-path-matcher web-map \    --default-service web-backend-service \    --path-matcher-name pathmap \    --path-rules="/video=video-backend-service,/video/*=video-backend-service"
  5. Create an SSL certificate resource to use in the HTTPS proxy. To createa Google-managed certificate, you must have a domain. If you do not havea domain, you can use aself-signed SSLcertificatefor testing. For more information, seeTypes of SSL certificates.

    If you are using multiple SSL certificates, you must create an SSLcertificate resource for each certificate.

    Warning: Donot use a self-signed certificate for production purposes.

    To create a self-managed SSL certificate resource:

    gcloud compute ssl-certificates create www-ssl-cert \    --certificate [CRT_FILE_PATH] \    --private-key [KEY_FILE_PATH]

    To create a Google-managed SSL certificate resource:

    gcloud compute ssl-certificates create www-ssl-cert \  --domains [DOMAIN]
  6. Create a target HTTPS proxy to route requests to your URL map. Theproxy is the portion of the load balancer that holds the SSL certificate forHTTPS Load Balancing, so you also load your certificate in this step.

    gcloud compute target-https-proxies create https-lb-proxy \    --url-map web-map --ssl-certificates www-ssl-cert
  7. Create two global forwarding rules to route incoming requests tothe proxy, one for each of the IP addresses you created.

    gcloud compute forwarding-rules create https-content-rule \    --load-balancing-scheme=LOAD_BALANCING_SCHEME \    --network-tier=PREMIUM \    --address=lb-ipv4-1 \    --global \    --target-https-proxy=https-lb-proxy \    --ports=443
    gcloud compute forwarding-rules create https-content-ipv6-rule \    --load-balancing-scheme=LOAD_BALANCING_SCHEME \    --network-tier=PREMIUM \    --address=lb-ipv6-1 \    --global \    --target-https-proxy=https-lb-proxy \    --ports=443

After creating the global forwarding rule, it can take several minutes foryour configuration to propagate worldwide.

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.

Sending traffic to your instances

Now that you have configured your load balancing service, you can start sendingtraffic to the forwarding rule and watch the traffic go to differentinstances.

Console and Web Browser

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

    Go to Load balancing

  2. Clickweb-map to expand the load balancer you just created.

  3. In theBackend section, confirm that the instances are healthy.TheHealthy column should be populated indicating that both instancesin each of the four instance groups are healthy. If you see otherwise,first try reloading the page. It can take a few moments for theGoogle Cloud console to indicate that the instances are healthy. If thebackends do not appear healthy after a few minutes, review the firewallconfiguration and the set of network tags assigned to your backend instances.

  4. Record the IPv4 and IPv6 addresses of your load balancer:

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

      Go to External IP addresses

    2. UnderName, find the addresses namedlb-ipv4-1 andlb-ipv6-1, and then record the associated values from theExternalAddresses column.

  5. If you are using a Google-managed certificate:

    1. Create the following DNS records:

    2. Confirm that your certificate resource's status is ACTIVE. For more information, seeGoogle-managed SSL certificate resourcestatus.

  6. Test your load balancer using a web browser by going to one of the following:

    • https://IP_ADDRESS, whereIP_ADDRESS is theload balancer's IPv4 address. If your browser displays a certificate warning,you must explicitly instruct your browser to trust the certificate. Thewarning occurs because certificates are typically configured with domains,not IP addresses.

    • https://FQDN, whereFQDN is the fully qualifieddomain name (FQDN) for which you configured DNS to point to the load balancer'sIP address. If you used a self-managed, self-signed SSL certificate or a self-managedSSL certificate signed by a custom certificate authority (CA), your browserdisplays a certificate warning unless you have explicitly configured itto trust the certificate or its CA. For more details about self-managedcertificates, seeCreating a private key and certificate.

    Your browser should render a page with content showing the name of theinstance that served the page, along with its zone(for example,Page on ig-www-us-02 in us-central1-b).

  7. In your browser, go to one of the following:

    • https://IP_ADDRESS/video, whereIP_ADDRESS is the load balancer's IPv4address.

    • https://FQDN/video, whereFQDN is the FQDNfor which you configured DNS to point to the load balancer'sIP address.

    Your browser should render apage with content showing the name of thevideo instance that servedthe page, along with its zone (for example,Page on ig-video-us-02 inus-central1-b).

gcloud and using curl

Note: This example uses-k with curl to suppress its warnings about self-signedcertificates. Web applications normally use certificates signed by a certificateauthority in order to demonstrate their authenticity to clients. You can useyour own CA-signed certificate with a load balancer, or you can configureyour load balancer to issue a Google-managed certificate for a domain thatyou control.
  1. Record the IPv4 and IPv6 addresses of your load balancer:

    gcloud compute addresses describe lb-ipv4-1 \--format="get(address)" \--global
    gcloud compute addresses describe lb-ipv6-1 \--format="get(address)" \--global
  2. If you are using a Google-managed certificate:

    1. Create the following DNS records:

    2. Confirm that your certificate resource's status is ACTIVE. For moreinformation, seeGoogle-managed SSL certificate resourcestatus.

      gcloud compute ssl-certificates list
  3. Use thecurl command to test the response from these URLs. ReplaceIP_ADDRESS with the load balancer's IPv4address:

    curl -k https://IP_ADDRESS
    curl -k https://IP_ADDRESS/video/
  4. Use thecurl command to test the response from these URLs. ReplaceIP_ADDRESS with the load balancer's IPv6address. For IPv6, you must putbrackets ([]) around the address and disable globbing with the-gflag (for example,curl -g -6 "https://[2001:DB8::]/").

    curl -k -g -6 https://[IP_ADDRESS]
    curl -k -g -6 https://[IP_ADDRESS]/video/

Testing multi-region functionality

To simulate a user in a different geography, you can connect to one of yourvirtual machine instances in a different region, and then run acurl commandfrom that instance to see the request go to an instance in the region closest toit.

If you connect toig-www-us-01, running acurl command shows that therequest goes to an instance inus-central1. You see output such as thefollowing:Page on ig-www-us-02 in us-central1-b.

If you connect toig-www-eu-01, running acurl command shows that therequest goes to an instance ineurope-west1. You see output such as thefollowing:Page on ig-www-eu-02 in europe-west1-b.

You can perform tests from a client system located anywhere in the world. If backendsin one region become unhealthy or reach capacity, the HTTPS load balancerautomatically sends traffic tothe next-closestregion.

Additional configuration options

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

Enabling session affinity

These procedures demonstrate how to configure a different type of sessionaffinity for each backend service:

  • Client IP address session affinity forweb-backend-service
  • HTTP cookie session affinity forvideo-backend-service

When client IP affinity is enabled, the load balancer directs a particularclient's requests to the same backend VM based on a hash created from theclient's IP address.

When generated cookie affinity is enabled, the load balancer issues a cookieon the first request. For each subsequent request with the same cookie, the loadbalancer directs the request to the same backend VM or endpoint. Forexternal Application Load Balancers, the cookie is namedGCLB.

Console

To enable client IP session affinity forweb-backend-service:

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

    Go to Load balancing

  2. ClickBackends.

  3. Clickweb-backend-service (the name of one of the backend servicesyou created for this example) and clickEdit.

  4. On theBackend service details page, clickAdvancedconfiguration.

  5. UnderSession affinity, selectClient IP from the menu.

  6. ClickSave.

To enable generated cookie session affinity forvideo-backend-service:

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

    Go to Load balancing

  2. ClickBackends.

  3. Clickvideo-backend-service (the name of one of the backend servicesyou created for this example) and clickEdit.

  4. On theBackend service details page, clickAdvancedconfiguration.

  5. UnderSession affinity, selectGenerated cookie from the menu.

  6. ClickUpdate.

gcloud

Use the followinggcloud command to update theweb-backend-servicebackend service, specifying client IP session affinity:

gcloud compute backend-services update web-backend-service \    --session-affinity=CLIENT_IP \    --global

Use the followinggcloud command to update thevideo-backend-servicebackend service, specifying generated cookie session affinity:

gcloud compute backend-services update video-backend-service \    --session-affinity=GENERATED_COOKIE \    --global

API

To set client IP session affinity, make aPATCH request to thebackendServices/patch method.

PATCHhttps://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/global/backendServices/web-backend-service{"sessionAffinity":"CLIENT_IP"}

To set generated cookie session affinity, make aPATCH request to thebackendServices/patchmethod.

PATCHhttps://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/global/backendServices/video-backend-service{"sessionAffinity":"GENERATED_COOKIE"}

Removing external IP addresses from backend VMs

External Application Load Balancers communicate with backends using theirinternal IP addresses and specialload balancerroutes. The backend instances do not needexternal IP addresses to communicate with the load balancer. You can increasesecurity by removing the external IP addresses from your backend instances.

To remove external IP addresses from backend instances, followthesedirections.

If you need to connect using SSH to a backend instance that does not have anexternal IP address, refer toConnecting to an instance that doesn't have anexternal IPaddress.

Cleaning up

After you have finished this tutorial you can delete the resources you've made,so that you won't continue to be billed for them in the future. If theseresources were created within their own project, you can delete the entireproject. Otherwise, you can delete the resources individually.

Deleting the project

Caution: Deleting a project has the following effects:
  • Everything in the project is deleted. If you used an existing project for this tutorial, when you delete it, you also delete any other work you've done in the project.
  • Custom project IDs are lost. When you created this project, you might have created a custom project ID that you want to use in the future. To preserve the URLs that use the project ID, such as anYOUR_PROJECT_ID.REGION_ID.r.appspot.com URL, delete selected resources inside the project instead of deleting the project.

Console

  1. In the Google Cloud console, go to theProjects page.

    Go to Projects

  2. In the project list, select the project you want to delete and clickDelete.

  3. In the dialog, type thePROJECT_ID, and then clickShut down to delete the project.

gcloud

Run the following command, replacingPROJECT_ID with your project ID:

gcloud projects deletePROJECT_ID

Deleting individual resources

Console

Deleting the load balancer

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

    Go to Load balancing

  2. Select the checkbox next toweb-map.

  3. Click theDelete button at the top of the page.

  4. Select the checkboxes next to all of the additional resources, includingbackend services, health checks, and SSL certificates.

  5. ClickDelete load balancer and the selected resources.

Deleting the instance groups

  1. In the Google Cloud console, go to theInstance groups page.

    Go to Instance groups

  2. Select the checkbox at the top next toName, to select all instance groups.

  3. ClickDelete.

  4. In the confirmation window, clickDelete.

Releasing external IP addresses

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

    Go to External IP addresses

  2. Select the checkboxes next tolb-ipv4-1 andlb-ipv6-1.

  3. ClickRelease static addresses.

  4. In the confirmation window, clickDelete.

Deleting the firewall rules

  1. In the Google Cloud console, go to theFirewall policies page.

    Go to Firewall policies

  2. Select the checkboxes next tofw-allow-health-check-and-proxy andfw-allow-ssh.

  3. ClickDelete.

  4. In the confirmation window, clickDelete.

Deleting the VM instances

  1. In the Google Cloud console, go to theVM instances page.

    Go to VM instances

  2. Select the checkbox at the top next toName to select all instances.

  3. ClickDelete.

  4. In the confirmation window, clickDelete.

Deleting the VPC network

  1. In the Google Cloud console, go to theVPC networks page.

    Go to VPC networks

  2. Clicklb-network.

  3. On the network details page, clickDelete VPC network.

  4. In the confirmation window, clickDelete.

gcloud

Note: You must entery after each command to confirm deletion.

Deleting the load balancer

To delete the load balancer, you'll need to delete each of its components.

  1. Delete the forwarding rules:

    gcloud compute forwarding-rules delete https-content-rule \    --global
    gcloud compute forwarding-rules delete https-content-ipv6-rule \    --global
  2. Delete the global external IP addresses:

    gcloud compute addresses delete lb-ipv4-1 \    --global
    gcloud compute addresses delete lb-ipv6-1 \    --global
  3. Delete the target proxy:

    gcloud compute target-https-proxies delete https-lb-proxy
  4. Delete the SSL certificate:

    gcloud compute ssl-certificates delete www-ssl-cert
  5. Delete the URL map:

    gcloud compute url-maps delete web-map
  6. Delete the backend services:

    gcloud compute backend-services delete web-backend-service \    --global
    gcloud compute backend-services delete video-backend-service \    --global
  7. Delete the health checks:

    gcloud compute health-checks delete http-basic-check

You have deleted all of the load balancer resources.

Deleting the instance groups

Repeat the following command to delete four unmanaged instance groups, usingthe following name and zone combinations. ReplaceINSTANCE_GROUP_NAME andZONE accordingly:

  • Name:ig-www-us, zone:us-central1-b
  • Name:ig-video-us, zone:us-central1-b
  • Name:ig-www-eu, zone:europe-west1-b
  • Name:ig-video-eu, zone:europe-west1-b
gcloud compute instance-groups unmanaged deleteINSTANCE_GROUP_NAME \   --zone=ZONE

Deleting the VM instances

Repeat the following command to delete eight VMs, using the following nameand zone combinations. ReplaceVM_NAME andZONEaccordingly:

  • Name:ig-www-us-01, zone:us-central1-b
  • Name:ig-www-us-02, zone:us-central1-b
  • Name:ig-video-us-01, zone:us-central1-b
  • Name:ig-video-us-02, zone:us-central1-b
  • Name:ig-www-eu-01, zone:europe-west1-b
  • Name:ig-www-eu-02, zone:europe-west1-b
  • Name:ig-video-eu-01, zone:europe-west1-b
  • Name:ig-video-eu-02, zone:europe-west1-b
gcloud compute instances deleteVM_NAME \   --zone=ZONE

Deleting the firewall rules

Delete both firewall rules:

gcloud compute firewall-rules delete fw-allow-health-check-and-proxy
gcloud compute firewall-rules delete fw-allow-ssh

Deleting the VPC network

  1. Delete theus-subnet:

    gcloud compute networks subnets delete us-subnet \--region=us-central1
  2. Delete theeu-subnet:

    gcloud compute networks subnets delete eu-subnet \--region=europe-west1
  3. Delete the VPC network:

    gcloud compute networks delete lb-network

You have deleted all of the resources that you set up in this project.

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.