ELB là gì?
Elastic Load Balancing (ELB) là dịch vụ phân phối lưu lượng truy cập (traffic) tự động của AWS, giúp phân tán request đến nhiều target (EC2, container, IP, Lambda) trên một hoặc nhiều Availability Zone. ELB tự động scale theo lưu lượng, đảm bảo high availability và fault tolerance cho ứng dụng.
Tại sao cần Load Balancer?
- Phân tải: Chia đều request đến nhiều server, tránh quá tải một instance
- High Availability: Nếu một server chết, LB tự động chuyển traffic sang server khác
- Health Check: Liên tục kiểm tra sức khỏe backend, chỉ gửi traffic đến target healthy
- SSL Termination: Xử lý mã hóa/giải mã SSL tại LB, giảm CPU cho backend
- Single DNS endpoint: Client chỉ cần biết 1 DNS name, không cần biết IP từng server
- Enforce stickiness: Giữ session của user trên cùng một backend server
Các loại Load Balancer trên AWS
AWS cung cấp 4 loại ELB, mỗi loại phục vụ use case khác nhau:
| Tiêu chí | ALB | NLB | GWLB | CLB (Legacy) |
|---|---|---|---|---|
| Layer | Layer 7 | Layer 4 | Layer 3 | Layer 4/7 |
| Protocol | HTTP, HTTPS, gRPC | TCP, UDP, TLS | IP (GENEVE) | HTTP, HTTPS, TCP, SSL |
| Static IP | Không (dùng DNS) | Có (1 IP/AZ, Elastic IP) | Không | Không |
| Latency | ~400ms | ~100μs (ultra-low) | ~ms | ~ms |
| Target types | Instance, IP, Lambda | Instance, IP, ALB | Instance, IP | Instance |
| Path/Host routing | ✓ Có | Không | Không | Không |
| WebSocket | ✓ Có | ✓ Có | Không | Không |
| SNI (Multi-cert) | ✓ Có | ✓ Có | Không | Không |
| Use case chính | Web app, microservices, API | Gaming, IoT, real-time, TCP | Firewall, IDS/IPS, DPI | Legacy (không nên dùng mới) |
Kiến trúc tổng quan ELB
Application Load Balancer (ALB)
ALB hoạt động ở Layer 7 (HTTP/HTTPS), là lựa chọn tốt nhất cho web application, microservices và container-based architecture. ALB hiểu nội dung HTTP request và có thể routing dựa trên path, host, header, query string, source IP.
Đặc điểm chính của ALB
- Content-based routing: Route dựa trên URL path, hostname, HTTP header, query string, source IP
- Host-based routing:
api.example.com→ Target Group A,web.example.com→ Target Group B - Path-based routing:
/api/*→ Backend API,/images/*→ Image Service - HTTP/2 & gRPC: Hỗ trợ native HTTP/2 và gRPC protocol
- WebSocket: Hỗ trợ WebSocket connections
- Redirect & Fixed Response: Trả về redirect 301/302 hoặc fixed response trực tiếp tại ALB
- Authentication: Tích hợp Cognito hoặc OIDC provider để authenticate user tại ALB
- WAF Integration: Gắn AWS WAF để bảo vệ khỏi SQL injection, XSS, DDoS
Kiến trúc ALB
ALB gồm 3 thành phần chính: Listener → Rule → Target Group
Routing Conditions của ALB
| Condition | Mô tả | Ví dụ |
|---|---|---|
| Host header | Route theo domain name | api.example.com |
| Path pattern | Route theo URL path | /api/v1/* |
| HTTP header | Route theo custom header | X-Custom-Header: mobile |
| Query string | Route theo query parameter | ?platform=mobile |
| HTTP method | Route theo HTTP method | GET, POST, PUT |
| Source IP | Route theo IP nguồn | 10.0.0.0/8 |
X-Forwarded Headers
Vì ALB terminate connection từ client, backend sẽ thấy IP của ALB thay vì IP client. ALB thêm các header sau:
X-Forwarded-For— IP gốc của clientX-Forwarded-Proto— Protocol gốc (http/https)X-Forwarded-Port— Port gốc của request
Network Load Balancer (NLB)
NLB hoạt động ở Layer 4 (TCP/UDP/TLS), được thiết kế cho workload cần ultra-low latency (~100 microseconds) và khả năng xử lý hàng triệu request/giây. NLB cung cấp static IP cho mỗi AZ và hỗ trợ Elastic IP.
Đặc điểm chính của NLB
- Ultra-low latency: ~100 microseconds — nhanh nhất trong các loại ELB
- Static IP: Mỗi AZ có 1 static IP, có thể gán Elastic IP → whitelist firewall dễ dàng
- Millions of RPS: Xử lý hàng triệu request/giây mà không cần warm-up
- TCP/UDP/TLS: Hỗ trợ TCP, UDP, TLS (TCP với encryption)
- Preserve source IP: Backend thấy IP gốc của client (không cần X-Forwarded-For)
- TLS Termination: Có thể terminate TLS tại NLB hoặc pass-through đến backend
- Target: ALB: NLB có thể forward traffic đến ALB (NLB → ALB pattern)
- PrivateLink: NLB là thành phần bắt buộc để tạo VPC Endpoint Service (PrivateLink)
- Cần static IP hoặc Elastic IP
- Workload TCP/UDP (không phải HTTP)
- Cần ultra-low latency (gaming, trading)
- Hàng triệu concurrent connections
- Cần expose service qua PrivateLink
- Cần preserve source IP cho backend
- Cần routing theo URL path, host header
- Cần authentication tại LB (Cognito/OIDC)
- Cần gắn WAF (WAF chỉ hỗ trợ ALB/CloudFront)
- Cần redirect HTTP → HTTPS tại LB
- Cần fixed response tại LB
- Web app thuần HTTP/HTTPS
NLB + Elastic IP
Mỗi NLB có thể gán 1 Elastic IP cho mỗi AZ. Điều này rất hữu ích khi partner/client cần whitelist IP cố định trong firewall:
# Tạo NLB với Elastic IP cho mỗi AZ
aws elbv2 create-load-balancer \
--name my-nlb \
--type network \
--subnet-mappings \
SubnetId=subnet-aaa,AllocationId=eipalloc-111 \
SubnetId=subnet-bbb,AllocationId=eipalloc-222
# Kết quả: NLB có 2 static IP cố định
# AZ-a: 52.10.20.30 (Elastic IP)
# AZ-b: 52.10.20.31 (Elastic IP)
NLB → ALB Pattern
Khi cần kết hợp static IP (NLB) với content-based routing (ALB), bạn có thể chain NLB → ALB:
- NLB cung cấp static IP / Elastic IP cho client whitelist
- NLB forward traffic đến ALB (ALB là target của NLB)
- ALB thực hiện path/host routing đến các Target Group
TLS Termination trên NLB
NLB hỗ trợ TLS listener để terminate TLS tại load balancer:
- Sử dụng certificate từ ACM (AWS Certificate Manager)
- Hỗ trợ SNI (Server Name Indication) — nhiều certificate trên 1 listener
- Hoặc TLS pass-through — NLB forward encrypted traffic trực tiếp đến backend
Gateway Load Balancer (GWLB)
GWLB hoạt động ở Layer 3 (Network layer), kết hợp vai trò transparent network gateway và load balancer. GWLB được thiết kế để deploy, scale và quản lý các third-party virtual appliances như firewall, IDS/IPS, deep packet inspection.
Đặc điểm chính của GWLB
- Transparent gateway: Hoạt động như single entry/exit point cho tất cả traffic
- GENEVE protocol: Sử dụng GENEVE encapsulation (port 6081) để forward traffic đến appliances
- Layer 3: Xử lý tất cả IP packets — không giới hạn protocol
- Bump-in-the-wire: Traffic đi qua appliance rồi quay lại GWLB trước khi đến destination
- Cross-AZ: Phân phối traffic đến appliances trên nhiều AZ
- Gateway Load Balancer Endpoint (GWLBe): VPC endpoint để route traffic từ VPC đến GWLB
Luồng traffic qua GWLB
- Traffic từ Internet đi vào Internet Gateway
- Route table chuyển traffic đến GWLBe (Gateway LB Endpoint) trong Application VPC
- GWLBe forward traffic đến GWLB trong Security VPC
- GWLB phân phối traffic đến các security appliances (firewall, IDS/IPS)
- Appliance inspect/filter traffic rồi gửi lại GWLB
- GWLB trả traffic về GWLBe → đến Application Server
Target Groups
Target Group là nhóm các target (đích) mà Load Balancer sẽ forward traffic đến. Mỗi target group có cấu hình health check riêng và thuộc về một hoặc nhiều listener rule.
Các loại Target
| Target Type | Mô tả | Hỗ trợ bởi | Use case |
|---|---|---|---|
| Instance | EC2 instance ID (traffic gửi đến primary private IP) | ALB NLB GWLB | EC2 truyền thống, Auto Scaling Group |
| IP | Private IP address (có thể ngoài VPC) | ALB NLB GWLB | On-premises server, peered VPC, container với awsvpc |
| Lambda | Lambda function ARN | ALB | Serverless backend, API endpoint |
| ALB | Application Load Balancer ARN | NLB | NLB → ALB pattern (static IP + L7 routing) |
Health Check Configuration
Health check xác định target nào healthy để nhận traffic. Cấu hình bao gồm:
| Tham số | Mô tả | Mặc định |
|---|---|---|
| Protocol | HTTP, HTTPS, TCP, gRPC | HTTP (ALB), TCP (NLB) |
| Path | URL path cho HTTP/HTTPS health check | / |
| Port | Port kiểm tra (traffic port hoặc override) | traffic-port |
| Healthy threshold | Số lần check thành công liên tiếp → healthy | 5 (ALB), 3 (NLB) |
| Unhealthy threshold | Số lần check thất bại liên tiếp → unhealthy | 2 |
| Interval | Khoảng thời gian giữa các lần check | 30s (ALB), 30s (NLB) |
| Timeout | Thời gian chờ response | 5s (ALB), 10s (NLB) |
| Success codes | HTTP status code coi là healthy | 200 |
Deregistration Delay (Connection Draining)
Khi target bị remove khỏi target group (scale-in, unhealthy), ELB sẽ chờ một khoảng thời gian để hoàn thành các request đang xử lý trước khi ngắt kết nối:
- Mặc định: 300 giây (5 phút)
- Range: 0 – 3600 giây
- Đặt 0: Ngắt kết nối ngay lập tức (không khuyến nghị)
- Khuyến nghị: Đặt bằng thời gian xử lý request dài nhất của ứng dụng
# Tạo target group cho ALB aws elbv2 create-target-group \ --name my-api-targets \ --protocol HTTP \ --port 8080 \ --vpc-id vpc-0123456789abcdef0 \ --target-type instance \ --health-check-protocol HTTP \ --health-check-path /health \ --health-check-interval-seconds 15 \ --healthy-threshold-count 3 \ --unhealthy-threshold-count 2 \ --matcher HttpCode=200 # Đăng ký target aws elbv2 register-targets \ --target-group-arn arn:aws:elasticloadbalancing:... \ --targets Id=i-0abcd1234efgh5678 Id=i-0ijkl9012mnop3456 # Cấu hình deregistration delay aws elbv2 modify-target-group-attributes \ --target-group-arn arn:aws:elasticloadbalancing:... \ --attributes Key=deregistration_delay.timeout_seconds,Value=120
Listeners & Rules
Listener là process lắng nghe connection request trên một protocol và port cụ thể. Mỗi listener có một hoặc nhiều rules để xác định cách route traffic đến target group.
Listener Configuration
| LB Type | Protocols hỗ trợ | Port range |
|---|---|---|
| ALB | HTTP (80), HTTPS (443) | 1 – 65535 |
| NLB | TCP, UDP, TLS, TCP_UDP | 1 – 65535 |
| GWLB | GENEVE (6081) | 6081 (cố định) |
Rule Components (ALB)
Mỗi rule gồm: Priority + Conditions + Actions
Conditions (Điều kiện)
host-header— Match domain name:*.example.compath-pattern— Match URL path:/api/*http-header— Match custom header:X-Device: mobilequery-string— Match query param:version=v2http-request-method— Match HTTP method:POSTsource-ip— Match source IP CIDR:10.0.0.0/8
Actions (Hành động)
| Action | Mô tả | Ví dụ |
|---|---|---|
| forward | Forward đến 1 hoặc nhiều target group (weighted) | 80% → TG-v2, 20% → TG-v1 |
| redirect | Redirect HTTP → HTTPS hoặc URL khác (301/302) | HTTP :80 → HTTPS :443 |
| fixed-response | Trả về response cố định (status code + body) | 503 "Service Maintenance" |
| authenticate-cognito | Authenticate qua Amazon Cognito User Pool | Login trước khi truy cập app |
| authenticate-oidc | Authenticate qua OIDC provider (Google, Okta...) | SSO với corporate IdP |
Priority (Độ ưu tiên)
Rules được đánh giá theo thứ tự priority (số nhỏ = ưu tiên cao). Rule đầu tiên match sẽ được thực thi. Mỗi listener có 1 default rule (priority thấp nhất) — xử lý traffic không match rule nào.
# Rule 1 (Priority 10): /api/* → API Target Group
aws elbv2 create-rule \
--listener-arn arn:aws:elasticloadbalancing:...:listener/app/my-alb/... \
--priority 10 \
--conditions Field=path-pattern,Values='/api/*' \
--actions Type=forward,TargetGroupArn=arn:aws:...tg-api
# Rule 2 (Priority 20): Redirect HTTP → HTTPS
aws elbv2 create-rule \
--listener-arn arn:aws:elasticloadbalancing:...:listener/app/my-alb/... \
--priority 20 \
--conditions Field=path-pattern,Values='/*' \
--actions Type=redirect,RedirectConfig='{Protocol=HTTPS,Port=443,StatusCode=HTTP_301}'
# Rule 3: Fixed response cho maintenance
aws elbv2 create-rule \
--listener-arn arn:aws:elasticloadbalancing:...:listener/app/my-alb/... \
--priority 5 \
--conditions Field=path-pattern,Values='/maintenance' \
--actions Type=fixed-response,FixedResponseConfig='{StatusCode=503,ContentType=text/html,MessageBody="<h1>Bảo trì hệ thống</h1>"}'
# Weighted Target Group (Blue/Green, Canary)
aws elbv2 create-rule \
--listener-arn arn:aws:elasticloadbalancing:...:listener/app/my-alb/... \
--priority 15 \
--conditions Field=path-pattern,Values='/app/*' \
--actions Type=forward,ForwardConfig='{
TargetGroups=[
{TargetGroupArn=arn:aws:...tg-blue,Weight=90},
{TargetGroupArn=arn:aws:...tg-green,Weight=10}
]
}'
SSL/TLS Termination
SSL/TLS Termination (hay SSL Offloading) là quá trình giải mã traffic HTTPS tại Load Balancer, giúp backend không phải xử lý mã hóa/giải mã — giảm CPU overhead đáng kể.
Cách hoạt động
- Client gửi HTTPS request đến Load Balancer
- LB thực hiện TLS handshake, giải mã traffic
- LB forward HTTP (plaintext) hoặc HTTPS (re-encrypt) đến backend
- Backend xử lý request và trả response
ACM Integration
AWS Certificate Manager (ACM) cung cấp SSL/TLS certificate miễn phí cho ELB:
- Miễn phí: ACM public certificate hoàn toàn miễn phí
- Auto-renew: ACM tự động gia hạn certificate trước khi hết hạn
- Wildcard: Hỗ trợ wildcard certificate (
*.example.com) - Multi-domain: Hỗ trợ SAN (Subject Alternative Name) cho nhiều domain
SNI — Server Name Indication
SNI cho phép host nhiều SSL certificate trên cùng một listener (cùng IP:port). Client gửi hostname trong TLS handshake, LB chọn certificate phù hợp.
| LB Type | SNI Support | Số certificate tối đa |
|---|---|---|
| ALB | ✓ Có | 25 (default, có thể tăng) |
| NLB | ✓ Có | 25 (default, có thể tăng) |
| CLB | ✗ Không | 1 certificate / CLB |
Security Policies
Security Policy xác định TLS protocol versions và cipher suites mà LB sử dụng:
- ELBSecurityPolicy-TLS13-1-2-2021-06: TLS 1.3 + TLS 1.2 (khuyến nghị)
- ELBSecurityPolicy-2016-08: TLS 1.0+ (legacy, không khuyến nghị)
- ELBSecurityPolicy-TLS-1-2-2017-01: Chỉ TLS 1.2+ (bảo mật cao)
- ELBSecurityPolicy-FS-1-2-Res-2020-10: Forward Secrecy + TLS 1.2 (restrictive)
Backend Encryption (End-to-End)
Nếu cần mã hóa end-to-end, cấu hình LB forward HTTPS đến backend:
- ALB: Target group protocol = HTTPS → ALB re-encrypt traffic đến backend
- NLB: Sử dụng TCP listener (TLS pass-through) → backend tự xử lý TLS
# Tạo HTTPS listener trên ALB
aws elbv2 create-listener \
--load-balancer-arn arn:aws:elasticloadbalancing:...:loadbalancer/app/my-alb/... \
--protocol HTTPS \
--port 443 \
--ssl-policy ELBSecurityPolicy-TLS13-1-2-2021-06 \
--certificates CertificateArn=arn:aws:acm:ap-southeast-1:123456789012:certificate/abc-123 \
--default-actions Type=forward,TargetGroupArn=arn:aws:...tg-web
# Thêm certificate cho SNI
aws elbv2 add-listener-certificates \
--listener-arn arn:aws:elasticloadbalancing:...:listener/app/my-alb/... \
--certificates CertificateArn=arn:aws:acm:...:certificate/def-456
# Redirect HTTP → HTTPS
aws elbv2 create-listener \
--load-balancer-arn arn:aws:elasticloadbalancing:...:loadbalancer/app/my-alb/... \
--protocol HTTP \
--port 80 \
--default-actions Type=redirect,RedirectConfig='{Protocol=HTTPS,Port=443,StatusCode=HTTP_301}'
Sticky Sessions (Session Affinity)
Sticky Sessions đảm bảo tất cả request từ cùng một client được gửi đến cùng một target trong target group. Điều này cần thiết khi ứng dụng lưu session state trên server (không phải stateless).
Hai loại Sticky Sessions
- Cookie do ELB tạo
- Cookie name:
AWSALB(ALB),AWSELB(CLB) - Cấu hình thời gian sống (1s – 7 ngày)
- Hết thời gian → LB có thể route đến target khác
- Phù hợp khi không cần kiểm soát cookie
- Cookie do ứng dụng tạo
- Custom cookie name (do bạn đặt)
- Không được dùng:
AWSALB,AWSALBAPP,AWSALBTG - LB tạo thêm cookie
AWSALBAPPđể track - Phù hợp khi app cần kiểm soát session
| Tiêu chí | Duration-based | Application-based |
|---|---|---|
| Cookie tạo bởi | ELB | Application + ELB |
| Cookie name | AWSALB | Custom + AWSALBAPP |
| Expiration | Cấu hình duration | Do application quyết định |
| Hỗ trợ | ALB, CLB | ALB |
| Use case | Session đơn giản | App cần custom session logic |
- Có thể gây imbalanced load — một số target nhận nhiều traffic hơn
- Nếu target chết, session bị mất (trừ khi dùng external session store)
- Best practice: Dùng external session store (ElastiCache Redis, DynamoDB) thay vì sticky sessions
# Duration-based stickiness (3600 giây = 1 giờ)
aws elbv2 modify-target-group-attributes \
--target-group-arn arn:aws:elasticloadbalancing:... \
--attributes \
Key=stickiness.enabled,Value=true \
Key=stickiness.type,Value=lb_cookie \
Key=stickiness.lb_cookie.duration_seconds,Value=3600
# Application-based stickiness
aws elbv2 modify-target-group-attributes \
--target-group-arn arn:aws:elasticloadbalancing:... \
--attributes \
Key=stickiness.enabled,Value=true \
Key=stickiness.type,Value=app_cookie \
Key=stickiness.app_cookie.cookie_name,Value=MY_SESSION_ID \
Key=stickiness.app_cookie.duration_seconds,Value=86400
Cross-Zone Load Balancing
Cross-Zone Load Balancing cho phép LB phân phối traffic đều đến tất cả registered targets trên tất cả AZ, thay vì chỉ phân phối đều giữa các AZ.
Có Cross-Zone vs Không Cross-Zone
Mặc định & Chi phí
| LB Type | Cross-Zone mặc định | Phí data transfer cross-AZ |
|---|---|---|
| ALB | Bật (luôn bật, không tắt được ở LB level) | Miễn phí |
| NLB | Tắt (mặc định) | Có phí nếu bật |
| GWLB | Tắt (mặc định) | Có phí nếu bật |
| CLB | Tắt (mặc định) | Miễn phí nếu bật |
Connection Draining / Deregistration Delay
Connection Draining (CLB) hay Deregistration Delay (ALB/NLB) là cơ chế cho phép LB hoàn thành các request đang xử lý (in-flight requests) trước khi ngắt kết nối với target bị deregister hoặc unhealthy.
Cách hoạt động
- Target bị đánh dấu draining (do scale-in, unhealthy, manual deregister)
- LB ngừng gửi request mới đến target đó
- LB chờ các in-flight request hoàn thành trong thời gian deregistration delay
- Sau khi hết thời gian hoặc tất cả request hoàn thành → LB ngắt kết nối
Cấu hình
| Tham số | Giá trị |
|---|---|
| Mặc định | 300 giây (5 phút) |
| Range | 0 – 3600 giây (0 = tắt, ngắt ngay) |
| Khuyến nghị | Bằng thời gian xử lý request dài nhất |
- API nhanh (< 5s): đặt 30-60 giây
- Upload file lớn: đặt 300-600 giây
- Long-polling/WebSocket: đặt 3600 giây
- Batch processing: đặt theo thời gian batch
- Đặt 0: Request bị ngắt đột ngột → lỗi 502
- Đặt quá cao: Scale-in chậm, tốn tiền EC2
- Không cấu hình: Mặc định 300s có thể quá dài
- Quên cấu hình khi dùng Auto Scaling
# Đặt deregistration delay = 120 giây aws elbv2 modify-target-group-attributes \ --target-group-arn arn:aws:elasticloadbalancing:... \ --attributes Key=deregistration_delay.timeout_seconds,Value=120 # Kiểm tra giá trị hiện tại aws elbv2 describe-target-group-attributes \ --target-group-arn arn:aws:elasticloadbalancing:...
ELB Access Logs & Monitoring
ELB cung cấp nhiều công cụ giám sát: CloudWatch Metrics cho real-time monitoring, Access Logs cho phân tích chi tiết, và Request Tracing cho debugging.
CloudWatch Metrics quan trọng
| Metric | Mô tả | Áp dụng | Alarm khi |
|---|---|---|---|
| RequestCount | Tổng số request đã xử lý | ALB | Spike bất thường |
| ActiveConnectionCount | Số connection đang active | ALB, NLB | Vượt capacity |
| HealthyHostCount | Số target healthy trong TG | ALB, NLB | < số target mong muốn |
| UnHealthyHostCount | Số target unhealthy | ALB, NLB | > 0 |
| TargetResponseTime | Thời gian backend xử lý request | ALB | > SLA threshold |
| HTTPCode_ELB_5XX_Count | Số lỗi 5xx từ ELB | ALB | > 0 (liên tục) |
| HTTPCode_Target_5XX_Count | Số lỗi 5xx từ backend | ALB | > threshold |
| SurgeQueueLength | Số request đang chờ trong queue | CLB | > 0 (liên tục) |
| SpilloverCount | Số request bị reject do queue đầy | CLB | > 0 |
| ConsumedLCUs | Số Load Balancer Capacity Units tiêu thụ | ALB, NLB | Theo dõi chi phí |
Access Logs
ELB Access Logs ghi lại chi tiết mỗi request và được lưu vào S3 bucket:
- Thông tin ghi lại: Timestamp, client IP:port, target IP:port, request processing time, target processing time, response processing time, ELB status code, target status code, bytes received/sent, request URL, user agent, SSL cipher, SSL protocol
- Tần suất: Mỗi 5 phút (hoặc 60 phút cho NLB)
- Format: Gzip compressed log files trong S3
- Chi phí: Không tính phí cho access logs, chỉ trả phí S3 storage
127311923021 cho us-east-1). Nếu thiếu policy này, access logs sẽ không hoạt động.
# Bật access logs
aws elbv2 modify-load-balancer-attributes \
--load-balancer-arn arn:aws:elasticloadbalancing:... \
--attributes \
Key=access_logs.s3.enabled,Value=true \
Key=access_logs.s3.bucket,Value=my-elb-logs-bucket \
Key=access_logs.s3.prefix,Value=alb-logs
# S3 Bucket Policy (cần thiết)
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::127311923021:root"
},
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::my-elb-logs-bucket/alb-logs/AWSLogs/123456789012/*"
}]
}
Request Tracing (ALB)
ALB thêm header X-Amzn-Trace-Id vào mỗi request, giúp trace request từ client → ALB → backend → response. Kết hợp với AWS X-Ray để distributed tracing.
Connection Logs (ALB)
Từ 2023, ALB hỗ trợ Connection Logs — ghi lại thông tin TLS connection (cipher, protocol version, client certificate) vào S3. Hữu ích cho security audit và compliance.
Các lỗi thường gặp & Best Practices
HTTP Error Codes từ ELB
| Error | Nguyên nhân | Cách xử lý |
|---|---|---|
| 400 Bad Request | Request header malformed, quá lớn | Kiểm tra client request, giảm header size |
| 403 Forbidden | WAF block request | Kiểm tra WAF rules, whitelist IP nếu cần |
| 460 Client Closed | Client đóng connection trước khi LB respond | Kiểm tra client timeout, network issues |
| 502 Bad Gateway | Target trả response không hợp lệ, target đóng connection, target không phản hồi | Kiểm tra backend health, security group, application logs |
| 503 Service Unavailable | Không có target healthy nào trong target group | Kiểm tra health check, đảm bảo có target healthy |
| 504 Gateway Timeout | Target không respond trong thời gian idle timeout (mặc định 60s) | Tăng idle timeout, tối ưu backend, kiểm tra database |
| 561 Unauthorized | Lỗi authentication (Cognito/OIDC) tại ALB | Kiểm tra IdP configuration, token expiry |
Troubleshooting 502 Bad Gateway
Lỗi 502 là lỗi phổ biến nhất. Checklist xử lý:
- Security Group: SG của target có cho phép traffic từ LB không?
- Health Check: Target có healthy không? Kiểm tra health check path và port
- Application: App có đang chạy và listen đúng port không?
- Keep-alive: Backend keep-alive timeout phải > ALB idle timeout (60s)
- Response format: Backend có trả HTTP response hợp lệ không?
- Target deregistered: Target có bị deregister trong quá trình xử lý request?
keepalive_timeout 65s) lớn hơn ALB idle timeout (mặc định 60s).
Best Practices
🏗️ Kiến trúc
- Luôn deploy LB trên ít nhất 2 AZ để đảm bảo HA
- Sử dụng ALB cho HTTP/HTTPS workload, NLB cho TCP/UDP
- Không dùng CLB cho project mới — migrate sang ALB/NLB
- Dùng internal LB cho communication giữa các tier (web → app → db)
- Kết hợp Auto Scaling Group với target group để tự động scale
🔒 Bảo mật
- Luôn redirect HTTP → HTTPS tại ALB
- Sử dụng ACM certificate (miễn phí, auto-renew)
- Chọn security policy TLS 1.2+ (tối thiểu)
- Gắn AWS WAF vào ALB để chống SQL injection, XSS
- Cấu hình Security Group chặt chẽ: LB chỉ nhận traffic từ internet, backend chỉ nhận từ LB
- Bật deletion protection cho production LB
📊 Monitoring
- Bật access logs và lưu vào S3 cho audit
- Tạo CloudWatch Alarms cho: UnHealthyHostCount > 0, HTTPCode_ELB_5XX > threshold, TargetResponseTime > SLA
- Sử dụng CloudWatch Dashboard để visualize metrics
- Kết hợp X-Ray cho distributed tracing
⚡ Performance
- Bật cross-zone load balancing cho NLB nếu target không đều giữa các AZ
- Cấu hình deregistration delay phù hợp với ứng dụng
- Sử dụng connection pooling ở backend
- Tăng idle timeout cho long-running request (WebSocket, file upload)
- Pre-warm ALB bằng cách liên hệ AWS Support nếu expect traffic spike lớn
ALB → EC2 SG: Allow inbound app port from ALB Security Group ID
Cách này đảm bảo EC2 chỉ nhận traffic từ ALB, không trực tiếp từ internet.
AWS CLI Cheat Sheet
Tổng hợp các lệnh AWS CLI thường dùng nhất cho Elastic Load Balancing. Tất cả lệnh sử dụng aws elbv2 (cho ALB, NLB, GWLB).
Quản lý Load Balancer
# ── Tạo ALB ──
aws elbv2 create-load-balancer \
--name my-alb \
--type application \
--subnets subnet-aaa subnet-bbb \
--security-groups sg-12345678 \
--scheme internet-facing \
--ip-address-type ipv4
# ── Tạo NLB ──
aws elbv2 create-load-balancer \
--name my-nlb \
--type network \
--subnets subnet-aaa subnet-bbb
# ── Tạo NLB với Elastic IP ──
aws elbv2 create-load-balancer \
--name my-nlb-eip \
--type network \
--subnet-mappings \
SubnetId=subnet-aaa,AllocationId=eipalloc-111 \
SubnetId=subnet-bbb,AllocationId=eipalloc-222
# ── Tạo Internal LB ──
aws elbv2 create-load-balancer \
--name my-internal-alb \
--type application \
--scheme internal \
--subnets subnet-private-a subnet-private-b \
--security-groups sg-internal
# ── Liệt kê tất cả LB ──
aws elbv2 describe-load-balancers
# ── Xem chi tiết 1 LB ──
aws elbv2 describe-load-balancers \
--names my-alb
# ── Bật deletion protection ──
aws elbv2 modify-load-balancer-attributes \
--load-balancer-arn arn:aws:elasticloadbalancing:... \
--attributes Key=deletion_protection.enabled,Value=true
# ── Xóa LB ──
aws elbv2 delete-load-balancer \
--load-balancer-arn arn:aws:elasticloadbalancing:...
Target Groups
# ── Tạo Target Group ── aws elbv2 create-target-group \ --name my-tg \ --protocol HTTP \ --port 80 \ --vpc-id vpc-123 \ --target-type instance \ --health-check-path /health \ --health-check-interval-seconds 15 \ --healthy-threshold-count 3 \ --unhealthy-threshold-count 2 # ── Tạo TG cho Lambda ── aws elbv2 create-target-group \ --name my-lambda-tg \ --target-type lambda # ── Tạo TG cho IP targets ── aws elbv2 create-target-group \ --name my-ip-tg \ --protocol HTTP \ --port 8080 \ --vpc-id vpc-123 \ --target-type ip # ── Đăng ký targets ── aws elbv2 register-targets \ --target-group-arn arn:aws:elasticloadbalancing:... \ --targets Id=i-111 Id=i-222 # ── Đăng ký IP targets ── aws elbv2 register-targets \ --target-group-arn arn:aws:elasticloadbalancing:... \ --targets Id=10.0.1.50,Port=8080 Id=10.0.2.60,Port=8080 # ── Hủy đăng ký target ── aws elbv2 deregister-targets \ --target-group-arn arn:aws:elasticloadbalancing:... \ --targets Id=i-111 # ── Kiểm tra health status ── aws elbv2 describe-target-health \ --target-group-arn arn:aws:elasticloadbalancing:... # ── Liệt kê tất cả TG ── aws elbv2 describe-target-groups
Listeners & Rules
# ── Tạo HTTP Listener ──
aws elbv2 create-listener \
--load-balancer-arn arn:aws:elasticloadbalancing:... \
--protocol HTTP \
--port 80 \
--default-actions Type=forward,TargetGroupArn=arn:aws:...
# ── Tạo HTTPS Listener ──
aws elbv2 create-listener \
--load-balancer-arn arn:aws:elasticloadbalancing:... \
--protocol HTTPS \
--port 443 \
--ssl-policy ELBSecurityPolicy-TLS13-1-2-2021-06 \
--certificates CertificateArn=arn:aws:acm:...:certificate/abc \
--default-actions Type=forward,TargetGroupArn=arn:aws:...
# ── HTTP → HTTPS Redirect Listener ──
aws elbv2 create-listener \
--load-balancer-arn arn:aws:elasticloadbalancing:... \
--protocol HTTP \
--port 80 \
--default-actions \
Type=redirect,RedirectConfig='{Protocol=HTTPS,Port=443,StatusCode=HTTP_301}'
# ── Tạo Rule với path routing ──
aws elbv2 create-rule \
--listener-arn arn:aws:elasticloadbalancing:...:listener/... \
--priority 10 \
--conditions Field=path-pattern,Values='/api/*' \
--actions Type=forward,TargetGroupArn=arn:aws:...tg-api
# ── Tạo Rule với host routing ──
aws elbv2 create-rule \
--listener-arn arn:aws:elasticloadbalancing:...:listener/... \
--priority 20 \
--conditions Field=host-header,Values='api.example.com' \
--actions Type=forward,TargetGroupArn=arn:aws:...tg-api
# ── Liệt kê rules ──
aws elbv2 describe-rules \
--listener-arn arn:aws:elasticloadbalancing:...:listener/...
# ── Thêm certificate (SNI) ──
aws elbv2 add-listener-certificates \
--listener-arn arn:aws:elasticloadbalancing:...:listener/... \
--certificates CertificateArn=arn:aws:acm:...:certificate/def
Monitoring & Attributes
# ── Bật Access Logs ──
aws elbv2 modify-load-balancer-attributes \
--load-balancer-arn arn:aws:elasticloadbalancing:... \
--attributes \
Key=access_logs.s3.enabled,Value=true \
Key=access_logs.s3.bucket,Value=my-logs-bucket \
Key=access_logs.s3.prefix,Value=elb
# ── Cấu hình Idle Timeout ──
aws elbv2 modify-load-balancer-attributes \
--load-balancer-arn arn:aws:elasticloadbalancing:... \
--attributes Key=idle_timeout.timeout_seconds,Value=120
# ── Bật Sticky Sessions ──
aws elbv2 modify-target-group-attributes \
--target-group-arn arn:aws:elasticloadbalancing:... \
--attributes \
Key=stickiness.enabled,Value=true \
Key=stickiness.type,Value=lb_cookie \
Key=stickiness.lb_cookie.duration_seconds,Value=3600
# ── Cấu hình Deregistration Delay ──
aws elbv2 modify-target-group-attributes \
--target-group-arn arn:aws:elasticloadbalancing:... \
--attributes Key=deregistration_delay.timeout_seconds,Value=120
# ── Xem LB attributes ──
aws elbv2 describe-load-balancer-attributes \
--load-balancer-arn arn:aws:elasticloadbalancing:...
# ── Xem TG attributes ──
aws elbv2 describe-target-group-attributes \
--target-group-arn arn:aws:elasticloadbalancing:...
# ── CloudWatch: Lấy UnHealthyHostCount ──
aws cloudwatch get-metric-statistics \
--namespace AWS/ApplicationELB \
--metric-name UnHealthyHostCount \
--dimensions \
Name=TargetGroup,Value=targetgroup/my-tg/abc123 \
Name=LoadBalancer,Value=app/my-alb/def456 \
--start-time 2026-01-01T00:00:00Z \
--end-time 2026-01-01T01:00:00Z \
--period 300 \
--statistics Maximum
# ── Tạo CloudWatch Alarm ──
aws cloudwatch put-metric-alarm \
--alarm-name elb-unhealthy-hosts \
--namespace AWS/ApplicationELB \
--metric-name UnHealthyHostCount \
--dimensions \
Name=TargetGroup,Value=targetgroup/my-tg/abc123 \
Name=LoadBalancer,Value=app/my-alb/def456 \
--statistic Maximum \
--period 60 \
--evaluation-periods 2 \
--threshold 1 \
--comparison-operator GreaterThanOrEqualToThreshold \
--alarm-actions arn:aws:sns:...:my-alerts
- Dùng
--queryđể filter output:--query 'LoadBalancers[].DNSName' - Dùng
--output tableđể hiển thị dạng bảng dễ đọc - Dùng
jqđể parse JSON:aws elbv2 describe-load-balancers | jq '.LoadBalancers[].DNSName' - Lệnh CLB cũ dùng
aws elb(không có "v2")