集群工具之HAProxy
HAProxy简介
- 它是一款实现负载均衡的调度器
- 适用于负载特别大的web站点
- HAProxy的工作模式- mode http:只适用于- web服务
- mode tcp:适用于各种服务
- mode health:仅做健康检查,很少使用
 
配置HAProxy

- client:- eth0->192.168.88.10
- haproxy:- eth0->192.168.88.50;- eth1->192.168.99.50
- web1:- eth0->192.168.99.100
- web2:- eth0->192.168.99.200
环境准备
- client
# 配置ip
nmcli connection modify eth0 ipv4.method manual ipv4.addresses 192.168.88.10/24 ipv4.gateway 192.168.88.254 connection.autoconnect yes
- HAProxy
# 配置ip
nmcli connection modify eth0 ipv4.method manual ipv4.addresses 192.168.88.50/24 ipv4.gateway 192.168.88.254 autoconnect yes
nmcli connection up eth0nmcli connection modify eth1 ipv4.method manual ipv4.addresses 192.168.99.50/24 ipv4.gateway 192.168.99.254 autoconnect yes
nmcli connection up eth1# 安装haproxy
yum install -y haproxy
- web1
# 配置ip
nmcli connection modify eth0 ipv4.method manual ipv4.addresses 192.168.99.100/24 ipv4.gateway 192.168.88.254 connection.autoconnect yes# 开启httpd服务
systemctl start httpd
echo "web1" > /var/www/html/index.html
- web2
# 配置ip
nmcli connection modify eth0 ipv4.method manual ipv4.addresses 192.168.99.200/24 ipv4.gateway 192.168.88.254 connection.autoconnect yes# 开启httpd服务
systemctl start httpd
echo "web2" > /var/www/html/index.html
相关配置
- haproxy
# 修改haproxy服务的配置文件
vim /etc/haproxy/haproxy.cfg
# 文件内容如下,63行之前的不需要改动,将63行后面的全部删除,包括63行,替换成下面的内容
listen myweb 0.0.0.0:80  # 定义本机监听地址balance roundrobin  # 调度算法为轮巡server web1 192.168.99.100 check inter 2000 rise 2 fall 5  # web1服务器健康检查,2000ms检查一次,连续2次成功,代表健康,连续5次失败,代表服务器宕机server web2 192.168.99.200 check inter 2000 rise 2 fall 5  # web2服务器健康检查,2000ms检查一次,连续2次成功,代表健康,连续5次失败,代表服务器宕机listen stats 0.0.0.0:1080  # 定义监控地址的端口stats refresh 30s  # 监控页面30s自动刷新stats uri /stats  # 定义监控的uri地址是/statsstats auth bhlu:1234  # 定义监控页面的用户名是bhlu,密码是1234# 启动服务
systemctl start haproxy# 查看服务是否正常启动,如果有报错-l可以全部显示出来
systemctl status haproxy -l
效果演示
- client
for i in {1..6}; do curl http://192.168.88.50; done
# web1 web2 web1 web2 web1 web2
- 访问监控地址
图片后续补上
补充:负载均衡调度器的简单比较
nginx:可以工作在第4层和第7层。可以根据url进行负载均衡。正则表达式支持的更广泛。
lvs:效率最高。工作在第4层。
haproxy:可以工作在第4层和第7层。可以根据url进行负载均衡。支持有限的正则表达式,属于适中的状态。