Overview and What You Will Learn
An Elastic Load Balancer (ELB) spreads incoming traffic across healthy targets in several Availability Zones, so no single server is overloaded or a single point of failure. AWS offers the Application Load Balancer (ALB), Network Load Balancer (NLB) and Gateway Load Balancer (GWLB), each for a different job. In this lab you build an ALB with two instances, lock the instances down behind it, add a routing rule, and test failover, all from the AWS CLI.
By the end you will be able to:
- Pick ALB, NLB or GWLB for a workload
- Route by path, host, header and query string, and use dynamic port mapping for containers
- Design health checks that remove broken targets without causing a wider outage
- Set up security groups so targets are reachable only through the load balancer
- Configure sticky sessions, cross-zone balancing, TLS termination with SNI, and deregistration delay
- Connect a load balancer to an Auto Scaling Group
- Diagnose 502, 503 and 504 errors
Why This Matters in Production
During an e-commerce flash sale, traffic can jump tenfold in a minute, and a single instance would fail. A load balancer spreads that traffic, health-checks each target, stops sending requests to broken ones, and works with Auto Scaling to add capacity as load grows. It is also the single public entry point, so the application servers can stay private.
Most production incidents here are configuration mistakes: a security group that exposes the instances directly, a health check that takes the whole fleet out of service, or a timeout mismatch that returns 502 errors. Knowing how each load balancer type behaves prevents them.
Core Principles
Why Do You Need a Load Balancer?
A load balancer gives you one stable address in front of many servers and removes the single-server failure mode. Users talk to the load balancer, and it decides which backend handles each request.
- Traffic distribution, so no server is overwhelmed
- One DNS name no matter how many servers run behind it
- Continuous health checks that stop traffic to failed targets
- TLS termination, so certificates are managed at the load balancer
- High availability across AZs, with traffic routed away from a failed zone
- Private servers, because only the load balancer needs a public address
A managed ELB saves you from patching, scaling and securing your own nginx or HAProxy fleet, and it integrates with Auto Scaling, ECS, ACM, WAF, CloudWatch and Route 53.
Which Load Balancer Type Should You Choose?
Use ALB for web applications, NLB for TCP or UDP traffic, static IPs and extreme throughput, and GWLB for inserting security appliances. The Classic Load Balancer is legacy, and AWS recommends migrating to ALB or NLB.
| Type | Layer | Choose when |
|---|---|---|
| ALB | 7, HTTP and gRPC | Web apps, microservices, containers |
| NLB | 4, TCP and UDP | Static IPs, non-HTTP, very high throughput |
| GWLB | 3, IP packets | Firewalls and inspection appliances |
How Do Health Checks Work, and How Should You Design /health?
The load balancer probes each target on a protocol, port and path, and routes traffic only to targets that pass. Intervals and thresholds are configurable and differ by load balancer type, so read the defaults for yours. A target is marked unhealthy after consecutive failures and added back after consecutive successes.
Design the health check to answer one question: can this instance serve traffic? A shallow check, where the process is up and can respond, is the safe default. If the health check fails whenever a shared dependency such as the database is down, every instance fails together and the whole service goes out at once. When all targets are unhealthy, an ALB sends traffic to all of them anyway (fail open), but you have still turned a partial problem into a full outage.
- Use a shallow
/healthfor the load balancer - Expose deeper dependency checks on a separate path for monitoring and alerts
- Use the success code matcher to define what counts as healthy, such as 200
from flask import Flask, jsonify app = Flask(__name__) def health(): # Shallow check: the process is running and can answer requests return jsonify(dict(status='ok')), 200 def health_deep(): # Dependency checks for dashboards and alerts, not for the load balancer checks = dict() try: db.execute('SELECT 1') checks['database'] = 'ok' except Exception: checks['database'] = 'failed' return jsonify(checks), 503 return jsonify(checks), 200How Do You Secure Targets Behind a Load Balancer?
Allow traffic to the instances only from the load balancer's security group, never from the internet. Give the load balancer a security group that accepts ports 80 and 443 from anywhere, and give the instances a security group that accepts the application port with the load balancer's group as the source.
| Security group | Inbound rule | Source |
|---|---|---|
| Load balancer | 80 and 443 | 0.0.0.0/0 |
| Instances | 80 | Load balancer security group ID |
SecurityIf the instance security group allows 0.0.0.0/0, anyone can bypass the load balancer and its WAF and hit the instance directly. Also keep SSH closed to the internet.
What Does an Application Load Balancer Do?
An ALB reads HTTP requests and routes them by their content, so one ALB can front many services. Listener rules match on path, hostname, header, query string, HTTP method or source IP, and forward to different target groups. It supports HTTP/2, WebSocket and gRPC, and rules can also redirect, return a fixed response, or authenticate users with OIDC or Cognito.
- Path: myapp.in/users goes to the users service
- Host: api.example.in and admin.example.in go to different groups
- Query string: ?Platform=Mobile goes to the mobile backend
- Header: a custom header or User-Agent value picks a backend
- One ALB replaces several load balancers and their cost
ALB target types are instances, IP addresses (private addresses, including on-premises over VPN or Direct Connect) and Lambda functions.
How Does ALB Dynamic Port Mapping Work with Containers?
With ECS on EC2 and bridge networking, each container gets a random host port, and ECS registers that port with the target group automatically. The ALB then routes to each container on its own port, and removes it when the task stops. With the awsvpc network mode, each task has its own IP address and port, so dynamic ports are not needed.
How Do You Get the Real Client IP Behind an ALB?
Read the X-Forwarded-For header, because the instance sees the ALB's address as the connection source. The ALB also adds X-Forwarded-Proto and X-Forwarded-Port.
Client 12.34.56.78 -> ALB adds:X-Forwarded-For: 12.34.56.78X-Forwarded-Proto: httpsX-Forwarded-Port: 443RememberApplications that log IPs or rate-limit must use X-Forwarded-For, not the socket address. An NLB with instance targets preserves the client IP by default.
When Should You Use a Network Load Balancer?
Use an NLB when you need a static IP, non-HTTP protocols, or very high throughput with low latency. It forwards TCP, UDP and TLS traffic at Layer 4 without inspecting HTTP content.
- One static IP per AZ, with optional Elastic IPs for client allow-lists
- Handles millions of requests per second with lower latency than an ALB
- Can terminate TLS, and supports health checks over TCP, HTTP and HTTPS
- Cross-zone balancing is off by default
- Targets can be instances, IP addresses or an ALB, so NLB in front of ALB gives static IPs plus Layer 7 routing
- NLBs are the basis of AWS PrivateLink endpoint services
- NLBs can have security groups attached, and without one the targets' own security groups must allow client traffic
Use an ALB instead when you need path or host routing, or are serving normal web traffic.
What Does a Gateway Load Balancer Do?
A GWLB inserts a fleet of third-party security appliances, such as firewalls and intrusion detection, into the traffic path transparently. Route tables send traffic to a Gateway Load Balancer endpoint, which forwards packets to the GWLB, which spreads them across the appliances using the GENEVE protocol on port 6081. Safe traffic returns and continues, and malicious traffic is dropped by the appliance.
What Are Sticky Sessions and Should You Use Them?
Sticky sessions send a user to the same target for a period, using a cookie. They solve problems where session data lives in instance memory, but they can unbalance load. A better design stores sessions in ElastiCache or DynamoDB so any instance can serve any user.
- Duration-based: The load balancer sets the AWSALB cookie for a time you choose
- Application-based: The load balancer sets AWSALBAPP, or uses a cookie name that your application defines
- NLB offers source IP affinity instead
Common MistakeRelying on stickiness to hold state. Heavy sticky users pile onto one instance, and a replaced instance loses the session. Move state out of the instance.
How Does Cross-Zone Load Balancing Work?
With cross-zone balancing, each load balancer node spreads requests across targets in every AZ, which evens out uneven instance counts. It is always available for ALB with no inter-AZ data charge, though you can turn it off per target group. For NLB and GWLB it is off by default, and enabling it incurs inter-AZ data transfer charges.
How Do TLS Termination and SNI Work?
The load balancer decrypts HTTPS using a certificate from ACM and forwards plain HTTP to targets inside the VPC, so instances do not manage certificates. Server Name Indication lets one ALB or NLB hold several certificates and pick the right one from the hostname in the TLS handshake. A Classic Load Balancer can hold only one certificate.
- Use an HTTPS listener with a TLS security policy, and ACM certificates
- Add a redirect rule on port 80 that sends HTTP to HTTPS
- ALB also supports mutual TLS where clients present certificates
What Is Deregistration Delay, and What About Slow Start?
Deregistration delay, called connection draining on Classic Load Balancers, lets in-flight requests finish before a target is removed. The load balancer stops sending new requests to a deregistering target and waits up to the delay, 300 seconds by default and configurable from 0 to 3600, before cutting it off. Set it to match your longest request. Slow start gradually ramps traffic to a new target so it can warm up.
How Does a Load Balancer Work with Auto Scaling?
Attach the target group to the Auto Scaling Group, and instances register and deregister automatically as the group scales. Turn on the ELB health check type on the ASG so unhealthy instances are replaced and not only removed from rotation. The ASG waits for the deregistration delay when scaling in.
Detailed Step-by-Step Practical Lab
This lab uses the default VPC in ap-south-1 and builds an ALB with two instances in two AZs. Instances and the load balancer cost money while they run, so clean up when you finish.
Step 1: Gather network details and an AMI
export AWS_REGION=ap-south-1 VPC_ID=$(aws ec2 describe-vpcs --filters Name=isDefault,Values=true \ --query 'Vpcs[0].VpcId' --output text) SUBNET_A=$(aws ec2 describe-subnets \ --filters Name=vpc-id,Values=$VPC_ID Name=availability-zone,Values=ap-south-1a \ --query 'Subnets[0].SubnetId' --output text)SUBNET_B=$(aws ec2 describe-subnets \ --filters Name=vpc-id,Values=$VPC_ID Name=availability-zone,Values=ap-south-1b \ --query 'Subnets[0].SubnetId' --output text) AMI=$(aws ssm get-parameter \ --name /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 \ --query Parameter.Value --output text)Step 2: Create the two security groups
ALB_SG=$(aws ec2 create-security-group --group-name devops-alb-sg \ --description "ALB" --vpc-id $VPC_ID --query GroupId --output text)aws ec2 authorize-security-group-ingress --group-id $ALB_SG \ --protocol tcp --port 80 --cidr 0.0.0.0/0 EC2_SG=$(aws ec2 create-security-group --group-name devops-ec2-sg \ --description "Instances" --vpc-id $VPC_ID --query GroupId --output text) aws ec2 authorize-security-group-ingress --group-id $EC2_SG \ --protocol tcp --port 80 --source-group $ALB_SGStep 3: Launch two web servers
cat > userdata-1.sh <<'EOF'#!/bin/bashdnf install -y nginxecho "<h1>Server 1 in ap-south-1a</h1>" > /usr/share/nginx/html/index.htmlsystemctl enable --now nginxEOF sed 's/Server 1 in ap-south-1a/Server 2 in ap-south-1b/' userdata-1.sh > userdata-2.sh I1=$(aws ec2 run-instances --image-id $AMI --instance-type t3.micro \ --subnet-id $SUBNET_A --security-group-ids $EC2_SG \ --user-data file://userdata-1.sh \ --query 'Instances[0].InstanceId' --output text)I2=$(aws ec2 run-instances --image-id $AMI --instance-type t3.micro \ --subnet-id $SUBNET_B --security-group-ids $EC2_SG \ --user-data file://userdata-2.sh \ --query 'Instances[0].InstanceId' --output text) aws ec2 wait instance-running --instance-ids $I1 $I2Step 4: Create the target group and register the instances
TG_ARN=$(aws elbv2 create-target-group --name devops-tg \ --protocol HTTP --port 80 --vpc-id $VPC_ID \ --health-check-path / \ --query 'TargetGroups[0].TargetGroupArn' --output text) aws elbv2 register-targets --target-group-arn $TG_ARN \ --targets Id=$I1 Id=$I2Step 5: Create the ALB and a listener
ALB_ARN=$(aws elbv2 create-load-balancer --name devops-alb \ --subnets $SUBNET_A $SUBNET_B --security-groups $ALB_SG \ --query 'LoadBalancers[0].LoadBalancerArn' --output text) aws elbv2 create-listener --load-balancer-arn $ALB_ARN \ --protocol HTTP --port 80 \ --default-actions Type=forward,TargetGroupArn=$TG_ARN aws elbv2 wait load-balancer-available --load-balancer-arns $ALB_ARN ALB_DNS=$(aws elbv2 describe-load-balancers --load-balancer-arns $ALB_ARN \ --query 'LoadBalancers[0].DNSName' --output text)Step 6: Test distribution
aws elbv2 wait target-in-service --target-group-arn $TG_ARN --targets Id=$I1 Id=$I2 for i in 1 2 3 4 5 6; do curl -s http://$ALB_DNS/; doneThe responses alternate between Server 1 and Server 2. Direct requests to an instance's public IP time out, because only the ALB security group may reach it.
Step 7: Add a path-based rule
LISTENER_ARN=$(aws elbv2 describe-listeners --load-balancer-arn $ALB_ARN \ --query 'Listeners[0].ListenerArn' --output text) aws elbv2 create-rule --listener-arn $LISTENER_ARN --priority 10 \ --conditions Field=path-pattern,Values=/orders/* \ --actions 'Type=fixed-response,FixedResponseConfig={StatusCode=200,ContentType=text/plain,MessageBody=orders-service}' curl -s http://$ALB_DNS/orders/123The orders path returns the fixed response, while other paths still reach the web servers.
Step 8: Test health check failover
aws ec2 stop-instances --instance-ids $I1 # After about a minute, server 1 is unhealthyaws elbv2 describe-target-health --target-group-arn $TG_ARN \ --query 'TargetHealthDescriptions[].[Target.Id,TargetHealth.State]' --output table for i in 1 2 3 4; do curl -s http://$ALB_DNS/; doneOnly Server 2 responds. Start the instance again with aws ec2 start-instances --instance-ids $I1 and it rejoins after it passes the health check.
Step 9: Clean up
aws elbv2 delete-load-balancer --load-balancer-arn $ALB_ARNaws ec2 terminate-instances --instance-ids $I1 $I2aws ec2 wait instance-terminated --instance-ids $I1 $I2 # Wait a minute for the ALB network interfaces to releaseaws elbv2 delete-target-group --target-group-arn $TG_ARNaws ec2 delete-security-group --group-id $EC2_SGaws ec2 delete-security-group --group-id $ALB_SGProduction Best Practices & Common Pitfalls
- Lock down instance security groups: Allow only the load balancer's security group.
- Use shallow health checks: Keep dependency checks out of the load balancer's health check path.
- Use ALB for HTTP, NLB for the rest: Choose NLB for static IPs, UDP or extreme throughput.
- Use HTTPS with ACM: Redirect port 80 to 443 and use a current TLS policy.
- Spread across at least two AZs: Keep targets in each enabled AZ.
- Store sessions externally: Prefer ElastiCache over sticky sessions.
- Match timeouts: Set the backend keep-alive timeout higher than the ALB idle timeout, which is 60 seconds by default.
- Set deregistration delay to your longest request: Avoid dropped requests during deploys.
- Turn on access logs: Send them to S3 to investigate errors and traffic.
- Add WAF to internet-facing ALBs: Filter bad requests at the edge.
Common MistakeBuilding a health check that fails when any dependency fails. A database outage then marks every instance unhealthy at once and removes capacity exactly when you need it.
TipIn the target group's health status, read the failure reason code for the last failed check. It usually names the cause faster than logging in to the instance.
Quick Reference & Troubleshooting Commands
| Task | Command |
|---|---|
| List load balancers | aws elbv2 describe-load-balancers |
| List target groups | aws elbv2 describe-target-groups |
| Check target health | aws elbv2 describe-target-health --target-group-arn <ARN> |
| Register a target | aws elbv2 register-targets --target-group-arn <ARN> --targets Id=<i-id> |
| Deregister a target | aws elbv2 deregister-targets --target-group-arn <ARN> --targets Id=<i-id> |
| List listeners | aws elbv2 describe-listeners --load-balancer-arn <ARN> |
| List rules | aws elbv2 describe-rules --listener-arn <ARN> |
| Problem | Likely cause and fix |
|---|---|
| 502 Bad Gateway | Target closed the connection or sent an invalid response. Raise the backend keep-alive above the ALB idle timeout. |
| 503 Service Unavailable | No registered healthy targets, or none in the listener's target group. Check target health. |
| 504 Gateway Timeout | Target did not respond within the idle timeout. Check app performance and timeouts. |
| All targets unhealthy | Wrong health path or port, or the instance security group blocks the load balancer. |
| Instance reachable from the internet | Instance security group allows 0.0.0.0/0. Restrict it to the load balancer group. |
| Uneven traffic | Sticky sessions on, or cross-zone off with uneven instance counts. |
| Connections drop during deployments | Deregistration delay shorter than the longest request. |