Load Balancer
In our Lego city analogy, the load balancer is like the traffic controller at the city gates. Without it, all cars (user requests) would pile up at a single road, causing jams and failures.
A load balancer ensures traffic is evenly distributed across multiple servers, checks their health, and reroutes traffic if one fails. In Terraform, we’ll configure an Application Load Balancer (ALB) to provide scalability, fault tolerance, and secure entry points for our 3‑tier app.
Key Concepts
1. Application Load Balancer (ALB)
- Definition: Distributes incoming traffic across multiple EC2 instances.
- Features:
- Layer 7 (HTTP/HTTPS) routing.
- Health checks for resilience.
- SSL termination for secure traffic.
2. Target Groups
- Define groups of EC2 instances or auto‑scaling groups.
- ALB routes traffic to healthy targets only.
- Example: Web tier EC2 instances in public subnets.
3. Listeners
- Define how ALB listens for traffic.
- Example:
- Port 80 → HTTP traffic.
- Port 443 → HTTPS traffic with SSL certificate.
4. Health Checks
- ALB continuously checks instance health.
- Routes traffic only to healthy instances.
- Example:
/healthendpoint on web servers.
Hands‑On Lab / Demo
Lab: Deploying ALB with Terraform
Create Listener:
resource "aws_lb_listener" "http_listener" {
load_balancer_arn = aws_lb.app_lb.arn
port = 80
protocol = "HTTP"
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.web_tg.arn
}
}
Create ALB:
resource "aws_lb" "app_lb" {
name = "app-lb"
internal = false
load_balancer_type = "application"
subnets = [aws_subnet.public1.id, aws_subnet.public2.id]
security_groups = [aws_security_group.web_sg.id]
}
Create Target Group:
resource "aws_lb_target_group" "web_tg" {
name = "web-tg"
port = 80
protocol = "HTTP"
vpc_id = aws_vpc.main.id
health_check {
path = "/health"
interval = 30
}
}
Pro Tips & Best Practices
- Always enable health checks for resilience.
- Use HTTPS with SSL certificates for secure traffic.
- Spread ALB across multiple AZs for high availability.
- Tag load balancers for easy identification.
- Document listener and target group configurations.
Summary & Cheatsheet
- ALB = Traffic controller.
- Target groups = Destination servers.
- Listeners = Entry points (HTTP/HTTPS).
- Health checks = Ensure resilience.
Quick mnemonic: ALB → Targets → Listeners → Health
The Hackers Notebook
The load balancer is the gateway to your 3‑tier infrastructure, ensuring traffic is distributed evenly, securely, and reliably. By configuring ALB with listeners, target groups, and health checks, you’ve added resilience and scalability to the web tier.
