1.负载均衡
1.1什么是负载均衡
负载均衡:Load Balance,简称LB,是一种服务或基于硬件设备等实现的高可用反向代理技术,负载均衡将特定的业务(web服务、网络流量等)分担给指定的一个或多个后端特定的服务器或设备,从而提高了 公司业务的并发处理能力、保证了业务的高可用性、方便了业务后期的水平动态扩展。
阿里云SLB介绍 :https://yq.aliyun.com/articles/1803
负载均衡
1.2为什么用负载均衡
- Web服务器的动态水平扩展-->对用户无感知
- 增加业务并发访问及处理能力-->解决单服务器瓶颈问题
- 节约公网IP地址-->降低IT支出成本
- 隐藏内部服务器IP-->提高内部服务器安全性
- 配置简单-->固定格式的配置文件
- 功能丰富-->支持四层和七层,支持动态下线主机
- 性能较强-->并发数万甚至数十万
1.3****四层负载均衡
四层代理
1.通过ip+port决定负载均衡的去向。
2.对流量请求进行NAT处理,转发至后台服务器。
3.记录tcp、udp流量分别是由哪台服务器处理,后续该请求连接的流量都通过该服务器处理。
4.支持四层的软件
- lvs:重量级四层负载均衡器。
- Nginx:轻量级四层负载均衡器,可缓存。(nginx四层是通过upstream模块)
- Haproxy:模拟四层转发。
1.4七层负载均衡
七层代理
1.通过虚拟ur|或主机ip进行流量识别,根据应用层信息进行解析,决定是否需要进行负载均衡。
2.代理后台服务器与客户端建立连接,如nginx可代理前后端,与前端客户端tcp连接,与后端服务器建立tcp连接,
3.支持7层代理的软件:
- Nginx:基于http协议(nginx七层是通过proxy_pass)
- Haproxy:七层代理,会话保持、标记、路径转移等。
1.5四层和七层的区别
所谓的四到七层负载均衡,就是在对后台的服务器进行负载均衡时,依据四层的信息或七层的信息来决****定怎么样转发流量
四层的负载均衡,就是通过发布三层的IP地址(VIP),然后加四层的端口号,来决定哪些流量需要做负 载均衡,对需要处理的流量进行NAT处理,转发至后台服务器,并记录下这个TCP或者UDP的流量是由哪 台服务器处理的,后续这个连接的所有流量都同样转发到同一台服务器处理
七层的负载均衡,就是在四层的基础上(没有四层是绝对不可能有七层的),再考虑应用层的特征,比 如同一个Web服务器的负载均衡,除了根据VIP加80端口辨别是否需要处理的流量,还可根据七层的 URL、浏览器类别、语言来决定是否要进行负载均衡。
- 分层位置:四层负载均衡在传输层及以下,七层负载均衡在应用层及以下
- 性能 :四层负载均衡架构无需解析报文消息内容,在网络吞吐量与处理能力上较高:七层可支持解析应用 层报文消息内容,识别URL、Cookie、HTTP header等信息。、
- 原理 :四层负载均衡是基于ip+port;七层是基于虚拟的URL或主机IP等。
- 功能类比:四层负载均衡类似于路由器;七层类似于代理服务器。
- 安全性:四层负载均衡无法识别DDoS攻击;七层可防御SYN Cookie/Flood攻击
2.haproxy
2.1haproxy****简介
HAProxy是法国开发者 威利塔罗(Willy Tarreau) 在2000年使用C语言开发的一个开源软件
是一款具备高并发(万级以上)、高性能的TCP和HTTP负载均衡器。
支持基于cookie的持久性,自动故障切换,支持正则表达式及web状态统计。
- 企业版网站:https://www.haproxy.com
- 社区版网站:http://www.haproxy.org
- github:https://github.com/haprox
企业版本和社区版功能对比
|----------------------------------|-----|-----|
| 功能 | 社区版 | 企业版 |
| 高级HTTP / TCP负载平衡和持久性 | 支持 | 支持 |
| 高级健康检查 | 支持 | 支持 |
| 应用程序加速 | 支持 | 支持 |
| 高级安全特性 | 支持 | 支持 |
| 高级管理 | 支持 | 支持 |
| HAProxy Dev Branch新功能 | | 支持 |
| 24*7 支持服务 | | 支持 |
| 实时仪表盘 | | 支持 |
| VRRP和Route Health Injection HA工具 | | 支持 |
| ACL,映射和TLS票证密钥同步 | | 支持 |
| 基于应用程序的高级DDoS和Bot保护(自动保护) | | 支持 |
| Bot(机器人)监测 | | 支持 |
| Web应用防火墙 | | 支持 |
| HTTP协议验证 | | 支持 |
| 实时集群追踪 | | |
2.2HAPORXY实验
2.2.1环境设定
haproxy实验环境
haproxy主机
bash
[root@haproxy ~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
link/ether 00:0c:29:ae:4a:ca brd ff:ff:ff:ff:ff:ff
altname enp3s0
altname ens160
inet 172.25.254.100/24 brd 172.25.254.255 scope global noprefixroute eth0
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:feae:4aca/64 scope link noprefixroute
valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
link/ether 00:0c:29:ae:4a:d4 brd ff:ff:ff:ff:ff:ff
altname enp19s0
altname ens224
inet 192.168.0.100/24 brd 192.168.0.255 scope global noprefixroute eth1
valid_lft forever preferred_lft forever
inet6 fe80::e811:3593:b4e4:b086/64 scope link noprefixroute
valid_lft forever preferred_lft forever
#配置内核路由功能
[root@haproxy ~]# echo net.ipv4.ip_forward=1 > /etc/sysctl.conf
[root@haproxy ~]# sysctl -p
net.ipv4.ip_forward = 1
webserver1与webserver2(修改其中的IP就行其他操作一样)
bash
[root@webserver1 ~]# dnf install httpd -y > /dev/null
[root@webserver1 ~]# echo webserver1 - 192.168.0.10 > /var/www/html/index.html
[root@webserver1 ~]# systemctl enable --now httpd
Created symlink /etc/systemd/system/multi-user.target.wants/httpd.service → /usr/lib/systemd/system/httpd.service.
[root@webserver1 ~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
link/ether 00:0c:29:f4:16:af brd ff:ff:ff:ff:ff:ff
altname enp3s0
altname ens160
inet 192.168.0.10/24 brd 192.168.0.255 scope global noprefixroute eth0
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fef4:16af/64 scope link noprefixroute
valid_lft forever preferred_lft forever
haproxy的安装以及配置参数
bash
[root@haproxy ~]# dnf search haproxy
正在更新 Subscription Management 软件仓库。
无法读取客户身份
本系统尚未在权利服务器中注册。可使用 subscription-manager 进行注册。
上次元数据过期检查:37 days, 2:51:06 前,执行于 2026年01月16日 星期五 15时57分06秒。
========================================= 名称 和 概况 匹配:haproxy ==========================================
haproxy.x86_64 : HAProxy reverse proxy for high availability environments
pcp-pmda-haproxy.x86_64 : Performance Co-Pilot (PCP) metrics for HAProxy
[root@haproxy ~]# dnf install haproxy.x86_64 -y >/dev/null
[root@haproxy ~]# systemctl enable --now haproxy.service
Created symlink /etc/systemd/system/multi-user.target.wants/haproxy.service → /usr/lib/systemd/system/haproxy.service.
haproxy****的基本配置信息
官方文档:http://cbonte.github.io/haproxy-dconv/
HAProxy 的配置文件haproxy.cfg由两大部分组成,分别是:
global:全局配置段
- 进程及安全配置相关的参数
- 性能调整相关参数
- Debug参数
proxies:代理配置段
- defaults:为frontend, backend, listen提供默认配置
- frontend:前端,相当于nginx中的server {}
- backend:后端,相当于nginx中的upstream {}
- listen:同时拥有前端和后端配置,配置简单,生产推荐使用
global****配置参数说明
bash
global
log 127.0.0.1 local2 #定义全局的syslog服务器;日志服务器需要开启UDP
协议,最多可以定义两个
chroot /var/lib/haproxy #锁定运行目录
pidfile /var/run/haproxy.pid #指定pid文件
maxconn 100000 #指定最大连接数
user haproxy #指定haproxy的运行用户
group haproxy #指定haproxy的运行组
daemon #指定haproxy以守护进程方式运行
# turn on stats unix socket
stats socket /var/lib/haproxy/stats #指定haproxy的套接字文件多进程和socket文件配置如下:
nbproc 2 #指定haproxy的work进程数量,默认是1个
cpu-map 1 0 #指定第一个work绑定第一个cpu核心
cpu-map 2 1 #指定第二个work绑定第二个cpu核心
nbthread 2 #指定haproxy的线程数量,默认每个进程一个线程,此参数与nbproc互斥
maxsslconn 100000 #每个haproxy进程ssl最大连接数,用于haproxy配置了证书的场景下
maxconnrate 100 #指定每个客户端每秒建立连接的最大数量
多进程和线程
多进程和socket文件配置如下:
bash
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面内容省略...
global
log 127.0.0.1 local2
chroot /var/lib/haproxy
pidfile /var/run/haproxy.pid
maxconn 100000
user haproxy
group haproxy
daemon
# turn on stats unix socket
stats socket /var/lib/haproxy/haproxy.sock1 mode 600 level admin process 1
#启用多个sock文件
stats socket /var/lib/haproxy/haproxy.sock2 mode 600 level admin process 2
nbproc 2 #启用多进程
cpu-map 1 0 #进程和cpu核心绑定防止cpu抖动从而减少系统资源消耗
cpu-map 2 1 #2 表示第二个进程,1表示第二个cpu核心
...下面内容省略 ...
启用多线程
bash
haproxy ~]# vim /etc/haproxy/haproxy.cfg
...上面内容省略...
log 127.0.0.1 local2
chroot /var/lib/haproxy
pidfile /var/run/haproxy.pid
maxconn 100000
user haproxy
group haproxy
daemon
# turn on stats unix socket
stats socket /var/lib/haproxy/haproxy.sock1 mode 600 level admin process 1
#启用多个sock文件
stats socket /var/lib/haproxy/haproxy.sock2 mode 600 level admin process 2
#nbproc 2
#cpu-map 1 0
#cpu-map 2 1
nbthread 2 #启用多线程
...下面内容省略...
proxies****配置
proxies参数说明proxies
|---------------|---------|---------------------------------------------------------|
| 参数 | 类型 | 作用 |
| defaults \[\] | proxies | 默认配置项,针对以下的frontend、backend和listen生效,可以多个 name也可以没有name |
| frontend | proxies | 前端servername,类似于Nginx的一个虚拟主机 server和LVS服务集 群。 |
| backend | proxies | #后端服务器组,等于nginx的upstream和LVS中的RS服务器 listen proxies |
| listen | proxies | #将frontend和backend合并在一起配置,相对于frontend和backend配置更简洁,生产常用 |
注:name字段只能使用大小写字母,数字,'-'(dash),'_'(underscore),'.' (dot)和 ':'(colon),并且严格区分大小写
Proxies配置-defaults
bash
defaults
mode http #HAProxy实例使用的连接协议
log global #指定日志地址和记录日志条目的syslog/rsyslog日志设备
#此处的 global表示使用 global配置段中设定的log值。
option httplog #日志记录选项,httplog表示记录与HTTP会话相关的各种属性值
#包括 HTTP请求、会话状态、连接数、源地址以及连接时间等
option dontlognull #dontlognull表示不记录空会话连接日志
option http-server-close #等待客户端完整HTTP请求的时间,此处为等待10s。
option forwardfor except 127.0.0.0/8 #透传客户端真实IP至后端web服务器
#在apache配置文件中加入:<br>%{XForwarded-For}i
#后在webserver中看日志即可看到地址透传信息
option redispatch #当server Id对应的服务器挂掉后,强制定向到其他健康的服务器,重新派发
option http-keep-alive #开启与客户端的会话保持
retries 3 #连接后端服务器失败次数
timeout http-request 10s #等待客户端请求完全被接收和处理的最长时间
timeout queue 1m #设置删除连接和客户端收到503或服务不可用等提示信息前的等待时间
timeout connect 120s #设置等待服务器连接成功的时间
timeout client 600s #设置允许客户端处于非活动状态,即既不发送数据也不接收数据的时间
timeout server 600s #设置服务器超时时间,即允许服务器处于既不接收也不发送数据的非活动时间
timeout http-keep-alive 60s #session 会话保持超时时间,此时间段内会转发到相同的后端服务器
timeout check 10s #指定后端服务器健康检查的超时时间
maxconn 3000
default-server inter 1000 weight 3
Proxies配置-frontend
bash
bind:指定HAProxy的监听地址,可以是IPV4或IPV6,可以同时监听多个IP或端口,可同时用于listen字段中
#格式:
bind [<address>]:<port_range> [, ...] [param*]
#注意:如果需要绑定在非本机的IP,需要开启内核参数:net.ipv4.ip_nonlocal_bind=1
backlog <backlog> #针对所有server配置,当前端服务器的连接数达到上限后的后援队列长度,注意:
不支持backend
frontend****配置示例:
frontend webcluster
bind *:80
mode http
use_backend webserver-80
Proxies配置-backend
- 定义一组后端服务器,backend服务器将被frontend进行调用。
- 注意: backend 的名称必须唯一,并且必须在listen或frontend中事先定义才可以使用,否则服务无法启动
bash
mode http|tcp #指定负载协议类型,和对应的frontend必须一致
option #配置选项
server #定义后端real server,必须指定IP和端口
注意:option后面加 httpchk,smtpchk,mysql-check,pgsql-check,ssl-hello-chk方法,可用于实现更多应用层检测功能。
server****配置
bash
#针对一个server配置
check #对指定real进行健康状态检查,如果不加此设置,默认不开启检查,只有check后面没有其它配置也可以启用检查功能
#默认对相应的后端服务器IP和端口,利用TCP连接进行周期性健康性检查,注意必须指
定端口才能实现健康性检查
addr <IP> #可指定的健康状态监测IP,可以是专门的数据网段,减少业务网络的流量
port <num> #指定的健康状态监测端口
inter <num> #健康状态检查间隔时间,默认2000 ms
fall <num> #后端服务器从线上转为线下的检查的连续失效次数,默认为3
rise <num> #后端服务器从下线恢复上线的检查的连续有效次数,默认为2
weight <weight> #默认为1,最大值为256,0(状态为蓝色)表示不参与负载均衡,但仍接受持久连接
backup #将后端服务器标记为备份状态,只在所有非备份主机down机时提供服务,类似Sorry
Server
disabled #将后端服务器标记为不可用状态,即维护状态,除了持久模式
#将不再接受连接,状态为深黄色,优雅下线,不再接受新用户的请求
redirect prefix http://www.baidu.com/ #将请求临时(302)重定向至其它URL,只适用于http
模式
maxconn <maxconn> #当前后端server的最大并发连接数
代码示例:
backend webserver-80
server web1 192.168.0.10:80 check inter 3s fall 3 rise 5
server web2 192.168.0.20:80 check inter 3s fall 3 rise 5
实验效果
Proxies配置-listen****简化配置
使用listen替换 frontend和backend的配置方式,可以简化设置,通常只用于TCP协议的应用
listen配置示例:
listen webcluster
bind *:80
mode http
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5
实验效果
实现haproxy的多进程
#默认haproxy是单进程
root@haproxy \~# pstree -p | grep haproxy
|-haproxy(31439)---haproxy(31441)-+-{haproxy}(31442)
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
nbproc 2
root@haproxy \~# systemctl restart haproxy.service
#验证
root@haproxy \~# pstree -p | grep haproxy
|-haproxy(31549)-+-haproxy(31551)
| `-haproxy(31552)
#多进程cpu绑定
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
nbproc 2
cpu-map 1 0
cpu-map 2 1
root@haproxy \~# systemctl restart haproxy.service
#为不同进程准备不同套接字
root@haproxy \~# systemctl stop haproxy.service
root@haproxy \~# rm -fr /var/lib/haproxy/stats
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
#stats socket /var/lib/haproxy/stats
stats socket /var/lib/haproxy/haproxy1 mode 600 level admin process 1
stats socket /var/lib/haproxy/haporxy2 mode 660 level admin process 1
root@haproxy \~# systemctl restart haproxy.service
#效果
root@haproxy \~# ll /var/lib/haproxy/
总用量 0
srw-rw---- 1 root root 0 1月 23 15:41 haporxy2
srw------- 1 root root 0 1月 23 15:41 haproxy1
haproxy实现多线程
注意多线程不能和多进程同时启用
#查看当前haproxy的进程信息
root@haproxy \~# pstree -p | grep haproxy
|-haproxy(31742)-+-haproxy(31744)
| `-haproxy(31745)
#查看haproxy子进程的线程信息
root@haproxy \~# cat /proc/31744/status | grep Threads
Threads: 1
#启用多线程
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
#nbproc 2
#cpu-map 1 0
#cpu-map 2 1
nbthread 2
turn on stats unix socket
stats socket /var/lib/haproxy/stats
#stats socket /var/lib/haproxy/haproxy1 mode 600 level admin process 1
#stats socket /var/lib/haproxy/haporxy2 mode 660 level admin process 1
root@haproxy \~# systemctl restart haproxy.service
#效果
root@haproxy \~# pstree -p | grep haproxy
|-haproxy(31858)---haproxy(31860)---{haproxy}(31861)
root@haproxy \~# cat /proc/31860/status | grep Threads
Threads: 2
log 日志管理
指定把日志发送到哪里
实验:指定日志发送到192.168.0.10
bash
#在192.168.0.10 开启接受日志的端口
[root@webserver1 ~]# vim /etc/rsyslog.conf
32 module(load="imudp") # needs to be done just once
33 input(type="imudp" port="514")
[root@webserver1 ~]# systemctl restart rsyslog.service
#测试接受日志端口是否开启
[root@webserver1 ~]# netstat -antlupe | grep rsyslog
udp 0 0 0.0.0.0:514 0.0.0.0:* 0 74140 30965/rsyslogd
udp6 0 0 :::514 :::* 0 74141 30965/rsyslogd
#在haproxy主机中设定日志发送信息
[root@haproxy haproxy]# vim haproxy.cfg
log 192.168.0.10 local2
[root@haproxy haproxy]# systemctl restart haproxy.service
验证:

Haproxy算法实验
- HAProxy通过固定参数 balance 指明对后端服务器的调度算法
- balance参数可以配置在listen或backend选项中。
- HAProxy的调度算法分为静态和动态调度算法
- 有些算法可以根据参数在静态和动态算法中相互转换。
静态算法
静态算法:按照事先定义好的规则轮询公平调度,不关心后端服务器的当前负载、连接数和响应速度 等,且无法实时修改权重(只能为0和1,不支持其它值),只能靠重启HAProxy生效。
static-rr**:基于权重的轮询调度**
- 不支持运行时利用socat进行权重的动态调整(只支持0和1,不支持其它值)
- 不支持端服务器慢启动 注:
慢启动是指在服务器刚刚启动上不会把他所应该承担的访问压力全部给它,而是先给一部分,当没 问题后在给一部分 - 其后端主机数量没有限制,相当于LVS中的 wrr
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance static-rr #算法参数
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 2
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1
root@haproxy \~# systemctl restart haproxy.service

first
- 根据服务器在列表中的位置,自上而下进行调度
- 其只会当第一台服务器的连接数达到上限,新请求才会分配给下一台服务
- 其会忽略服务器的权重设置
- 不支持用socat进行动态修改权重,可以设置0和1,可以设置其它值但无效
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance first
server haha 192.168.0.10:80 maxconn 1 check inter 3s fall 3 rise 5 weight 2
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1
root@haproxy \~# systemctl restart haproxy.service
测试:

动态算法
- 基于后端服务器状态进行调度适当调整,
- 新请求将优先调度至当前负载较低的服务器
- 权重可以在haproxy运行时动态调整无需重启
roundrobin
- 基于权重的轮询动态调度算法,
- 支持权重的运行时调整,不同于lvs中的rr轮训模式,
- HAProxy中的roundrobin支持慢启动(新加的服务器会逐渐增加转发数),
- 其每个后端backend中最多支持4095个real server,
- 支持对real server权重动态调整,
- roundrobin为默认调度算法,此算法使用广泛

动态权重更新
记得安装socat
以及修改配置文件追加
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
stats socket /var/lib/haproxy/stats mode 600 level admin
root@haproxy \~# echo "get weight webcluster/haha" | socat stdio /var/lib/haproxy/stats
2 (initial 2)root@haproxy \~# echo "set weight webcluster/haha 1 " | socat stdio /var/lib/haproxy/stats
root@haproxy \~# echo "get weight webcluster/haha" | socat stdio /var/lib/haproxy/stats
1 (initial 2)
2 leastconn
- leastconn加权的最少连接的动态
- 支持权重的运行时调整和慢启动,即:根据当前连接最少的后端服务器而非权重进行优先调度(新客户 端连接)
- 比较适合长连接的场景使用,比如:MySQL等场景。
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance leastconn
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 2
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1
root@haproxy \~# systemctl restart haproxy.service

混合算法
其它算法即可作为静态算法,又可以通过选项成为动态算法
source
源地址hash,基于用户源地址hash并将请求转发到后端服务器,后续同一个源地址请求将被转发至同一 个后端web服务器。此方式当后端服务器数据量发生变化时,会导致很多用户的请求转发至新的后端服 务器,默认为静态方式,但是可以通过hash-type支持的选项更改这个算法一般是在不插入Cookie的TCP 模式下使用,也可给拒绝会话cookie的客户提供最好的会话粘性,适用于session会话保持但不支持 cookie和缓存的场景源地址有两种转发客户端请求到后端服务器的服务器选取计算方式,分别是取模法 和一致性hash
#默认静态算法
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance source
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 2
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1
root@haproxy \~# systemctl restart haproxy.service
#测试:
root@celint \~# for i in {1..10}; do curl 172.25.254.100; done
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
#source动态算法
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance source
hash-type consistent
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 2
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1
root@haproxy \~# systemctl restart haproxy.service
#测试:
root@celint \~# for i in {1..10}; do curl 172.25.254.100; done
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
**缺陷:**如果访问客户端时一个家庭,那么所有的家庭的访问流量都会被定向到一台服务器,这时source算法的缺陷
uri
基于对用户请求的URI的左半部分或整个uri做hash,再将hash结果对总权重进行取模后
根据最终结果将请求转发到后端指定服务器
适用于后端是缓存服务器场景
默认是静态算法,也可以通过hash-type指定map-based和consistent,来定义使用取模法还是一致性hash
注意:此算法基于应用层,所以只支持 mode http ,不支持 mode tcp
#主备实验环境
root@webserver1 \~# echo RS1 - 192.168.0.10 > /var/www/html/index1.html
root@webserver1 \~# echo RS1 - 192.168.0.10 > /var/www/html/index2.html
root@webserver2 \~# echo RS2 - 192.168.0.20 > /var/www/html/index1.html
root@webserver2 \~# echo RS2 - 192.168.0.20 > /var/www/html/index2.html#设定uri算法
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance uri
hash-type consistent
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 2
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1root@haproxy \~# systemctl restart haproxy.service
#测试
root@Yhu \~# for i in {1..10}; do curl 172.25.254.100/index2.html;done
hjw2-192.168.0.20
hjw2-192.168.0.20
hjw2-192.168.0.20
hjw2-192.168.0.20
hjw2-192.168.0.20
hjw2-192.168.0.20
hjw2-192.168.0.20
hjw2-192.168.0.20
hjw2-192.168.0.20
hjw2-192.168.0.20
root@Yhu \~# for i in {1..10}; do curl 172.25.254.100/index1.html;done
hjw1-192.168.0.10
hjw1-192.168.0.10
hjw1-192.168.0.10
hjw1-192.168.0.10
hjw1-192.168.0.10
hjw1-192.168.0.10
hjw1-192.168.0.10
hjw1-192.168.0.10
hjw1-192.168.0.10
hjw1-192.168.0.10
url_param
url_param对用户请求的url中的 params 部分中的一个参数key对应的value值作hash计算,并由服务器 总权重相除以后派发至某挑出的服务器,后端搜索同一个数据会被调度到同一个服务器,多用与电商
通常用于追踪用户,以确保来自同一个用户的请求始终发往同一个real server
如果无没key,将按roundrobin算法
#主备实验环境
root@webserver1 \~# echo RS1 - 192.168.0.10 > /var/www/html/index1.html
root@webserver1 \~# echo RS1 - 192.168.0.10 > /var/www/html/index2.html
root@webserver2 \~# echo RS2 - 192.168.0.20 > /var/www/html/index1.html
root@webserver2 \~# echo RS2 - 192.168.0.20 > /var/www/html/index2.html
#设定url_param算法
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance url_param name
hash-type consistent
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 2
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1
root@haproxy \~# systemctl restart haproxy.service
测试
root@Yhu \~# for i in {1..10}; do curl 172.25.254.100/index.html?name=hjw2; done
webserver1 - 192.168.0.10
webserver1 - 192.168.0.10
webserver1 - 192.168.0.10
webserver1 - 192.168.0.10
webserver1 - 192.168.0.10
webserver1 - 192.168.0.10
webserver1 - 192.168.0.10
webserver1 - 192.168.0.10
webserver1 - 192.168.0.10
webserver1 - 192.168.0.10
root@Yhu \~# for i in {1..10}; do curl 172.25.254.100/index.html?name=hjw1; done
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
webserver2 - 192.168.0.20
hdr
针对用户每个http头部(header)请求中的指定信息做hash,
此处由 name 指定的http首部将会被取出并做hash计算,
然后由服务器总权重取模以后派发至某挑出的服务器,如果无有效值,则会使用默认的轮询调度。
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance hdr(User-Agent)
hash-type consistent
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 2
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1
root@haproxy \~# systemctl restart haproxy.service
#测试:
root@Yhu \~# curl -A "lee" 172.25.254.100
webserver2 - 192.168.0.20
root@Yhu \~# curl -A "hjw" 172.25.254.100
webserver1 - 192.168.0.10
root@Yhu \~# curl -A "www.baidu.wwwwwwwww" 172.25.254.100
webserver2 - 192.168.0.20
root@Yhu \~# curl -A "wwwwwwwwwwww" 172.25.254.100
webserver1 - 192.168.0.10
root@Yhu \~# curl -A "wwwwwwwwwwww" 172.25.254.100
webserver1 - 192.168.0.10
3.高级功能及配置
基于cookie的会话保持
如果在haprorxy中设定算法为source,在同一台客户端主机中,无论使用什么浏览器访问的最终服务器是同一个
可以使用cookie值进行优化,让同一台客户端中同一个浏览器中访问的是同一个服务器
不同浏览器访问的是不同的服务器
注意:不支持 tcp mode,使用 http mode
#配合基于cookie的会话保持方法
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance roundrobin
hash-type consistent
cookie WEBCOOKIE insert nocache indirect
server haha 192.168.0.10:80 cookie web1 check inter 3s fall 3 rise 5 weight 2
server hehe 192.168.0.20:80 cookie web2 check inter 3s fall 3 rise 5 weight 1root@haproxy \~# systemctl restart haproxy.service
浏览器一

浏览器二

HAProxy状态页
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
listen stats
mode http
bind 0.0.0.0:4321
stats enable
log global
stats refresh
stats uri /status
stats auth lee:lee
root@haproxy \~# systemctl restart haproxy.service
登录测试:

开启自动刷新
加上:stats refresh 1参数就行。

IP透传
七层IP透传
#实验环境
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance roundrobin
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 1
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1
root@haproxy \~# systemctl restart haproxy.service
#测试环境
root@Yhu \~# for i in {1..5}; do curl 172.25.254.100;done
webserver2 - 192.168.0.20
webserver1 - 192.168.0.10
webserver2 - 192.168.0.20
webserver1 - 192.168.0.10
webserver2 - 192.168.0.20
#在rs主机中默认是未开启透传功能的
root@webserver2 \~# cat /etc/httpd/logs/access_log192.168.0.100 - - 22/Feb/2026:20:55:43 +0800 "GET / HTTP/1.1" 200 26 "-" "curl/7.76.1"
192.168.0.100 - - 22/Feb/2026:20:58:48 +0800 "GET / HTTP/1.1" 200 26 "-" "curl/7.76.1"
192.168.0.100 - - 22/Feb/2026:20:58:48 +0800 "GET / HTTP/1.1" 200 26 "-" "curl/7.76.1"
192.168.0.100 - - 22/Feb/2026:20:58:48 +0800 "GET / HTTP/1.1" 200 26 "-" "curl/7.76.1"
192.168.0.100 - - 22/Feb/2026:20:58:48 +0800 "GET / HTTP/1.1" 200 26 "-" "curl/7.76.1"
192.168.0.100 - - 22/Feb/2026:20:58:48 +0800 "GET / HTTP/1.1" 200 26 "-" "curl/7.76.1
#开启ip透传的方式
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
。。。忽略。。。。。
defaults
mode http
log global
option httplog
option dontlognull
option http-server-close
option forwardfor except 127.0.0.0/8 #开启haproxy透传功能
option redispatch
retries 3
timeout http-request 10s
timeout queue 1m
timeout connect 10s
timeout client 1m
timeout server 1m
timeout http-keep-alive 10s
timeout check 10s
maxconn 3000
#在rs中设定采集透传IP
root@webserver2 \~# vim /etc/httpd/conf/httpd.conf
201 LogFormat "%h %l %u %t \"%r\" %>s %b \"%{X-Forwarded-For}i\" \"%{Referer}i\" \"%{User-Agent}i \"" combined
#\"%{X-Forwarded-For}i\" 添加这个参数开启日志采集
root@webserver2 \~# systemctl restart httpd
#测试效果
root@webserver2 \~# cat /etc/httpd/logs/access_log
192.168.0.100 - - 22/Feb/2026:21:08:48 +0800 "GET / HTTP/1.1" 200 26 "172.25.254.131" "-" "curl/7.76.1"
192.168.0.100 - - 22/Feb/2026:21:10:23 +0800 "GET / HTTP/1.1" 200 26 "172.25.254.131" "-" "curl/7.76.1"
四层IP透传
#环境设置
#在RS中把apache停止
root@webserver1 \~# systemctl disable --now httpd
root@webserver2 \~# systemctl disable --now httpd
#部署nginx
root@webserver1 \~# dnf install nginx -y
root@webserver2 \~# dnf install nginx -y
root@webserver1 \~# echo hello nginx-192.268.0.10 >/usr/share/nginx/html/index.html
root@webserver2 \~# echo hello nginx-192.268.0.20 >/usr/share/nginx/html/index.html
root@webserver1 \~# systemctl enable --now nginx
root@webserver2 \~# systemctl enable --now nginx
#测环境
root@Yhu \~# for i in {1..5}; do curl 172.25.254.100;done
hello nginx-192.168.0.10
hello nginx-192.268.0.20
hello nginx-192.168.0.10
hello nginx-192.268.0.20
hello nginx-192.168.0.10
#启用nginx的四层访问控制
root@webserver1 \~# vim /etc/nginx/nginx.conf
server {
listen 80 proxy_protocol; #启用四层访问控制添加proxy_protocol
listen :::80;
server_name _;
root /usr/share/nginx/html;
Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
error_page 404 /404.html;
location = /404.html {
}
root@webserver2 \~# vim /etc/nginx/nginx.conf
server {
listen 80 proxy_protocol; #启用四层访问控制
listen :::80;
server_name _;
root /usr/share/nginx/html;
Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
error_page 404 /404.html;
location = /404.html {
}
root@webserver1 \~# systemctl restart nginx.service
root@webserver2 \~# systemctl restart nginx.service
#测试
Administrator.DESKTOP-VJ307M3] ➤ curl 172.25.254.100
<html><body><h1>502 Bad Gateway</h1>
The server returned an invalid or incomplete response.
</body></html>
出现上述报错标识nginx只支持四层访问
#设定haproxy访问4层
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
mode tcp #四层访问将http改为tcp
balance roundrobin
server haha 192.168.0.10:80 send-proxy check inter 3s fall 3 rise 5 weight 1
server hehe 192.168.0.20:80 send-proxy check inter 3s fall 3 rise 5 weight 1 #同时详细信息中添加send-proxy这个参数
root@haproxy \~# systemctl restart haproxy.service
#测试四层访问
Administrator.DESKTOP-VJ307M3 ➤ for i in {1..5}; do curl 172.25.254.100; done
RS1 - 192.168.0.10
RS2 - 192.168.0.20
RS1 - 192.168.0.10
RS2 - 192.168.0.20
RS1 - 192.168.0.10
#设置4层ip透传
root@webserver1\&2 \~# vim /etc/nginx/nginx.conf
log_format main 'remote_addr - remote_user $time_local "$request" '
'"proxy_protocol_addr"' #采集透传信息添加'"proxy_protocol_addr"'
'status body_bytes_sent "$http_referer" '
'"http_user_agent" "http_x_forwarded_for"';
root@webserver1\&2 \~# systemctl restart nginx.service
#测试
Administrator.DESKTOP-VJ307M3 ➤ for i in {1..5}; do curl 172.25.254.100; done
RS2 - 192.168.0.20
RS1 - 192.168.0.10
RS2 - 192.168.0.20
RS1 - 192.168.0.10
RS2 - 192.168.0.20
root@webserver1 \~# cat /var/log/nginx/access.log
192.168.0.100 - - 22/Feb/2026:21:09:36 +0800 "GET / HTTP/1.1" "172.25.254.131"200 25 "-" "curl/7.76.1" "-"
192.168.0.100 - - 22/Feb/2026:21:10:23 +0800"GET / HTTP/1.1" "172.25.254.131"200 25 "-" "curl/7.76.1" "-"
192.168.0.100 - - 22/Feb/2026:21:10:26 +0800 "GET / HTTP/1.1" "172.25.254.131"200 25 "-" "curl/7.76.1" "-"
自定义HAProxy 错误界面
sorryserver的设定
正常的所有服务器如果出现宕机,那么客户将被定向到指定的主机中,这个当业务主机出问题时被临时访问的主机叫做sorryserver
#在新主机中安装apache(可以用haproxy主机代替)
root@haproxy \~# dnf install httpd -y
root@haproxy \~# vim /etc/httpd/conf/httpd.conf
47 Listen 8080
root@haproxy \~# systemctl enable --now httpd
Created symlink /etc/systemd/system/multi-user.target.wants/httpd.service → /usr/lib/systemd/system/httpd.service.
root@haproxy \~# echo "hjw" > /var/www/html/index.html
#配置sorryserver上线、
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
mode http
balance roundrobin
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 1
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1
server wuwu 192.168.0.100:8080 backup #sorryserver
root@haproxy \~# systemctl restart haproxy.service
#测试
root@Yhu \~# for i in {1..5}; do curl 172.25.254.100;done
webserver1 - 192.168.0.10
webserver2 - 192.168.0.20
webserver1 - 192.168.0.10
webserver2 - 192.168.0.20
webserver1 - 192.168.0.10
#关闭两台正常的业务主机
root@webserver1+2 \~# systemctl stop httpd
root@Yhu \~# curl 172.25.254.100
hjw
自定义错误页面
当所有主机包括sorryserver都宕机了,那么haproxy会提供一个默认访问的错误页面,这个错误页面跟报错代码有关,这个页面可以通过定义来机型设置
#出现的错误页面
root@webserver1+2 \~# systemctl stop httpd
root@haproxy \~# systemctl stop httpd
#所有后端web服务都宕机
root@Yhu \~# for i in {1..5}; do curl 172.25.254.100;done
<html><body><h1>503 Service Unavailable</h1>
No server is available to handle this request.
</body></html>
root@haproxy \~# mkdir /errorpage/html/ -p
root@haproxy \~# vim /hjw/html/503.http
HTTP/1.0 503 Service Unavailable
Cache-Control: no-cache
Connection: close
Content-Type: text/html;charset=UTF-8
<html><body><h1>什么动物生气最安静</h1>
大猩猩!!
</body></html>
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
defaults
mode http
log global
option httplog
option dontlognull
option http-server-close
option forwardfor except 127.0.0.0/8
option redispatch
retries 3
timeout http-request 10s
timeout queue 1m
timeout connect 10s
timeout client 1m
timeout server 1m
timeout http-keep-alive 10s
timeout check 10s
maxconn 3000
#errorloc 503 https://www.baidu.com
errorfile 503 /hjw/html/503.http
#error 页面
root@haproxy \~# systemctl restart haproxy.service
#测试
root@Yhu \~# curl 172.25.254.100
<html><body><h1>什么动物生气最安静</h1>
大猩猩!!
</body></html>
从定向错误到指定网站
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
defaults
mode http
log global
option httplog
option dontlognull
option http-server-close
option forwardfor except 127.0.0.0/8
option redispatch
retries 3
timeout http-request 10s
timeout queue 1m
timeout connect 10s
timeout client 1m
timeout server 1m
timeout http-keep-alive 10s
timeout check 10s
maxconn 3000
errorloc 503 https://www.baidu.com
#errorfile 503 /hjw/html/503.http
#error 页面
root@haproxy \~# systemctl restart haproxy.service

ACL
ACL-criterion****匹配规范
定义ACL匹配规范,即:判断条件
bash
hdr string,提取在一个HTTP请求报文的首部
hdr([<name> [,<occ>]]):完全匹配字符串,header的指定信息,<occ> 表示在多值中使用的值的
出现次数
hdr_beg([<name> [,<occ>]]):前缀匹配,header中指定匹配内容的begin
hdr_end([<name> [,<occ>]]):后缀匹配,header中指定匹配内容end
hdr_dom([<name> [,<occ>]]):域匹配,header中的dom(host)
hdr_dir([<name> [,<occ>]]):路径匹配,header的uri路径
hdr_len([<name> [,<occ>]]):长度匹配,header的长度匹配
hdr_reg([<name> [,<occ>]]):正则表达式匹配,自定义表达式(regex)模糊匹配
hdr_sub([<name> [,<occ>]]):子串匹配,header中的uri模糊匹配 模糊匹配c 报文中a/b/c也会
匹配
#示例:
hdr(<string>) 用于测试请求头部首部指定内容
hdr_dom(host) 请求的host名称,如 www.timinglee.org
hdr_beg(host) 请求的host开头,如 www. img. video. download. ftp.
hdr_end(host) 请求的host结尾,如 .com .net .cn
#示例:
acl bad_agent hdr_sub(User-Agent) -i curl wget
http-request deny if bad_agent
#有些功能是类似的,比如以下几个都是匹配用户请求报文中host的开头是不是www
acl short_form hdr_beg(host) www.
acl alternate1 hdr_beg(host) -m beg www.
acl alternate2 hdr_dom(host) -m beg www.
acl alternate3 hdr(host) -m beg www.
base : string
#返回第一个主机头和请求的路径部分的连接,该请求从主机名开始,并在问号之前结束,对虚拟主机有用
<scheme>://<user>:<password>@#<host>:<port>/<path>;<params>#?<query>#<frag>
base : exact string match
base_beg : prefix match
base_dir : subdir match
base_dom : domain match
base_end : suffix match
base_len : length match
base_reg : regex match
base_sub : substring match
path : string
#提取请求的URL路径,该路径从第一个斜杠开始,并在问号之前结束(无主机部分)
<scheme>://<user>:<password>@<host>:<port>#/<path>;<params>#?<query>#<frag>
path : exact string match
path_beg : prefix match #请求的URL开头,如/static、/images、/img、/css
path_end : suffix match #请求的URL中资源的结尾,如 .gif .png .css .js .jpg .jpeg
path_dom : domain match
path_dir : subdir match
path_len : length match
path_reg : regex match
path_sub : substring match
#示例:
path_beg -i /haproxy-status/
path_end .jpg .jpeg .png .gif
path_reg ^/images.*\.jpeg$
path_sub image
path_dir jpegs
path_dom timinglee
url : string
#提取请求中的整个URL。
url :exact string match
url_beg : prefix match
url_dir : subdir match
url_dom : domain match
url_end : suffix match
url_len : length match
url_reg : regex match
url_sub : substring match
dst #目标IP
dst_port #目标PORT
src #源IP
src_port #源PORT
#示例:
acl invalid_src src 10.0.0.7 192.168.1.0/24
acl invalid_src src 172.16.0.0/24
acl invalid_port src_port 0:1023
status : integer #返回在响应报文中的状态码
#七层协议
acl valid_method method GET HEAD
http-request deny if ! valid_method
ACL-flags****匹配模式
-i 不区分大小写
-m 使用指定的正则表达式匹配方法
-n 不做DNS解析
-u 禁止acl重名,否则多个同名ACL匹配或关系
ACL-operator****具体操作符
整数比较:eq、ge、gt、le、lt
字符比较:
- exact match (-m str) :字符串必须完全匹配模式
- substring match (-m sub) :在提取的字符串中查找模式,如果其中任何一个被发现,ACL将匹配
- prefix match (-m beg) :在提取的字符串首部中查找模式,如果其中任何一个被发现,ACL将匹配
- suffix match (-m end) :将模式与提取字符串的尾部进行比较,如果其中任何一个匹配,则ACL进
行匹配- subdir match (-m dir) :查看提取出来的用斜线分隔("/")的字符串,如其中任一个匹配,则
ACL进行匹配- domain match (-m dom) :查找提取的用点(".")分隔字符串,如果其中任何一个匹配,则ACL进
行匹配
ACL-value****操作对象
value的类型
The ACL engine can match these types against patterns of the following types :
- Boolean #布尔值
- integer or integer range #整数或整数范围,比如用于匹配端口范围
- IP address / network #IP地址或IP范围, 192.168.0.1 ,192.168.0.1/24
- string--> www.timinglee.org
exact #精确比较
substring #子串
suffix #后缀比较
prefix #前缀比较
subdir #路径, /wp-includes/js/jquery/jquery.js
domain #域名,www.timinglee.org- regular expression #正则表达式
- hex block #16进制
多个ACL的组合调用方式
多个ACL的逻辑处理
- 与:隐式(默认)使用
- 或:使用"or" 或 "||"表示
- 否定:使用 "!" 表示
示列:
#在访问的网址中,所有以.com 结尾的访问10,其他访问20

base参数acl
如果访问路径以 /lee 开头,转发到 webserver-80-web1
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
frontend webcluster
bind *:80
mode http
acl pathdir base_dir -i /lee
use_backend webserver-80-web1 if pathdir
default_backend webserver-80-web2 #acl列表访问不匹配
backend webserver-80-web1
server web1 192.168.0.10:80 check inter 3s fall 3 rise 5
backend webserver-80-web2
server web2 192.168.0.20:80 check inter 3s fall 3 rise 5
root@webserver1+2 \~# mkdir -p /var/www/html/lee/
root@webserver1+2 \~# mkdir -p /var/www/html/lee/test/
root@webserver1 \~# echo lee - 192.168.0.10 > /var/www/html/lee/index.html
root@webserver1 \~# echo lee/test - 192.168.0.10 > /var/www/html/lee/test/index.html
root@webserver2 \~# echo lee - 192.168.0.20 > /var/www/html/lee/index.html
root@webserver2 \~# echo lee/test - 192.168.0.20 > /var/www/html/lee/test/index.html

黑白名单
#acl禁止列表黑名单
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
frontend webcluster
bind *:80
mode http
acl test hdr_end(host) -i .com #acl列表
use_backend webserver-80-web1 if test #acl列表访问匹配
default_backend webserver-80-web2 #acl列表访问不匹配
acl invalid_src src 172.25.254.1
http-request deny if invalid_src
backend webserver-80-web1
server web1 192.168.0.10:80 check inter 3s fall 3 rise 5
backend webserver-80-web2
server web2 192.168.0.20:80 check inter 3s fall 3 rise 5
#测试:
root@celint \~#curl 172.25.254.100
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>
#禁止列表白名单
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
frontend webcluster
bind *:80
mode http
acl test hdr_end(host) -i .com #acl列表
use_backend webserver-80-web1 if test #acl列表访问匹配
default_backend webserver-80-web2 #acl列表访问不匹配
acl invalid_src src 172.25.254.1
http-request deny if ! invalid_src
backend webserver-80-web1
server web1 192.168.0.10:80 check inter 3s fall 3 rise 5
backend webserver-80-web2
server web2 192.168.0.20:80 check inter 3s fall 3 rise 5
#测试:
Administrator.DESKTOP-VJ307M3 ➤ curl 172.25.254.100
webserver2 - 192.168.0.20
root@haproxy \~# curl 172.25.254.100
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>
Haproxy全站加密
制作证书
root@haproxy \~# mkdir /etc/haproxy/certs/
root@haproxy \~# openssl req -newkey rsa:2048 -nodes -sha256 -keyout /etc/haproxy/certs/timinglee.org.key -x509 -days 365 -out /etc/haproxy/certs/timinglee.org.crt
....+....+.....+....+..++++++++++++++++++++++++++++++++++++++++++++++++......
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
Country Name (2 letter code) XX:CN
State or Province Name (full name) \[\]:HUNAN
Locality Name (eg, city) Default City:CHANGSHA
Organization Name (eg, company) Default Company Ltd:hjw
Organizational Unit Name (eg, section) \[\]:linux
Common Name (eg, your name or your server's hostname) \[\]:www.hjw.org
Email Address \[\]:hjw@163.com
root@haproxy \~# ll /etc/haproxy/certs/
总用量 8
-rw-r--r-- 1 root root 1407 2月 22 22:01 timinglee.org.crt
-rw------- 1 root root 1704 2月 22 22:00 timinglee.org.key
root@haproxy \~# cat /etc/haproxy/certs/timinglee.org.{key,crt} > /etc/haproxy/certs/timinglee.pem
root@haproxy \~# vim /etc/haproxy/haproxy.cfg
frontend webcluster-http
bind *:80
redirect scheme https if ! { ssl_fc }
listen webcluster-https
bind *:443 ssl crt /etc/haproxy/certs/timinglee.pem
mode http
balance roundrobin
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 1
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1
root@haproxy \~# systemctl restart haproxy.service
#测试:
root@celint \~# curl -v -k -L http://172.25.254.100
* Trying 172.25.254.100:80...
* Connected to 172.25.254.100 (172.25.254.100) port 80 (#0)
> GET / HTTP/1.1
> Host: 172.25.254.100
> User-Agent: curl/7.76.1
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 302 Found
< content-length: 0
< location: https://172.25.254.100/
< cache-control: no-cache
<
* Connection #0 to host 172.25.254.100 left intact
* Clear auth, redirects to port from 80 to 443Issue another request to this URL: 'https://172.25.254.100/'
* Trying 172.25.254.100:443...
* Connected to 172.25.254.100 (172.25.254.100) port 443 (#1)
* ALPN, offering h2
* ALPN, offering http/1.1
* CAfile: /etc/pki/tls/certs/ca-bundle.crt
* TLSv1.0 (OUT), TLS header, Certificate Status (22):
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS header, Certificate Status (22):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS header, Finished (20):
* TLSv1.2 (IN), TLS header, Unknown (23):
* TLSv1.3 (IN), TLS handshake, Encrypted Extensions (8):
* TLSv1.2 (IN), TLS header, Unknown (23):
* TLSv1.3 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS header, Unknown (23):
* TLSv1.3 (IN), TLS handshake, CERT verify (15):
* TLSv1.2 (IN), TLS header, Unknown (23):
* TLSv1.3 (IN), TLS handshake, Finished (20):
* TLSv1.2 (OUT), TLS header, Finished (20):
* TLSv1.3 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (OUT), TLS header, Unknown (23):
* TLSv1.3 (OUT), TLS handshake, Finished (20):
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384
* ALPN, server did not agree to a protocol
* Server certificate:
* subject: C=CN; ST=HUNAN; L=CHANGSHA; O=hjw; OU=linux; CN=www.hjw.org; emailAddress=hjw@163.com
* start date: Feb 22 14:01:08 2026 GMT
* expire date: Feb 22 14:01:08 2027 GMT
* issuer: C=CN; ST=HUNAN; L=CHANGSHA; O=hjw; OU=linux; CN=www.hjw.org; emailAddress=hjw@163.com
* SSL certificate verify result: self-signed certificate (18), continuing anyway.
* TLSv1.2 (OUT), TLS header, Unknown (23):
> GET / HTTP/1.1
> Host: 172.25.254.100
> User-Agent: curl/7.76.1
> Accept: */*
>
* TLSv1.2 (IN), TLS header, Unknown (23):
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* TLSv1.2 (IN), TLS header, Unknown (23):
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* old SSL session ID is stale, removing
* TLSv1.2 (IN), TLS header, Unknown (23):
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< date: Sun, 22 Feb 2026 14:03:00 GMT
< server: Apache/2.4.57 (Red Hat Enterprise Linux)
< last-modified: Sun, 22 Feb 2026 10:44:31 GMT
< etag: "1a-64b6756dc6bc7"
< accept-ranges: bytes
< content-length: 26
< content-type: text/html; charset=UTF-8
<
webserver2 - 192.168.0.20
* Connection #1 to host 172.25.254.100 left intact
实验效果