HAProxy 是一套開源的高效能網站平衡負載工具, HAProxy 可以將如 web server, database server 等負載工作分配到一台以上的主機, 可以增強整體的效能及穩定性。以下會介紹在 RHEL 及 CentOS 安裝及配置 HAProxy 的方法。
以下會以 CentOS 6.7 作為安裝平台, 系統的 IP 是 192.168.1.100, Hostname 是 web.testing.com.
另外假設已經安裝好 3 台用作分流的 Client Web Servers, 假設 IP 及 Hostname 資料如下:
IP: 192.168.1.101 (hostname: web01.testing.com)
IP: 192.168.1.102 (hostname: web02.testing.com)
IP: 192.168.1.103 (hostname: web03.testing.com)
安裝 HAProxy
在 CentOS 安裝 HAProxy 最簡單的方法是透過 YUM 直接安裝:
安裝 HAProxy 後, 需要修改一些設定, HAProxy 的設定檔位置是 /etc/haproxy/haproxy.cfg, 以下是配置 HTTP 及 HTTPS 平衡負載的例子, 裡面的 IP 地址需要根據 Client Web Servers 的 IP 更改:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
global log 127.0.0.1 local0 log 127.0.0.1 local1 debug maxconn 45000 daemon nbproc 1 defaults timeout server 86400000 timeout connect 86400000 timeout client 86400000 timeout queue 1000s # [HTTP Configuration] listen http_web 192.168.1.100:80 mode http balance roundrobin option httpchk option forwardfor server server1 192.168.1.101:80 weight 1 maxconn 512 check server server2 192.168.1.102:80 weight 1 maxconn 512 check server server3 192.168.1.103:80 weight 1 maxconn 512 check # [HTTPS Configuration] listen https_web 192.168.1.100:443 mode tcp balance source# Load Balancing algorithm reqadd X-Forwarded-Proto:\ http server server1 192.168.1.101:443 weight 1 maxconn 512 check server server2 192.168.1.102:443 weight 1 maxconn 512 check server server2 192.168.1.102:443 weight 1 maxconn 512 check |
設定了分流的 Client Web Serers 的 IP 後, 啟動 HAProxy 及設定開機自動執行:
# chkconfig haproxy on
接著要用 iptables 開啟 80 及 443 埠號:
# iptables -A INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
# iptables -A INPUT -i eth0 -p tcp --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT
如果是 RHEL 及 CentOS 7 要用 firewall-cmd 開啟
# firewallcmd permanent zone=public addport=443/tcp
# firewallcmd reload
要測試 HAProxy 平衡負載是否正確執行, 可以分別在 3 台分流主機上的 DocumentRoot 位置放置一個測試的 HTML 檔, 以下是測試 HTML 檔的內容:
1 2 3 4 5 6 7 8 9 |
<html> <head> <title>HAProxy Testing Page</title> </head> <body> HAProxy Testing Page </body> </html> |
然後用瀏覽器嘗試連接到安裝 HAProxy 的主機, 以上例子是 http://192.168.1.100, 如果可以看到以上的 "HAProxy Testing Page" 測試頁面, 那便表示運作正常了。
要存取 HAProxy 的統計資料, 可以透過以下網址查閱, 登入用戶名稱為 "haproxy", 密碼為 "redhat":
http://192.168.1.100/stats