1. Cấu hình cơ bản (Load Balancing HTTP)
Mô hình:
Client → HAProxy → 2 Web Server
global
log /dev/log local0
maxconn 2000
defaults
mode http
timeout connect 5s
timeout client 50s
timeout server 50s
frontend http_front
bind *:80
default_backend web_servers
backend web_servers
balance roundrobin
server web1 192.168.1.10:80 check
server web2 192.168.1.11:80 check
Ý nghĩa:
-
frontend: nhận request từ client
-
backend: danh sách server xử lý
-
check: bật health check
2. Dùng Least Connection (chuẩn production)
Phù hợp web nhiều user online
balance leastconn
server web1 192.168.1.10:80 check
server web2 192.168.1.11:80 check
server web3 192.168.1.12:80 check
Server nào ít kết nối nhất sẽ được chọn
3. Cấu hình HTTPS + SSL Termination
HAProxy xử lý SSL
frontend https_front
bind *:443 ssl crt /etc/haproxy/ssl/domain.pem
default_backend web_servers
backend web_servers
balance roundrobin
server web1 192.168.1.10:80 check
server web2 192.168.1.11:80 check
Luồng:
Client HTTPS → HAProxy → HTTP backend
4. Redirect HTTP → HTTPS
bind *:80
redirect scheme https if !{ ssl_fc }
5. Sticky Session (giữ phiên login)
👉 Dùng cho web login, giỏ hàng
balance source
server web1 192.168.1.10:80 check
server web2 192.168.1.11:80 check
Cùng IP → luôn vào cùng server
6. Cấu hình theo Domain (Multi Website)
1 HAProxy chạy nhiều domain
frontend http_front
bind *:80
acl is_blog hdr(host) -i blog.domain.com
acl is_shop hdr(host) -i shop.domain.com
use_backend blog_servers if is_blog
use_backend shop_servers if is_shop
backend blog_servers
balance roundrobin
server blog1 192.168.1.10:80 check
backend shop_servers
balance roundrobin
server shop1 192.168.1.20:80 check
7. Cấu hình theo URL (Path-based Routing)
API và Web tách riêng
frontend http_front
bind *:80
acl is_api path_beg /api
use_backend api_servers if is_api
default_backend web_servers
backend api_servers
balance roundrobin
server api1 192.168.1.30:8000 check
backend web_servers
balance roundrobin
server web1 192.168.1.10:80 check
8. Health Check nâng cao
backend web_servers
option httpchk GET /
http-check expect status 200
server web1 192.168.1.10:80 check
server web2 192.168.1.11:80 check
Nếu không trả về 200 → bị loại
9. Backup Server (Failover)
balance roundrobin
server web1 192.168.1.10:80 check
server web2 192.168.1.11:80 check
server backup1 192.168.1.100:80 check backup
Chỉ dùng khi server chính chết
10. Rate Limit (chống spam / DDoS nhẹ)
frontend http_front
bind *:80
stick-table type ip size 1m expire 10s store http_req_rate(10s)
tcp-request connection track-sc0 src
tcp-request connection reject if { sc_http_req_rate(0) gt 50 }
default_backend web_servers
1 IP > 50 request / 10s → block
11. Logging chi tiết
global
log 127.0.0.1 local0
defaults
log global
option httplog
Gợi ý cấu hình thực tế (Production)
Thường dùng combo:
-
leastconn
-
SSL termination
-
health check
-
rate limit
-
backup server
Cấu trúc file chuẩn
defaults
frontend
backend
listen (optional)
Chúc các bạn thành công.