How can I configure an AWS load balancer listener for routing the traffic to different target groups?

264    Asked by AashnaSaito in AWS , Asked on Apr 15, 2024

 I am currently engaged in a particular task that is related to architecting a highly available web-based application on AWS by using elastic load balancing (ELB) to distribute incoming traffic. How can I configure an AWS load balancer listener to route the traffic to different target groups based on the URL paths?

Answered by Carole Thom

In the context of AWS, here is how you can configure an AWS load balancer listener to route the traffic based on URL paths to different target groups:-

Listeners Configuration

Firstly, try to create an application load balancer or even a network load balancer in your AWS account. You can configure the HTTP/HTTPS listeners on the load balancer for listening on the desired port.

Target group Configuration

You can create multiple target groups, each related to a different application or path within your web-based application.

Listener rules

You should Configure the listener's rules on the load balancer to route the incoming request to the respective target group based on the URL paths.

Here is the example given below of how you can configure an ALB listener with listeners rules in Python programming language by using the Boto3:-

Import boto3

# Initialize Boto3 client for ALB
Elbv2_client = boto3.client(‘elbv2’)
# Create target groups
Response_app1 = elbv2_client.create_target_group(
    Name=’targetGroupApp1’,
    Protocol=’HTTP’,
    Port=80,
    VpcId=’your_vpc_id’
)
Target_group_app1_arn = response_app1[‘TargetGroups’][0][‘TargetGroupArn’]
Response_app2 = elbv2_client.create_target_group(
    Name=’targetGroupApp2’,
    Protocol=’HTTP’,
    Port=80,
    VpcId=’your_vpc_id’
)
Target_group_app2_arn = response_app2[‘TargetGroups’][0][‘TargetGroupArn’]
# Create ALB listener
Response_listener = elbv2_client.create_listener(
    LoadBalancerArn=’your_alb_arn’,
    Protocol=’HTTP’,
    Port=80,
    DefaultActions=[
        {
            ‘Type’: ‘forward’,
            ‘TargetGroupArn’: target_group_app1_arn,
        }
    ]
)
Listener_arn = response_listener[‘Listeners’][0][‘ListenerArn’]
# Add listener rules for path-based routing
Elbv2_client.create_rule(
    ListenerArn=listener_arn,
    Conditions=[
        {
            ‘Field’: ‘path-pattern’,
            ‘Values’: [‘/app1/*’]
        }
    ],
    Actions=[
        {
            ‘Type’: ‘forward’,
            ‘TargetGroupArn’: target_group_app1_arn,
        }
    ]
)
Elbv2_client.create_rule(
    ListenerArn=listener_arn,
    Conditions=[
        {
            ‘Field’: ‘path-pattern’,
            ‘Values’: [‘/app2/*’]
        }
    ],
    Actions=[
        {
            ‘Type’: ‘forward’,
            ‘TargetGroupArn’: target_group_app2_arn,
        }
    ]
)


Your Answer

Interviews

Parent Categories