HAProxy七层负载均衡 HAProxy 是一款专业的负载均衡软件,性能很强。这里主要是体验一番负载均衡。
一、环境准备
主机名
ip
用途
haproxy
192.168.10.101
负载均衡入口
nginx-02
192.168.10.102
web-02
nginx-03
192.168.10.103
web-03
nginx-04
192.168.10.104
web-04
1 2 3 4 5 6 cat >> /etc/hosts << EOF 192.168.10.101 haproxy 192.168.10.102 web-02 192.168.10.103 web-03 192.168.10.104 web-04 EOF
二、安装必备软件 2.1 安装haproxy
2.2 安装 nginx
nginx-02
nginx-03
nginx-04s
1 vim /etc/yum.repos.d/nginx.repo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [nginx-stable] name =nginx stable repobaseurl =https://nginx.org/packages/centos/$releasever /$basearch /gpgcheck =1 enabled =1 gpgkey =https://nginx.org/keys/nginx_signing.keymodule_hotfixes =true [nginx-mainline] name =nginx mainline repobaseurl =https://nginx.org/packages/mainline/centos/$releasever /$basearch /gpgcheck =1 enabled =0 gpgkey =https://nginx.org/keys/nginx_signing.keymodule_hotfixes =true
1 sudo yum install nginx -y
1 systemctl enable --now nginx
1 echo "$HOSTNAME $(hostname -I) " > /usr/share/nginx/html/index.html
三、配置使用
备份配置
1 cp /etc/haproxy/haproxy.cfg{,.bak}
修改配置
1 vim /etc/haproxy/haproxy.cfg
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 global log 127.0.0.1 local2 chroot /var/lib/haproxy pidfile /var/run/haproxy.pid maxconn 4000 user haproxy group haproxy daemon defaults mode http log global option httplog option dontlognull retries 3 timeout http-request 10s timeout queue 1m timeout connect 10s timeout client 1m timeout server 1m listen stats_page bind *:8080 stats enable stats uri /haproxy?stats stats auth admin:123456 stats refresh 5s frontend my_web_front bind *:80 default_backend my_web_back backend my_web_back balance roundrobin server web-02 192.168.10.102:80 check inter 2000 rise 2 fall 3 server web-03 192.168.10.103:80 check inter 2000 rise 2 fall 3 server web-04 192.168.10.104:80 check inter 2000 rise 2 fall 3
重新启动
1 systemctl restart haproxy
四、验证
脚本批量发起请求
1 for i in {1..6}; do curl 192.168.10.101; done
访问web查看监控页面
1 2 3 http://192.168.10.101:8080/haproxy?stats admin 123456
五、简单对比
特性
LVS
HAProxy
Nginx
工作层次
4层 (传输层 TCP/UDP)
4层 & 7层 (TCP/HTTP)
7层 (HTTP) 为主 (也支持4层)
抗负载能力
超强 (内核级转发,几乎无损耗)
强 (专门优化,并发能力极高)
中偏高 (应用层软件,稍弱于前两者)
功能定位
纯粹的流量分发
专业的负载均衡器
Web服务器 + 反向代理 + 缓存
健康检查
弱 (需配合 Keepalived 等工具)
强 (自带丰富检查机制)
中 (被动检查,高级功能需商业版)
配置难度
难 (涉及网络底层、路由表)
中 (逻辑清晰,参数多)
易 (配置直观,文档丰富)
典型应用
门户入口、超大流量分发
数据库LB、微服务网关、高并发Web
Web服务入口、静态服务器、K8s Ingress