Forwarding traffic to multiple target groups with path-based routing in ALB

TOC

Configuration of ALB for path-based routing

ALB supports path-based routing.

If you have a listener with a default rule that forwards requests to one target group, you can add a rule that forwards requests to another target group based on URL.

Add path-based routing

In this example, we will prepare two EC2 instances and route the traffic according to the URL.

Environment

Diagram of fowarding traffic to multiple target groups with Path-based routing in ALB.

Create two ALB target groups, and place one EC2 instance in each group.
Install Apache on the two instances and run them as web servers.

CloudFormation Template Files

We will build the above configuration using CloudFormation. We have placed the CloudFormation template at the following URL.

https://github.com/awstut-an-r/awstut-fa/tree/main/029

Explanation of key points of template files

The configuration for this project is generally the same as the following page.

あわせて読みたい
Attaching instances in private subnet to ALB 【Configure instances in private subnets to be attached to ALB】 We will see how to attach an instance located in a private subnet to an ALB. The following m...

For information on how to attach the EC2 instances in the private subnet to the ALB and how to run yum on the EC2 instants in the private subnet, please refer to the above page. The difference is that we are using path-based routing. Therefore, this page will focus on the content related to it.
When doing path-based routing, the following two resources are the key.

  • Target group
  • Listener rules

We will check them in order.

Target Group

In this configuration, we will separate the two instances into different groups. Therefore, the key point is to create two target groups.

Resources:
  ALBTargetGroup1:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      VpcId: !Ref VPC
      Name: !Sub "${Prefix}-ALBTargetGroup1"
      Protocol: HTTP
      Port: !Ref HTTPPort
      HealthCheckProtocol: HTTP
      HealthCheckPath: /
      HealthCheckPort: traffic-port
      HealthyThresholdCount: !Ref HealthyThresholdCount
      UnhealthyThresholdCount: !Ref UnhealthyThresholdCount
      HealthCheckTimeoutSeconds: !Ref HealthCheckTimeoutSeconds
      HealthCheckIntervalSeconds: !Ref HealthCheckIntervalSeconds
      Matcher:
        HttpCode: !Ref HttpCode
      Targets:
        - Id: !Ref Instance1
      TargetType: instance

  ALBTargetGroup2:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      Name: !Sub "${Prefix}-ALBTargetGroup2"
      ...
Code language: YAML (yaml)

No special configuration is required to perform path-based routing. This time, we will create two target groups with exactly the same settings.

Listener Rules

In the listener rule, set the URL and the corresponding target group.

Resources:
  ALBListener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      DefaultActions:
        - TargetGroupArn: !Ref ALBTargetGroup1
          Type: forward
      LoadBalancerArn: !Ref ALB
      Port: !Ref HTTPPort
      Protocol: HTTP

  ALBListenerRule1:
    Type: AWS::ElasticLoadBalancingV2::ListenerRule
    Properties:
      Actions:
        - TargetGroupArn: !Ref ALBTargetGroup1
          Type: forward
      Conditions:
        - Field: path-pattern
          PathPatternConfig:
            Values:
              - /instance1/*
      ListenerArn: !Ref ALBListener
      Priority: 1

  ALBListenerRule2:
    Type: AWS::ElasticLoadBalancingV2::ListenerRule
    Properties:
      Actions:
        - TargetGroupArn: !Ref ALBTargetGroup2
          Type: forward
      Conditions:
        - Field: path-pattern
          PathPatternConfig:
            Values:
              - /instance2/*
      ListenerArn: !Ref ALBListener
      Priority: 2
Code language: YAML (yaml)

As a prerequisite, we need to set the default action, i.e. the default traffic destination, for the listener resource, which can be set in the DefaultActions property. In this case, we will set the ALBTargetGroup1.
In the TargetGroupArn property, specify the target group to be targeted. The associated URL can be set in the Conditions property, where the “path-pattern” is specified in the Field property and the URL is specified in the PathPatternConfig property.
To summarize the above, we will set the following.

  • /: ALBTargetGroup1(Instance1)
  • /instance1/:ALBTargetGroup1(Instance1)
  • /instance2/: ALBTargetGroup2(Instance2)

(Reference) Instance initialization

We will configure two EC2 instances as a web server, and we will do this with UserData.

Resources:
  Instance1:
    Type: AWS::EC2::Instance
    Properties:
      UserData: !Base64 |
        #!/bin/bash -xe
        yum update -y
        yum install -y httpd
        systemctl start httpd
        systemctl enable httpd
        echo 'path: "/"' >> /var/www/html/index.html
        ec2-metadata -i >> /var/www/html/index.html

        mkdir /var/www/html/instance1
        echo 'path: "/isntace1/"' >> /var/www/html/instance1/index.html
        ec2-metadata -i >> /var/www/html/instance1/index.html

  Instance2:
    Type: AWS::EC2::Instance
    Properties:
      UserData: !Base64 |
        #!/bin/bash -xe
        yum update -y
        yum install -y httpd
        systemctl start httpd
        systemctl enable httpd

        mkdir /var/www/html/instance2
        echo 'path: "/isntace2/"' >> /var/www/html/instance2/index.html
        ec2-metadata -i >> /var/www/html/instance2/index.html
Code language: YAML (yaml)

After installing and starting Apache with yum, create and place HTML files in each directory.
What you need to pay attention to is the position where you place the contents. It must be placed at the location corresponding to the URL mentioned above.

The path pattern is used to route requests but does not alter them. For example, if a rule has a path pattern of /img/*, the rule forwards a request for /img/picture.jpg to the specified target group as a request for /img/picture.jpg.

Listeners for your Application Load Balancers

Following the above, place the HTML file at the location corresponding to the URL as seen from the document root.

Architecting

We will use CloudFormation to build this environment and check the actual behavior.

Create CloudFormation stacks and check resources in stacks

We will create a CloudFormation stack.
For information on how to create a stack and check each stack, please refer to the following page

あわせて読みたい
CloudFormation’s nested stack 【How to build an environment with a nested CloudFormation stack】 Examine nested stacks in CloudFormation. CloudFormation allows you to nest stacks. Nested ...

After checking the resources of each stack, the information of the main resources created this time is as follows.

  • ALB: fa-029-ALB
  • Target group 1: fa-029-ALBTargetGroup1
  • Target group 2: fa-029-ALBTargetGroup2
  • Instance 1: i-06542b7318333fd34
  • Instance 2: i-0d3bdfef3f2f83533

We will also check the resource creation status from the AWS Management Console. First, we will check the ALB.

The ALB has been created successfully.

The ALB has been created.

Next, we will check the listener rules. You can access the rules from the Listener page.

Access the listener rules page.
Listener Rules.

Next, check the target groups.

ALB Target Group 1
ALB Target Group 2

You can see that instances have been registered in each target group.

Operation check

Now that everything is ready, let’s access the ALB.

First is the root page (“/”).

Go to the root page of ALB.

We got a response from instance 1. This means that the traffic has been routed to instance 1 registered in target group 1, as configured in the default action.

Next, access “/instance1/”.

Path-based routing 1

We received a response from instance 1 as well. According to the first line of the listener rule, the traffic was routed to target group 1.

Finally, access “/instance2/”.

Path-based routing 2

The response came from instance 2. It was routed to target group 2 according to the second line of the listener rule.

Summary

We have now confirmed how to forward traffic to multiple target groups using path-based routing in ALB.

TOC