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

  • haproxy
1
yum install haproxy -y

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 repo
baseurl=https://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=https://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_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. 备份配置
1
cp /etc/haproxy/haproxy.cfg{,.bak}
  1. 修改配置
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

# --- 核心实验配置部分 ---

# 1. 监控页面配置 (Dashboard)
listen stats_page
bind *:8080 # 监听端口
stats enable
stats uri /haproxy?stats # 访问路径
stats auth admin:123456 # 认证账号:密码
stats refresh 5s # 自动刷新间隔

# 2. 前端配置 (接收用户请求)
frontend my_web_front
bind *:80 # HAProxy 监听的对外端口
default_backend my_web_back # 转发给哪个后端组

# 3. 后端配置 (实际处理请求的服务器)
backend my_web_back
balance roundrobin # 负载均衡算法:轮询
# check: 开启健康检查
# inter 2000: 每2秒检查一次
# rise 2: 连续成功2次视为上线
# fall 3: 连续失败3次视为宕机
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. 重新启动
1
systemctl restart haproxy

四、验证

  1. 脚本批量发起请求
1
for i in {1..6}; do curl 192.168.10.101; done
  1. 访问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