Bird
Raised Fist0
AWScloud~5 mins

Application Load Balancer (ALB) in AWS - Commands & Configuration

Choose your learning style10 modes available
Introduction
When you run multiple copies of your app on different servers, you need a way to share incoming user traffic evenly. An Application Load Balancer (ALB) helps by automatically sending user requests to the best server available. This keeps your app fast and reliable.
When you want to spread web traffic across several servers to avoid overload.
When you need to route users to different app versions based on the URL path.
When you want to improve app availability by automatically handling server failures.
When you want to secure your app with HTTPS by managing SSL certificates on the load balancer.
When you want to monitor and control traffic with detailed health checks and logging.
Config File - alb-setup.tf
alb-setup.tf
provider "aws" {
  region = "us-east-1"
}

resource "aws_security_group" "alb_sg" {
  name        = "alb-security-group"
  description = "Allow HTTP and HTTPS traffic"
  vpc_id      = "vpc-0abcd1234efgh5678"

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_lb" "app_alb" {
  name               = "example-app-alb"
  internal           = false
  load_balancer_type = "application"
  security_groups    = [aws_security_group.alb_sg.id]
  subnets            = ["subnet-0123456789abcdef0", "subnet-0fedcba9876543210"]
}

resource "aws_lb_target_group" "app_tg" {
  name     = "example-app-tg"
  port     = 80
  protocol = "HTTP"
  vpc_id   = "vpc-0abcd1234efgh5678"

  health_check {
    path                = "/health"
    protocol            = "HTTP"
    matcher             = "200"
    interval            = 30
    timeout             = 5
    healthy_threshold   = 3
    unhealthy_threshold = 3
  }
}

resource "aws_lb_listener" "http_listener" {
  load_balancer_arn = aws_lb.app_alb.arn
  port              = 80
  protocol          = "HTTP"

  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.app_tg.arn
  }
}

This Terraform file creates an Application Load Balancer (ALB) in AWS.

  • aws_security_group.alb_sg: Allows web traffic on ports 80 (HTTP) and 443 (HTTPS).
  • aws_lb.app_alb: Defines the ALB with public subnets and the security group.
  • aws_lb_target_group.app_tg: Groups backend servers listening on port 80 with health checks on /health.
  • aws_lb_listener.http_listener: Listens on port 80 and forwards requests to the target group.
Commands
This command initializes Terraform in the current folder. It downloads the AWS provider plugin needed to create resources.
Terminal
terraform init
Expected OutputExpected
Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/aws... - Installing hashicorp/aws v4.60.0... - Installed hashicorp/aws v4.60.0 (signed by HashiCorp) Terraform has been successfully initialized!
This command shows what Terraform will create or change in AWS based on the configuration file.
Terminal
terraform plan
Expected OutputExpected
An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # aws_lb.app_alb will be created + resource "aws_lb" "app_alb" { + arn = (known after apply) + dns_name = (known after apply) + id = (known after apply) + internal = false + load_balancer_type = "application" + name = "example-app-alb" + security_groups = [ + "sg-0a1b2c3d4e5f6g7h8", ] + subnets = [ + "subnet-0123456789abcdef0", + "subnet-0fedcba9876543210", ] } Plan: 4 to add, 0 to change, 0 to destroy.
This command creates the ALB and related resources in AWS without asking for confirmation.
Terminal
terraform apply -auto-approve
Expected OutputExpected
aws_security_group.alb_sg: Creating... aws_security_group.alb_sg: Creation complete after 2s [id=sg-0a1b2c3d4e5f6g7h8] aws_lb.app_alb: Creating... aws_lb_target_group.app_tg: Creating... aws_lb_listener.http_listener: Creating... aws_lb.app_alb: Creation complete after 10s [id=arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/example-app-alb/50dc6c495c0c9188] aws_lb_target_group.app_tg: Creation complete after 3s [id=arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/example-app-tg/6d0ecf831eec9f09] aws_lb_listener.http_listener: Creation complete after 2s [id=arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/example-app-alb/50dc6c495c0c9188/6f0ecf831eec9f09] Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
→
-auto-approve - Skips manual confirmation to apply changes immediately
This AWS CLI command checks that the ALB was created and shows its details.
Terminal
aws elbv2 describe-load-balancers --names example-app-alb
Expected OutputExpected
{ "LoadBalancers": [ { "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/example-app-alb/50dc6c495c0c9188", "DNSName": "example-app-alb-1234567890.us-east-1.elb.amazonaws.com", "CanonicalHostedZoneId": "Z35SXDOTRQ7X7K", "CreatedTime": "2024-06-01T12:00:00.000Z", "LoadBalancerName": "example-app-alb", "Scheme": "internet-facing", "VpcId": "vpc-0abcd1234efgh5678", "State": { "Code": "active" }, "Type": "application", "AvailabilityZones": [ { "ZoneName": "us-east-1a", "SubnetId": "subnet-0123456789abcdef0" }, { "ZoneName": "us-east-1b", "SubnetId": "subnet-0fedcba9876543210" } ] } ] }
→
--names - Specifies the ALB name to describe
Key Concept

If you remember nothing else from this pattern, remember: an Application Load Balancer automatically spreads user traffic across healthy servers to keep your app fast and available.

