⚖️ HAProxy
高效能 TCP/HTTP 負載均衡器
HAProxy 是業界標準的負載均衡器,支援 Layer 4/7 負載均衡、健康檢查、會話保持,適合需要高可用與水平擴展的生產架構。
安裝
$ sudo apt update && sudo apt install -y haproxy
sudo systemctl enable --now haproxy$ haproxy -vHAProxy version 2.6.17
設定檔結構(/etc/haproxy/haproxy.cfg)
HAProxy 設定分為四個區塊:
| 區塊 | 說明 |
|---|---|
global | 全域程序設定(日誌、最大連線數、安全性) |
defaults | 預設值,套用到後續所有 frontend/backend |
frontend | 接受外部連線的監聽器,決定如何路由流量 |
backend | 實際服務的伺服器群組與負載均衡設定 |
基本 HTTP 負載均衡設定
global
log /dev/log local0
maxconn 50000
user haproxy
group haproxy
defaults
mode http
log global
option httplog
option forwardfor # 傳遞 X-Forwarded-For 標頭
option http-server-close
timeout connect 5s
timeout client 30s
timeout server 30s
frontend web_front
bind *:80
bind *:443 ssl crt /etc/ssl/certs/example.com.pem # 合併 cert+key 的 PEM
http-request redirect scheme https unless { ssl_fc } # HTTP → HTTPS
default_backend web_backend
backend web_backend
balance roundrobin # 輪詢(可改 leastconn、random)
option httpchk GET /health # 健康檢查路徑
server web1 192.168.1.11:8080 check
server web2 192.168.1.12:8080 check
server web3 192.168.1.13:8080 check backup # 備援節點$ sudo haproxy -c -f /etc/haproxy/haproxy.cfg # 驗證語法
sudo systemctl reload haproxy健康檢查設定
backend web_backend
option httpchk GET /health HTTP/1.1\r\nHost:\ example.com
http-check expect status 200
# 失敗 3 次才標為 DOWN,恢復 2 次才標為 UP
server web1 192.168.1.11:8080 check inter 5s rise 2 fall 3
server web2 192.168.1.12:8080 check inter 5s rise 2 fall 3啟用統計管理介面
frontend stats
bind *:8404
stats enable
stats uri /stats
stats refresh 10s
stats auth admin:安全密碼 # 基本認證
stats show-legends
stats show-node$ sudo ufw allow 8404/tcp
# 開啟瀏覽器訪問 http://伺服器IP:8404/stats常用操作
| 操作 | 指令 |
|---|---|
| 驗證設定語法 | sudo haproxy -c -f /etc/haproxy/haproxy.cfg |
| 重新載入(不中斷連線) | sudo systemctl reload haproxy |
| 查看連線統計 | echo "show info" | sudo socat stdio /run/haproxy/admin.sock |
| 即時查看日誌 | sudo tail -f /var/log/haproxy.log |