HAProxy 是專注於 TCP/HTTP (Layer 4/7) 高可用負載均衡的專用代理軟體,以極高併發處理能力、豐富健康檢查機制、原生 Session 粘滯、SSL 卸載、ACL 內容路由等功能,廣泛用於高流量 Web 架構前端。本文涵蓋核心特性解析、安裝部署、核心配置範本、效能調優參數、監控與故障排查全生命週期管理。
| 維度 | HAProxy | Nginx | Apache httpd |
|---|---|---|---|
| 核心職責 | 專職 L4/L7 負載均衡代理 | Web Server + 反向代理 | Web Server + 反向代理 |
| 併發極限 (官方) | 10 Gbps / 數萬連線 | ~5 萬併發 (受限於事件模型) | ~1 萬併發 (prefork/worker) |
| Session 粘滯 | 原生 cookie/prefix/stick-table | 需 ngx_http_upstream_consistent_hash 或商業版 | 需 mod_proxy_balancer + stickysession |
| 健康檢查 | TCP/HTTP/MySQL/Redis/PgSQL/自定義 | HTTP/TCP 基礎 | HTTP/TCP 基礎 |
| 運行模式 | 單進程事件驅動 (多執行緒 1.6+) | Master + Worker 多進程 | 多進程/多執行緒 |
| 配置熱重載 | 無縫 (SO_REUSEPORT) | 平滑但需 Worker 回收 | Graceful restart 較慢 |
結論:純負載均衡場景首選 HAProxy;需同時提供靜態檔案服務、動態應用容器時,可採「Nginx (前端靜態/SSL 終結) → HAProxy (後端均衡)」混合架構。
# Rocky/RHEL/CentOS Stream
dnf install -y haproxy
# Ubuntu/Debian
apt update && apt install -y haproxy
# 啟用並啟動
systemctl enable --now haproxy
# 驗證版本
haproxy -v
/etc/haproxy/haproxy.cfg
global
log 127.0.0.1 local0 info
chroot /var/lib/haproxy
pidfile /var/run/haproxy.pid
maxconn 50000
user haproxy
group haproxy
daemon
stats socket /var/lib/haproxy/stats level admin expose-fd listeners
ssl-default-bind-ciphers PROFILE=SYSTEM
ssl-default-server-ciphers PROFILE=SYSTEM
tune.ssl.default-dh-param 2048
defaults
mode http
log global
option httplog
option dontlognull
option http-server-close
option forwardfor except 127.0.0.0/8
option redispatch
retries 3
timeout connect 5s
timeout client 30s
timeout server 30s
timeout http-request 10s
timeout http-keep-alive 5s
timeout check 5s
maxconn 30000
errorfile 400 /etc/haproxy/errors/400.http
errorfile 403 /etc/haproxy/errors/403.http
errorfile 408 /etc/haproxy/errors/408.http
errorfile 500 /etc/haproxy/errors/500.http
errorfile 502 /etc/haproxy/errors/502.http
errorfile 503 /etc/haproxy/errors/503.http
errorfile 504 /etc/haproxy/errors/504.http
# 統計頁面 (建議僅內網存取)
listen stats
bind *:8404
mode http
stats enable
stats uri /stats
stats refresh 10s
stats auth admin:StrongPasswordHere
stats admin if TRUE
# HTTP 前端 → 後端 Web 叢集
frontend http_front
bind *:80
bind *:443 ssl crt /etc/haproxy/certs/ alpn h2,http/1.1
http-request redirect scheme https code 301 unless { ssl_fc }
acl is_api path_beg /api/
acl is_static path_beg /static/
use_backend api_servers if is_api
use_backend static_servers if is_static
default_backend web_servers
backend web_servers
balance roundrobin
option httpchk GET /healthz
http-check expect status 200
cookie SERVERID insert indirect nocache
server web1 10.0.1.11:80 check inter 2s rise 2 fall 3 cookie web1
server web2 10.0.1.12:80 check inter 2s rise 2 fall 3 cookie web2
server web3 10.0.1.13:80 check inter 2s rise 2 fall 3 cookie web3
backend api_servers
balance leastconn
option httpchk GET /api/health
server api1 10.0.2.11:8080 check inter 3s rise 2 fall 3
server api2 10.0.2.12:8080 check inter 3s rise 2 fall 3
backend static_servers
balance source
server cdn1 10.0.3.11:80 check
server cdn2 10.0.3.12:80 check
| 參數 | 建議值 | 影響 |
|---|---|---|
maxconn | 50000~100000 | 全域最大併發連線數,受限於 ulimit -n |
nbproc / nbthread | CPU 核心數 / 2~4 | 多執行緒模式 (2.0+),利用多核 |
tune.bufsize | 16384 (16KB) | 緩衝區大小,大請求頭需調大 |
tune.maxrewrite | 1024 | 重寫緩衝區上限 |
spread-checks | 0~5 (隨機抖動) | 避免健康檢查驚群 |
maxsslrate | 10000 | 每秒最大 SSL 握手數,防禦 DoS |
tune.ssl.default-dh-param | 2048 | DH 參數長度,平衡安全與效能 |
frontend http_front
acl url_api path_beg -i /api/
acl hdr_json req.hdr(Content-Type) -m found
use_backend api_back if url_api hdr_json
backend web_servers
stick-table type ip size 200k expire 30m store http_req_rate(10s),conn_cur
stick on src
# 限流:每 IP 10 秒超過 100 請求拒絕
http-request deny deny_status 429 if { src_http_req_rate(10s) gt 100 }
global
ssl-dh-param-file /etc/haproxy/dhparam2048.pem
tune.ssl.default-dh-param 2048
frontend https_front
bind *:443 ssl crt /etc/haproxy/certs/site.pem alpn h2,http/1.1 npn h2,http/1.1
# OCSP Stapling 需 2.0+ 且憑證含 OCSP URI
frontend mysql_front
mode tcp
bind *:3306
default_backend mysql_back
backend mysql_back
mode tcp
balance leastconn
option mysql-check user haproxy_check
server db1 10.0.4.11:3306 check inter 5s rise 2 fall 3
server db2 10.0.4.12:3306 check inter 5s rise 2 fall 3
echo "show stat" | socat /var/lib/haproxy/stats stdio 整合 Prometheus haproxy_exporterlog-format "%ci:%cp [%tr] %ft %b/%s %TR/%Tw/%Tc/%Tr/%Ta %ST %B %CC %CS %tsc %ac/%fc/%bc/%sc/%rc %sq/%bq %{+Q}r"scur (當前連線)、qcur (佇列)、hrsp_5xx (5xx 回應)、ereq (請求錯誤)haproxy -c -f /etc/haproxy/haproxy.cfg 配置語法檢查systemctl status haproxy + journalctl -u haproxy -f 查看啟動錯誤ss -ltnp | grep haproxy 確認監聽埠netstat -s | grep -i listen 檢查 SYN queue 溢位curl -v https://backend/healthz 手動驗證openssl s_client -connect localhost:443 -servername example.com
# /etc/keepalived/keepalived.conf
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication { auth_type PASS auth_pass Secret123 }
virtual_ipaddress { 192.168.100.100/24 }
}
track_script {
chk_haproxy
}
搭配 notify_master/notify_backup 觸發 HAProxy 重載或狀態同步。
HAProxy 憑藉專職代理架構、極致效能與豐富 L7 功能,已成為現代高流量基礎設施不可或缺的負載均衡基石。掌握其配置藝術與調優哲學,將為系統架構師帶來從容應對流量洪峰的底氣。
CentOS 6.4 安裝 Oracle 11g R2 環境準備全攻略(核心參數、套件、用戶、目錄)
CentOS vsftpd 安裝配置全攻略:匿名/本地/虛擬用戶、PAM 認證、SELinux、防火牆、HTTP 下載整合
Linux 日誌式檔案系統深度解析:從 Ext2 到 Journaling 的演進與優勢
Fedora 9 安裝常見問題與解決方案:光碟安裝、Live CD、Preupgrade 升級全攻略
CentOS 6.x 手動安裝 Oracle JDK 7 全流程:RPM 包部署、環境變量配置、生效驗證
Linux 顯卡驅動安裝實戰:NVIDIA/AMD/Intel 全流程指南