Haproxy搭建Web群集

用 HAProxy 搭建 Web 集群(负载均衡),核心是把用户请求分发到多台后端 Web 服务器,提升并发与可用性。下面是完整、可直接复制的实战步骤(CentOS/RHEL 环境)。

一、环境规划(示例)

HAProxy 负载均衡器:192.168.1.100(CentOS 7/8/9)

Web 服务器 1(Nginx):192.168.1.101

Web 服务器 2(Nginx):192.168.1.102

所有机器关闭防火墙、SELinux(测试环境)

二、步骤 1:配置后端 Web 服务器(两台都做)

bash

运行

1. 安装 Nginx

yum install -y nginx

2. 创建区分页面(方便测试负载均衡)

Web1 (101):

echo "<h1>Web Server 1 (192.168.1.101)</h1>" > /usr/share/nginx/html/index.html

Web2 (102):

echo "<h1>Web Server 2 (192.168.1.102)</h1>" > /usr/share/nginx/html/index.html

3. 启动并开机自启

systemctl start nginx

systemctl enable nginx

三、步骤 2:在 192.168.1.100 安装与配置 HAProxy

  1. 安装 HAProxy

bash

运行

yum install -y haproxy

或 dnf install haproxy -y (CentOS 8+/RHEL 8+)

  1. 备份并编辑配置(关键)

bash

运行

cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.bak

vim /etc/haproxy/haproxy.cfg

完整可用配置(直接替换):

ini

global

log 127.0.0.1 local3 info

chroot /var/lib/haproxy

pidfile /var/run/haproxy.pid

user haproxy

group haproxy

daemon

maxconn 4096

defaults

mode http

log global

option httplog

option dontlognull

retries 3

timeout http-request 5s

timeout queue 1m

timeout connect 5s

timeout client 1m

timeout server 1m

maxconn 2048

监听 80 端口,Web 集群

listen web_cluster

bind 0.0.0.0:80

option httpchk GET /index.html # HTTP 健康检查

balance roundrobin # 轮询算法

server web1 192.168.1.101:80 check inter 2000 fall 3 rise 2

server web2 192.168.1.102:80 check inter 2000 fall 3 rise 2

监控页面(可选,推荐)

listen stats

bind 0.0.0.0:1080

stats enable

stats uri /stats # 访问路径

stats auth admin:Admin@123 # 账号密码

stats refresh 30s # 刷新间隔

  1. 启动、开机自启、检查配置

bash

运行

检查配置是否正确

haproxy -c -f /etc/haproxy/haproxy.cfg

启动

systemctl start haproxy

systemctl enable haproxy

查看状态

systemctl status haproxy

四、步骤 3:测试负载均衡

浏览器 /curl 访问 HAProxy IP:

bash

运行

curl http://192.168.1.100

多次刷新 / 请求,会交替显示 Server 1 / Server 2(轮询生效)。

查看 HAProxy 监控:

访问:http://192.168.1.100:1080/stats

输入账号:admin / 密码:Admin@123

可看到两台 Web 节点状态、流量、健康检查结果。

五、常用调度算法(balance)

roundrobin:轮询(默认,加权)

leastconn:最小连接数(适合长连接应用)

source:根据客户端 IP 哈希(会话保持)

uri:根据 URL 哈希

url_param:根据 URL 参数哈希

六、健康检查关键参数

check:开启健康检查

inter 2000:检查间隔 2 秒

fall 3:失败 3 次标记为宕机

rise 2:恢复 2 次标记为上线

option httpchk GET /index.html:七层 HTTP 检查

七、高可用扩展(生产必备)

用 Keepalived 给 HAProxy 做双机热备(VIP 漂移)

避免单点故障

相关推荐
扶风ff1 天前
新品知识更新太快?用练题簿在线刷题,安排企业培训的小测与复盘
前端·学习·小程序
对空六课1 天前
支持注意力分析的热力图工具有哪些?
前端·数据库·数据分析
Csvn1 天前
Vue3 响应式与编译:依赖收集如何升级为节点级靶向更新
前端
星栈1 天前
pnpm 12 升级实测
前端·javascript
Sirens.1 天前
Java并发锁详解:六类锁策略与 synchronized 底层原理
java·前端·算法
特创数字科技1 天前
一个纯本地运行的图片处理工具:压缩 / 裁剪 / 九宫格 / 圆角 / 滤镜 / 拼图 / 水印,终生使用
前端
IT_陈寒1 天前
Vue的v-if和v-for混用居然是个天坑
前端·人工智能·后端
天衍四九-1 天前
【无标题】
前端·spring boot·mysql·nginx·docker
广州华水科技1 天前
2026年单北斗GNSS变形监测系统推荐榜单,解锁GNSS位移监测新高度
前端
xcyxiner1 天前
DicomViewer24 修复编译bug(window test 失败)
前端·qt