Common Mistakes
Not attaching the correct security group allowing HTTP/HTTPS traffic to the ALB
The ALB will not accept incoming user requests, so your app will be unreachable.
Create and attach a security group that allows inbound traffic on ports 80 and 443.
Skipping health checks or misconfiguring the health check path
The ALB cannot detect unhealthy servers and may send traffic to broken instances, causing errors for users.
Configure health checks with the correct path that returns a 200 status when the app is healthy.
Using private subnets without a public IP for the ALB
The ALB will not be reachable from the internet if it is internet-facing but placed in private subnets.
Place the ALB in public subnets with internet access for internet-facing load balancers.
Summary
Initialize Terraform to prepare AWS provider plugins.
Plan the infrastructure to see what resources will be created.
Apply the Terraform configuration to create the ALB, target group, and listener.
Verify the ALB creation using AWS CLI to check its status and details.

Practice

(1/5)
1. What is the primary purpose of an Application Load Balancer (ALB) in AWS?
easy
A. To create virtual private clouds (VPCs)
B. To distribute incoming web traffic across multiple targets for better availability
C. To monitor network traffic for security threats
D. To store large amounts of data securely

Solution

  1. Step 1: Understand ALB's role in traffic management

    ALB distributes incoming HTTP/HTTPS requests to multiple backend servers to balance load and improve availability.
  2. Step 2: Compare options with ALB's function

    Options A, B, and C describe other AWS services, not ALB's main function.
  3. Final Answer:

    To distribute incoming web traffic across multiple targets for better availability -> Option B
  4. Quick Check:

    ALB = traffic distribution [OK]
Hint: ALB balances web traffic to keep apps available [OK]
Common Mistakes:
  • Confusing ALB with storage services
  • Thinking ALB handles security monitoring
  • Mixing ALB with network setup services
2. Which of the following is the correct way to specify a listener protocol for an ALB in AWS?
easy
A. ListenerProtocol: HTTP
B. ListenerProtocol: FTP
C. ListenerProtocol: TCP
D. ListenerProtocol: SMTP

Solution

  1. Step 1: Identify supported ALB listener protocols

    ALB supports HTTP and HTTPS protocols for listeners, not TCP, FTP, or SMTP.
  2. Step 2: Match correct protocol syntax

    ListenerProtocol: HTTP uses HTTP, which is valid for ALB listeners.
  3. Final Answer:

    <code>ListenerProtocol: HTTP</code> -> Option A
  4. Quick Check:

    ALB listener protocol = HTTP or HTTPS [OK]
Hint: ALB listeners use HTTP/HTTPS, not TCP or FTP [OK]
Common Mistakes:
  • Using unsupported protocols like FTP or SMTP
  • Confusing ALB with Network Load Balancer protocols
  • Incorrect syntax for listener protocol
3. Given an ALB with two target groups: tg1 and tg2. The ALB uses a rule to route requests with path /api/* to tg1 and all other requests to tg2. What happens when a user requests /api/users?
medium
A. The request is routed to target group tg1
B. The request is routed to target group tg2
C. The request is rejected with an error
D. The request is routed to both tg1 and tg2 simultaneously

Solution

  1. Step 1: Analyze the ALB routing rule

    The rule states requests with path starting /api/ go to tg1.
  2. Step 2: Match the request path

    The request path /api/users matches the /api/* pattern, so it routes to tg1.
  3. Final Answer:

    The request is routed to target group <code>tg1</code> -> Option A
  4. Quick Check:

    Path /api/* routes to tg1 [OK]
Hint: Path rules route matching requests to correct target group [OK]
Common Mistakes:
  • Assuming default target group handles all requests
  • Thinking requests route to multiple target groups
  • Ignoring path-based routing rules
4. You configured an ALB with HTTPS listener but forgot to attach an SSL certificate. What issue will occur?
medium
A. The ALB will route requests without encryption
B. The ALB will automatically generate a certificate and accept requests
C. The ALB will downgrade HTTPS requests to HTTP
D. The ALB will reject all HTTPS requests with a TLS handshake failure

Solution

  1. Step 1: Understand HTTPS listener requirements

    HTTPS listeners require a valid SSL certificate to establish secure connections.
  2. Step 2: Consequence of missing certificate

    Without a certificate, TLS handshake fails, causing ALB to reject HTTPS requests.
  3. Final Answer:

    The ALB will reject all HTTPS requests with a TLS handshake failure -> Option D
  4. Quick Check:

    HTTPS needs SSL cert; missing cert = handshake failure [OK]
Hint: HTTPS listeners must have SSL certificates attached [OK]
Common Mistakes:
  • Assuming ALB auto-generates SSL certificates
  • Thinking ALB downgrades HTTPS to HTTP automatically
  • Believing ALB routes unencrypted traffic on HTTPS listener
5. You want to design a scalable web app using ALB that routes traffic based on user device type: mobile users to tg-mobile and desktop users to tg-desktop. Which ALB feature should you use to implement this?
hard
A. Use ALB path-based routing with /mobile and /desktop paths
B. Use ALB health checks to detect device type
C. Use ALB listener rules with HTTP header-based routing on the User-Agent header
D. Use ALB sticky sessions to route users based on device

Solution

  1. Step 1: Identify how to detect device type in requests

    User device type is typically indicated in the HTTP User-Agent header.
  2. Step 2: Choose ALB feature for routing based on headers

    ALB supports listener rules that route traffic based on HTTP headers like User-Agent.
  3. Step 3: Evaluate other options

    Health checks do not detect device type; path-based routing requires URL changes; sticky sessions maintain session but don't route by device.
  4. Final Answer:

    Use ALB listener rules with HTTP header-based routing on the User-Agent header -> Option C
  5. Quick Check:

    Header-based routing = device type routing [OK]
Hint: Use header-based routing on User-Agent for device detection [OK]
Common Mistakes:
  • Using health checks to detect device type
  • Relying on path-based routing without URL changes
  • Confusing sticky sessions with routing logic
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard