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