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 漂移)

避免单点故障

相关推荐
Csvn1 天前
OpenSpec 详细使用教程
前端
之歆1 天前
Day19_LESS 完全指南——从入门到工程实践
前端·css·less
云水一下1 天前
HTML5 从入门到精通:实战收官——从零搭建完整静态网站,综合运用所有知识
前端·html5
不总是1 天前
Windows 系统 Node.js 免安装版(zip)安装与配置教程(2026 最新)
前端·windows·node.js
冬奇Lab1 天前
每日一个开源项目(第105篇):Twenty - 跳出 Salesforce 的圈套,定义现代开源 CRM
前端·后端·开源
zhangyao9403301 天前
开发pc端时,表格的高度怎么设置才能铺满页面
前端·javascript·elementui
kjs--1 天前
浏览器书签执行脚本
前端
之歆1 天前
Day16_JavaScript 轮播图与事件工程实战(下篇)
服务器·开发语言·前端·javascript·网络·性能优化
沄媪1 天前
CSRF 跨站请求伪造
前端·ctf·csrf
kyriewen1 天前
我关掉了Copilot:因为我写的代码出现在了别人的建议里
前端·javascript·ai编程