AWS ALB 應用程式負載平衡器設定

ALB 簡介

AWS Application Load Balancer (ALB) 是 AWS Elastic Load Balancing 服務中的一種負載平衡器,專門針對 HTTP 和 HTTPS 流量進行最佳化。ALB 運作於 OSI 模型的第七層(應用程式層),能夠根據請求內容進行智慧路由決策。

ALB 的主要特色

  • 內容導向路由:可根據 URL 路徑、主機標頭、HTTP 方法、查詢字串等進行路由
  • 原生支援容器化應用:與 Amazon ECS、EKS 無縫整合
  • WebSocket 支援:支援即時雙向通訊
  • HTTP/2 支援:提升效能和減少延遲
  • SSL/TLS 終止:在負載平衡器層處理加密,減輕後端伺服器負擔
  • 整合 AWS WAF:提供應用程式層級的安全防護

ALB 與其他負載平衡器的比較

特性ALBNLBCLB
OSI 層級第七層第四層第四/七層
協定HTTP/HTTPSTCP/UDP/TLSTCP/SSL/HTTP/HTTPS
延遲較高極低中等
固定 IP
WebSocket

建立步驟

步驟一:進入 EC2 控制台

  1. 登入 AWS Management Console
  2. 搜尋並進入 EC2 服務
  3. 在左側選單中選擇 負載平衡器 (Load Balancers)
  4. 點擊 建立負載平衡器 (Create Load Balancer)

步驟二:選擇負載平衡器類型

在負載平衡器類型選擇頁面中,選擇 Application Load Balancer,然後點擊 建立

步驟三:基本設定

1
2
3
負載平衡器名稱:my-application-alb
架構:面向網際網路 (Internet-facing)
IP 位址類型:IPv4

步驟四:網路設定

  1. 選擇您的 VPC
  2. 選擇至少兩個不同可用區的子網路(建議選擇公有子網路)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# Terraform 範例
resource "aws_lb" "main" {
  name               = "my-application-alb"
  internal           = false
  load_balancer_type = "application"
  security_groups    = [aws_security_group.alb_sg.id]
  subnets            = [aws_subnet.public_a.id, aws_subnet.public_b.id]

  enable_deletion_protection = true

  tags = {
    Environment = "production"
  }
}

步驟五:安全群組設定

建立或選擇安全群組,確保開放以下連接埠:

  • HTTP (80):允許來自 0.0.0.0/0
  • HTTPS (443):允許來自 0.0.0.0/0
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
resource "aws_security_group" "alb_sg" {
  name        = "alb-security-group"
  description = "Security group for ALB"
  vpc_id      = aws_vpc.main.id

  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"]
  }
}

目標群組設定

目標群組 (Target Group) 定義了 ALB 將流量轉發到哪些後端資源。

建立目標群組

  1. 在 EC2 控制台左側選單選擇 目標群組 (Target Groups)
  2. 點擊 建立目標群組 (Create target group)

目標群組設定選項

1
2
3
4
5
6
目標類型:執行個體 (Instances) / IP / Lambda 函數
目標群組名稱:my-app-target-group
協定:HTTP
連接埠:80
VPC:選擇您的 VPC
協定版本:HTTP1

目標類型說明

目標類型使用情境
執行個體 (Instance)EC2 執行個體
IPECS 任務、容器、私有 IP
Lambda無伺服器應用程式

Terraform 目標群組範例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
resource "aws_lb_target_group" "main" {
  name     = "my-app-target-group"
  port     = 80
  protocol = "HTTP"
  vpc_id   = aws_vpc.main.id

  target_type = "instance"

  stickiness {
    type            = "lb_cookie"
    cookie_duration = 86400
    enabled         = true
  }

  tags = {
    Name = "my-app-target-group"
  }
}

# 註冊目標
resource "aws_lb_target_group_attachment" "web_server" {
  target_group_arn = aws_lb_target_group.main.arn
  target_id        = aws_instance.web_server.id
  port             = 80
}

健康檢查

