萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

手把手教你在 Linux 上部署 HAProxy 搭建高可用 HTTP 負載均衡集群

隨著業務增長,單台 Web 服務器難以應對高併發與故障恢復需求。HAProxy 作為業界標杆級的開源 TCP/HTTP 負載均衡器,憑藉單線程事件驅動架構、微秒級調度延遲、豐富的健康檢查與 ACL 功能,成為構建高可用集群的首選。本教程將從零開始,手把手帶你在 CentOS/Debian/Ubuntu 上部署 HAProxy,實現多後端 Web 服務器的智能流量分發。

架構概覽

  • 負載均衡器 (LB): 192.168.100.4,運行 HAProxy,監聽 80 端口
  • 後端 Web 節點:
    • web01: 192.168.100.2:80
    • web02: 192.168.100.3:80
  • 演算法: Round Robin (輪詢),支援 Cookie 會話保持
  • 監控: 內建 Stats 頁面,HTTP Basic Auth 保護

前置條件

  • 後端 Web 服務已就緒並可互通(測試 curl 192.168.100.2)
  • LB 節點可訪問公網或內網 YUM/APT 源
  • 關閉或配置防火牆允許 80/8834/514 端口

安裝 HAProxy

Debian / Ubuntu

# Debian 10/11 需啟用 backports (可選,獲取較新版)
echo "deb https://deb.debian.org/debian $(lsb_release -sc)-backports main" | sudo tee /etc/apt/sources.list.d/backports.list
sudo apt update
sudo apt install haproxy

CentOS / RHEL / Rocky / AlmaLinux

sudo dnf install -y epel-release
sudo dnf install -y haproxy

核心配置:/etc/haproxy/haproxy.cfg

備份原配置後,替換為以下生產就緒模板:

1. Global 區塊:日誌與進程模型

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

2. 日誌系統整合 (rsyslog)

創建 /etc/rsyslog.d/haproxy.conf:

$ModLoad imudp
$UDPServerRun 514
$template Haproxy,"%msg%\n"
local0.=info     /var/log/haproxy.log;Haproxy
local0.notice    /var/log/haproxy-status.log;Haproxy
local0.*         ~

重啟 rsyslog:sudo systemctl restart rsyslog

3. Defaults 區塊:HTTP 優化預設值

defaults
    log         global
    mode        http
    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     20000

4. Frontend & Backend:核心調度邏輯

frontend http_in
    bind *:80
    mode http
    # 統計頁面
    stats enable
    stats uri /haproxy?stats
    stats realm "HAProxy Statistics"
    stats auth admin:StrongPassword123  # 生產環境請修改強密碼
    # 默認後端
    default_backend webfarm

backend webfarm
    mode http
    balance roundrobin
    # Cookie 會話保持 (插入模式,間接,不緩存)
    cookie LBN insert indirect nocache
    option httpchk GET /healthz      # 健康檢查端點
    server web01 192.168.100.2:80 cookie node1 check inter 2000 rise 2 fall 3
    server web02 192.168.100.3:80 cookie node2 check inter 2000 rise 2 fall 3

關鍵參數解讀

  • balance roundrobin:輪詢調度,亦可改為 leastconn (最少連接)、source (IP Hash)、uri、url_param、hdr(name) 等。
  • cookie LBN insert indirect nocache:HAProxy 自動插入 LBN=node1 Cookie,瀏覽器攜帶後固定路由至同一節點,indirect 表示不覆寫後端 Cookie,nocache 防止中間緩存干擾。
  • option httpchk GET /healthz:主動健康檢查,後端需提供 /healthz 返回 2xx/3xx,否則標記 DOWN。
  • check inter 2000 rise 2 fall 3:每 2 秒檢查,連續 2 次成功視為 UP,連續 3 次失敗視為 DOWN。

啟動與驗證

sudo systemctl enable --now haproxy
sudo systemctl status haproxy
# 測試統計頁
curl -u admin:StrongPassword123 https://192.168.100.4/haproxy?stats
# 測試負載均衡
for i in {1..10}; do curl -s https://192.168.100.4 | grep "Server IP"; done

進階:HTTPS/SSL 終結

將證書合併為 /etc/haproxy/certs/site.pem (含私鑰+完整鏈),修改 frontend:

frontend https_in
    bind *:443 ssl crt /etc/haproxy/certs/site.pem alpn h2,http/1.1
    http-request set-header X-Forwarded-Proto https
    default_backend webfarm

常見坑位避雷

  1. SELinux 阻擋:setsebool -P haproxy_connect_any=1 或設定 httpd_can_network_connect。
  2. 防火牆:firewall-cmd --permanent --add-service=http --add-service=https; firewall-cmd --reload。
  3. maxconn 過小:依據壓測調整 global/frontends/servers 三層 maxconn。
  4. 健康檢查 404:後端必須實現 /healthz 或修改 httpchk 路徑。
  5. Cookie 域名問題:跨子域會話保持需添加 domain .example.com。

總結

通過以上配置,你已擁有一個具備健康檢查、會話保持、統計監控、HTTPS 就緒的生產級 HTTP 負載均衡器。後續可擴展:引入 Keepalived/VRRP 實現 LB 雙機熱備,接入 Prometheus + Grafana 做歷史趨勢監控,或啟用 HAProxy Enterprise 的 WAF 模組防禦 Web 攻擊。HAProxy 文檔極其詳盡,建議收藏 官方文檔 持續深入。

copyright © 萬盛學電腦網 all rights reserved