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) 代理。
  • 支援虛擬主機、會話保持、七層處理。
  • 單機可支援萬級並發連線,運行模式易整合既有架構,保護後端 Web 伺服器不直接暴露。
  • 非 HTTP 伺服器:無法直接提供靜態/動態檔案服務,專注於流量分發。

安裝步驟(CentOS 範例)

# 1. 下載原始碼
wget https://haproxy.1wt.eu/download/1.4/src/haproxy-1.4.8.tar.gz
tar zxvf haproxy-1.4.8.tar.gz
cd haproxy-1.4.8

# 2. 編譯安裝(依核心版本選 TARGET)
uname -a                    # 確認核心版本
make TARGET=linux26 PREFIX=/usr/local/haproxy
make install PREFIX=/usr/local/haproxy

核心配置檔 /usr/local/haproxy/haproxy.cfg

global
    maxconn 5120
    chroot /usr/local/haproxy
    uid 99
    gid 99
    daemon
    quiet
    nbproc 2
    pidfile /usr/local/haproxy/haproxy.pid

defaults
    log     global
    mode    http
    option  httplog
    option  dontlognull
    log 127.0.0.1 local3
    retries 3
    option  redispatch
    maxconn 2000
    contimeout  5000
    clitimeout  50000
    srvtimeout  50000

# Web 應用負載均衡
listen webinfo :1080
    mode http
    balance roundrobin
    option httpclose
    option forwardfor
    server phpinfo1 192.168.18.2:10000 check weight 1 minconn 1 maxconn 3 inter 40000
    server phpinfo2 127.0.0.1:80     check weight 1 minconn 1 maxconn 3 inter 40000

# 另一組服務
listen webmb :1081
    mode http
    balance roundrobin
    option httpclose
    option forwardfor
    server webmb1 192.168.1.91:10000 weight 1 minconn 1 maxconn 3 inter 40000
    server webmb2 127.0.0.1:10000    weight 1 minconn 1 maxconn 3 inter 40000

# 統計頁面
listen stats :8888
    mode http
    stats uri /haproxy-stats
    stats realm "Haproxy Statistic"
    stats auth admin:admin

關鍵指令說明

  • balance roundrobin:輪詢演算法。
  • check:啟用健康檢查。
  • inter 40000:健檢間隔 40 秒。
  • option forwardfor:添加 X-Forwarded-For 標頭,後端可見真實 Client IP。
  • stats uri /haproxy-stats:監控頁面路徑。

啟動與驗證

/usr/local/haproxy/sbin/haproxy -f /usr/local/haproxy/haproxy.cfg
ps -e | grep haproxy   # 應見兩行 (nbproc 2)

測試與監控

  • 服務測試:https://localhost:1080/phpinfo.php
  • 統計頁面:https://localhost:8888/haproxy-stats(帳號 admin/admin)

架構對比

Nginx/Apache Proxy/Lighttpd/Cherokee 皆為 **Web 伺服器** 附帶反向代理;HAProxy **專職負載均衡代理**,無靜態檔案服務功能,專注於高效分發與健檢。

Copyright © Windows教程網 All Rights Reserved