健康檢查用於監控目標群組中各個目標的健康狀態,確保流量只會轉發到健康的目標。

健康檢查設定參數

參數說明建議值
協定健康檢查使用的協定HTTP
路徑健康檢查的 URL 路徑/health 或 /api/health
連接埠健康檢查的連接埠traffic-port
健康閾值判定為健康所需的連續成功次數2
不健康閾值判定為不健康所需的連續失敗次數3
逾時健康檢查逾時時間5 秒
間隔健康檢查的間隔時間30 秒
成功代碼視為成功的 HTTP 狀態碼200-299

Terraform 健康檢查設定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
resource "aws_lb_target_group" "main" {
  name     = "my-app-target-group"
  port     = 80
  protocol = "HTTP"
  vpc_id   = aws_vpc.main.id

  health_check {
    enabled             = true
    healthy_threshold   = 2
    unhealthy_threshold = 3
    timeout             = 5
    interval            = 30
    path                = "/health"
    port                = "traffic-port"
    protocol            = "HTTP"
    matcher             = "200-299"
  }
}

健康檢查端點最佳實踐

建議在應用程式中實作專用的健康檢查端點:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# Flask 範例
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/health')
def health_check():
    # 檢查資料庫連線
    # 檢查外部依賴服務
    # 檢查記憶體使用量
    return jsonify({
        'status': 'healthy',
        'database': 'connected',
        'cache': 'connected'
    }), 200

監聽器規則

監聽器 (Listener) 檢查連接請求,並根據定義的規則將請求路由到適當的目標群組。

建立監聽器

  1. 在 ALB 詳細頁面選擇 監聽器 (Listeners) 標籤
  2. 點擊 新增監聽器 (Add listener)

HTTP 監聽器設定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
resource "aws_lb_listener" "http" {
  load_balancer_arn = aws_lb.main.arn
  port              = 80
  protocol          = "HTTP"

  default_action {
    type = "redirect"
    redirect {
      port        = "443"
      protocol    = "HTTPS"
      status_code = "HTTP_301"
    }
  }
}

HTTPS 監聽器設定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
resource "aws_lb_listener" "https" {
  load_balancer_arn = aws_lb.main.arn
  port              = 443
  protocol          = "HTTPS"
  ssl_policy        = "ELBSecurityPolicy-TLS13-1-2-2021-06"
  certificate_arn   = aws_acm_certificate.main.arn

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

進階路由規則

ALB 支援多種條件式路由:

基於路徑的路由

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
resource "aws_lb_listener_rule" "api" {
  listener_arn = aws_lb_listener.https.arn
  priority     = 100

  action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.api.arn
  }

  condition {
    path_pattern {
      values = ["/api/*"]
    }
  }
}

基於主機的路由

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
resource "aws_lb_listener_rule" "admin" {
  listener_arn = aws_lb_listener.https.arn
  priority     = 200

  action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.admin.arn
  }

  condition {
    host_header {
      values = ["admin.example.com"]
    }
  }
}

加權目標群組(藍綠部署/金絲雀發布)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
resource "aws_lb_listener_rule" "weighted" {
  listener_arn = aws_lb_listener.https.arn
  priority     = 300

  action {
    type = "forward"
    forward {
      target_group {
        arn    = aws_lb_target_group.blue.arn
        weight = 90
      }
      target_group {
        arn    = aws_lb_target_group.green.arn
        weight = 10
      }
    }
  }

  condition {
    path_pattern {
      values = ["/*"]
    }
  }
}

規則優先順序

  • 規則按優先順序(數字越小越優先)依序評估
  • 第一個匹配的規則會被執行
  • 預設規則的優先順序最低,作為最後的備案

總結

AWS ALB 提供了強大且靈活的應用程式層負載平衡功能。透過正確設定目標群組、健康檢查和監聽器規則,您可以建立高可用性、可擴展的應用程式架構。建議搭配 AWS Auto Scaling 使用,以實現完整的彈性擴展解決方案。

相關資源

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy