Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

HAProxy 企業級負載均衡部署與調優完整指南

編輯:Linux 教學

HAProxy 是專注於 TCP/HTTP (Layer 4/7) 高可用負載均衡的專用代理軟體,以極高併發處理能力、豐富健康檢查機制、原生 Session 粘滯、SSL 卸載、ACL 內容路由等功能,廣泛用於高流量 Web 架構前端。本文涵蓋核心特性解析、安裝部署、核心配置範本、效能調優參數、監控與故障排查全生命週期管理。

核心定位:為何選 HAProxy 而非 Nginx/Apache?

維度HAProxyNginxApache 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 Linux 9 / Ubuntu 22.04 為例)

# 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

關鍵效能調優參數 (global/ defaults 區段)

參數建議值影響
maxconn50000~100000全域最大併發連線數,受限於 ulimit -n
nbproc / nbthreadCPU 核心數 / 2~4多執行緒模式 (2.0+),利用多核
tune.bufsize16384 (16KB)緩衝區大小,大請求頭需調大
tune.maxrewrite1024重寫緩衝區上限
spread-checks0~5 (隨機抖動)避免健康檢查驚群
maxsslrate10000每秒最大 SSL 握手數,防禦 DoS
tune.ssl.default-dh-param2048DH 參數長度,平衡安全與效能

進階功能實戰範例

1. 基於 ACL 的七層路由


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

2. Stick Table 實現 Session 粘滯與限流


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 }

3. SSL 終結與 OCSP Stapling


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

4. TCP Layer 4 轉發 (MySQL/Redis/PostgreSQL)


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

監控與可觀測性

  • Stats Socket:echo "show stat" | socat /var/lib/haproxy/stats stdio 整合 Prometheus haproxy_exporter
  • 日誌格式化:log-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 (請求錯誤)

常見故障排查清單

  1. haproxy -c -f /etc/haproxy/haproxy.cfg 配置語法檢查
  2. systemctl status haproxy + journalctl -u haproxy -f 查看啟動錯誤
  3. ss -ltnp | grep haproxy 確認監聽埠
  4. netstat -s | grep -i listen 檢查 SYN queue 溢位
  5. 後端健康檢查失敗:curl -v https://backend/healthz 手動驗證
  6. SSL 握手失敗:openssl s_client -connect localhost:443 -servername example.com

高可用架構:Keepalived/VRRP + HAProxy


# /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 功能,已成為現代高流量基礎設施不可或缺的負載均衡基石。掌握其配置藝術與調優哲學,將為系統架構師帶來從容應對流量洪峰的底氣。

Copyright © Windows教程網 All Rights Reserved