当前位置: 首页 > news >正文

Linux中配置haproxy

haproxy

负载均衡

负载均衡:Load Balance,简称LB,是一种服务或基于硬件设备等实现的高可用反向代理技术,负载均 衡将特定的业务(web服务、网络流量等)分担给指定的一个或多个后端特定的服务器或设备,从而提高了 公司业务的并发处理能力、保证了业务的高可用性、方便了业务后期的水平动态扩展。

在这里插入图片描述

为什么要用负载均衡?

  • Web服务器的动态水平扩展–>对用户无感知
  • 增加业务并发访问及处理能力–>解决单服务器瓶颈问题
  • 节约公网IP地址–>降低IT支出成本
  • 隐藏内部服务器IP–>提高内部服务器安全性
  • 配置简单–>固定格式的配置文件
  • 功能丰富–>支持四层和七层,支持动态下线主机
  • 性能较强–>并发数万甚至数十万

四层负载均衡

在这里插入图片描述

  1. 通过ip+port决定负载均衡的去向。

  2. 对流量请求进行NAT处理,转发至后台服务器。

  3. 记录tcp、udp流量分别是由哪台服务器处理,后续该请求连接的流量都通过该服务器处理。

  4. 支持四层的软件

    • lvs:重量级四层负载均衡器。

    • Nginx:轻量级四层负载均衡器,可缓存。(nginx四层是通过upstream模块)

    • Haproxy:模拟四层转发

七层负载均衡

在这里插入图片描述

  1. 通过虚拟url或主机ip进行流量识别,根据应用层信息进行解析,决定是否需要进行负载均衡。
  2. 代理后台服务器与客户端建立连接,如nginx可代理前后端,与前端客户端tcp连接,与后端服务器建立 tcp连接
  3. 支持7层代理的软件:
    • Nginx:基于http协议(nginx七层是通过proxy_pass)
    • Haproxy:七层代理,会话保持、标记、路径转移等。

四层和七层的区别

所谓的四到七层负载均衡,就是在对后台的服务器进行负载均衡时,依据四层的信息或七层的信息来决定怎么样转发流量。

四层的负载均衡,就是通过发布三层的IP地址(VIP),然后加四层的端口号,来决定哪些流量需要做负 载均衡,对需要处理的流量进行NAT处理,转发至后台服务器,并记录下这个TCP或者UDP的流量是由哪 台服务器处理的,后续这个连接的所有流量都同样转发到同一台服务器处理。

七层的负载均衡,就是在四层的基础上(没有四层是绝对不可能有七层的),再考虑应用层的特征,比如同一个Web服务器的负载均衡,除了根据VIP加80端口辨别是否需要处理的流量,还可根据七层的 URL、浏览器类别、语言来决定是否要进行负载均衡。

  1. 分层位置:四层负载均衡在传输层及以下,七层负载均衡在应用层及以下
  2. 性能 :四层负载均衡架构无需解析报文消息内容,在网络吞吐量与处理能力上较高:七层可支持解析应用 层报文消息内容,识别URL、Cookie、HTTP header等信息。
  3. 原理 :四层负载均衡是基于ip+port;七层是基于虚拟的URL或主机IP等。
  4. 功能类比:四层负载均衡类似于路由器;七层类似于代理服务器。
  5. 安全性:四层负载均衡无法识别DDoS攻击;七层可防御SYN Cookie/Flood攻击

haproxy的安装和服务信息

在这里插入图片描述

haproxy主机

ipv4.address172.25.254.100/24
dnf install haproxy -y			#安装haproxy
curl 172.25.254.10
curl 172.25.254.20
#检查网络是否配通vim /etc/haproxy/haproxy.cfg
#要在defaults整个模块的下面写64 #---------------------------------------------------------------------65 # custom web cluster66 #---------------------------------------------------------------------67 frontend haha68     bind        *:8069     mode        http70     balance     roundrobin71     use_backend haha72	73 backend haha74     server web1 172.25.254.10:8075     server web2 172.25.254.20:80
#注意frontend后跟的名字需要与use_backend后跟的名字一致systemctl restart haproxy.service

RS1

ipv4.address172.25.254.10
dnf install nginx -y
echo RS1 - 172.25.254.10 > /usr/share/nginx/html/index.html
#开启nginx服务
systemctl enable --now nginx.service
#关闭火墙
systemctl disable --now firewalld.service#查看nginx成功访问的日志
cat /var/log/nginx/access.log

RS2

ipv4.address172.25.254.20

同理,RS2上的配置大致与RS1上的配置一致。

所以这里不做过多赘述。

Client

测试访问
for i in {1..10}; do curl 172.25.254.100; done

option forwardfor

开启这个选项设置后,后端服务器能够获取客户端的真实 IP 地址(而不是 HAProxy 的 IP)

在haproxy主机上的haproxy的主配置文件中将option forwardfor这一选项注释掉

vim /etc/haproxy/haproxy.cfg

在这里插入图片描述

之前

在这里插入图片描述

之后

在这里插入图片描述

当我们关闭任意一台RS主机时,haproxy会自动分配给没被关的RS主机上,实现正常访问RS,而不会卡住或报错

[root@RS1 ~]# systemctl disable nginx --now[root@HaProxy ~]# for i in {1..10}; do curl 172.25.254.100; done

在这里插入图片描述

基本配置信息

HAProxy 的配置文件haproxy.cfg由两大部分组成,分别是:

global:全局配置段

  • 进程及安全配置相关的参数
  • 性能调整相关参数
  • Debug参数

proxies:代理配置段

  • defaults:为frontend, backend, listen提供默认配置
  • frontend:前端,相当于nginx中的server {}
  • backend:后端,相当于nginx中的upstream {}
  • listen:同时拥有前端和后端配置,配置简单,生产推荐使用

global配置参数说明

更改进程数量
[root@HAProxy ~]# vim /etc/haproxy/haproxy.cfgnbproc      2[root@HAProxy ~]# pstree -p | grep haproxy|-haproxy(1718)-+-haproxy(1720)|               `-haproxy(1721)
#主进程是  1718 (这是 HAProxy 的主进程,负责管理)。
#它下面有两个子进程  1720  和  1721 ,这两个就是实际处理请求的工作进程。

在这里插入图片描述

绑定进程与CPU核心
#让进程绑定CPU核心
[root@HAProxy ~]# vim /etc/haproxy/haproxy.cfgnbproc      2cpu-map		1 0cpu-map		2 1

[!TIP]

建议将进程与CPU核心绑定起来,以免进程在进行时在CPU核心之间来回切换降低效率,增加消耗。

更改为单进程多线程
#单进程多线程
[root@HAProxy ~]# vim /etc/haproxy/haproxy.cfgnbproc	 1nbthread 2
[root@HAProxy ~]# systemctl restart haproxy.service[root@HAProxy ~]# ps -T -p $(pgrep haproxy | tail -n1)
PID    SPID TTY          TIME CMD
2557   2557 ?        00:00:00 haproxy   ← 主线程
2557   2558 ?        00:00:00 haproxy   ← 工作线程
#查看目前进程数量与线程数量
#2557和2558就是两个线程

[!CAUTION]

不能直接打开多进程多线程,还是建议 nbproc 1 + nbthread N,否则haproxy启动时可能会报错,只有特殊情况才更改!

Proxies配置-defaults

defaultsmode                    http          # 默认使用 HTTP 模式(而不是 TCP 模式)log                     global        # 使用 global 段定义的日志配置option                  httplog       # 启用详细的 HTTP 请求日志格式option                  dontlognull   # 不记录没有有效数据的连接日志(减少日志噪音)option http-server-close  # 允许服务器关闭连接(节省资源)option forwardfor       except 127.0.0.0/8  # 在请求头中添加 X-Forwarded-For,除了本地地址option                  redispatch    # 如果后端服务器不可用,重新分发请求到其他可用服务器retries                 3             # 连接后端失败时重试 3 次timeout http-request    10s           # 客户端发送完整请求头的超时时间timeout queue           1m            # 请求在队列中等待的最大时间timeout connect         10s           # 与后端服务器建立连接的超时时间timeout client          1m            # 客户端连接空闲超时时间timeout server          1m            # 后端服务器响应超时时间timeout http-keep-alive 10s           # HTTP keep-alive 连接空闲超时时间timeout check           10s           # 健康检查的超时时间maxconn                 3000          # 每个进程的最大并发连接数(全局限制)errorfile 503 /etc/haproxy/errorpage/503.http  # 当返回 503 错误时,使用自定义错误页面

Proxies配置-frontend

frontend 配置参数:

bind:指定HAProxy的监听地址,可以是IPV4或IPV6,可以同时监听多个IP或端口,可同时用于listen字段中
#格式:
bind [<address>]:<port_range> [, ...] [param*]#注意:如果需要绑定在非本机的IP,需要开启内核参数:net.ipv4.ip_nonlocal_bind=1backlog <backlog> #针对所有server配置,当前端服务器的连接数达到上限后的后援队列长度,注意:不支持backend

Proxies配置-backend

  • 定义一组后端服务器,backend服务器将被frontend进行调用。
  • 注意: backend 的名称必须唯一,并且必须在listen或frontend中事先定义才可以使用,否则服务无法启动
mode http|tcp       #指定负载协议类型,和对应的frontend必须一致
option				#配置选项
server				#定义后端realserver,必须指定IP和端口

注意:option后面加 httpchk,smtpchk,mysql-check,pgsql-check,ssl-hello-chk方法,可用于实现更 多应用层检测功能。

server 配置

e.g.

[root@HAProxy ~]# vim /etc/haproxy/haproxy.cfg
listen webculsterbind        *:80mode        httpbalance     roundrobinserver web1 172.25.254.10:80 check inter 5s fall 3 weight 2server web2 172.25.254.20:80 check inter 5s fall 3 weight 1
参数/选项描述
check对指定real进行健康状态检查,如果不加此设置,默认不开启检查,只有check后面没 有其它配置也可以启用检查功能
默认对相应的后端服务器IP和端口,利用TCP连接进行周期性健康性检查,注意必须指定 端口才能实现健康性检查
addr <IP>可指定的健康状态监测IP,可以是专门的数据网段,减少业务网络的流量
port <num>指定的健康状态监测端口
inter <num>健康状态检查间隔时间,默认2000ms
fall <num>后端服务器从线上转为线下的检查的连续失效次数,默认为3
rise <num>后端服务器从下线恢复上线的检查的连续有效次数,默认为2
weight <weight_num>默认为1,最大值为256,0(状态为蓝色)表示不参与负载均衡,但仍接受持久连接
backup将后端服务器标记为备份状态,只在所有非备份主机down机时提供服务,类似Sorry Server
disabled将后端服务器标记为不可用状态,即维护状态,除了持久模式
redirect prefix url将请求临时(302)重定向至其它URL,只适用于http模式
maxconn <maxconn_num>当前后端server的最大并发连接数
sorry server

可以直接在backend底下写

backend web_backendbalance roundrobinserver web1 192.168.1.101:80 checkserver web2 192.168.1.102:80 checkserver sorry 127.0.0.1:8080 backup  # 只有当所有主服务器 down 时才会用,这就是sorry server的配置[root@HAProxy ~]# vim /etc/httpd/conf/httpd.conf
Listen 8080					#由于haproxy已经占用了80端口,所以这里更改httpd的默认端口为8080#生成我们自定义的sorry server页面显示内容
[root@HAProxy ~]# echo sorry server > /var/www/html/index.html#当我们注释掉(假设两台server都坏了)server web1 和 web2
[root@HAProxy ~]# vim /etc/haproxy/haproxy.cfg
#    server web1 172.25.254.10:80 check inter 3s fall 3
#    server web2 172.25.254.20:80 check inter 3s fall 3#当我们直接访问时,将会显示处sorry server的内容
[root@client ~]# curl 172.25.254.100
sorry server

由于haproxy已经占用了80端口,所以这里更改httpd的默认端口为8080

在这里插入图片描述

Proxies配置-listen

使用listen替换 frontend和backend的配置方式,可以简化设置,通常只用于TCP协议的应用

e.g.

[root@HAProxy ~]# vim /etc/haproxy/haproxy.cfg
listen webculsterbind        *:80mode        httpbalance     roundrobinserver web1 172.25.254.10:80 check inter 5s fall 3server web2 172.25.254.20:80 check inter 5s fall 3server web3 172.25.254.100:80 check inter 5s fall 3
[root@client ~]# for i in {1..10}; do curl 172.25.254.100; done

在这里插入图片描述

socat工具

对服务器动态权重和其它状态可以利用 socat工具进行调整,Socat 是 Linux 下的一个多功能的网络工 具,名字来由是Socket CAT,相当于netCAT的增强版.Socat 的主要特点就是在两个数据流之间建立双向 通道,且支持众多协议和链接方式。如 IP、TCP、 UDP、IPv6、Socket文件等

安装socat
[root@HAProxy ~]# dnf install socat-1.7.4.1-5.el9.x86_64 -y
查看帮助
[root@HAProxy ~]# socat -h
[root@HAProxy ~]# echo "help" | socat stdio /var/lib/haproxy/stats

在这里插入图片描述

更改配置文件
[root@HAProxy ~]# vim /etc/haproxy/haproxy.cfg39     stats socket /var/lib/haproxy/stats mode 600 level admin

在这里插入图片描述

在这里插入图片描述

查看Haproxy状态
[root@HAProxy ~]# echo "show info" | socat stdio /var/lib/haproxy/stats

在这里插入图片描述

查看集群状态
[root@HAProxy ~]# echo "show servers state" | socat stdio /var/lib/haproxy/stats

在这里插入图片描述

查看集群权重
[root@HAProxy ~]# vim /etc/haproxy/haproxy.cfgserver web1 172.25.254.10:80 weight 3 check inter 3s fall 3server web2 172.25.254.20:80 weight 1 check inter 3s fall 3
#我们分别设置了web1的权重为3,web2的权重为1[root@HAProxy ~]# systemctl restart haproxy.service
#重启服务让其重新加载配置文件[root@HAProxy ~]# echo get weight httpweb/web1 | socat stdio /var/lib/haproxy/stats
3 (initial 3)
#现在权重是3 (配置里的权重是3)
[root@HAProxy ~]# echo get weight httpweb/web2 | socat stdio /var/lib/haproxy/stats
1 (initial 1)
#现在权重是1 (配置里的权重是1)
更改集群权重
[root@HAProxy ~]# vim /etc/haproxy/haproxy.cfg
stats socket /var/lib/haproxy/stats mode 600 level admin
#这一条务必打开或存在在global配置块内[root@HAProxy ~]# systemctl restart haproxy.service
#重启服务让其重新加载配置文件[root@HAProxy ~]# echo "set weight httpweb/web2 2" | socat stdio /var/lib/haproxy/stats[root@HAProxy ~]# echo "get weight httpweb/web2" | socat stdio /var/lib/haproxy/stats
2 (initial 1)
#当前权重值为2 配置权重值为1
更改服务器设定
下线后端服务器
[root@HAProxy ~]# echo "disable server  httpweb/web1 "  | socat stdio /var/lib/haproxy/stats

在这里插入图片描述

上线后端服务器
[root@HAProxy ~]# echo "enable server  httpweb/web1 "  | socat stdio /var/lib/haproxy/stats

在这里插入图片描述

查看后端服务器信息

在这里插入图片描述

针对多进程处理方法

如果开启多进程那么我们在对进程的sock文件进行操作时其对进程的操作时随机的 如果需要指定操作进程那么需要用多soct文件方式来完成

[root@HAProxy ~]# vim /etc/haproxy/haproxy.cfg
globalnbproc      1nbthread    2cpu-map 1 0cpu-map 2 1......stats socket /var/lib/haproxy/stats1 mode 600 level admin process 1stats socket /var/lib/haproxy/stats2 mode 600 level admin process 2
#注意路径底下务必有这个文件[root@HAProxy ~]# systemctl restart haproxy

在这里插入图片描述

这样每个进程就会有单独的sock文件来进行单独管理

[root@HAProxy ~]# ll /var/lib/haproxy/
total 0
srwx------ 1 root root 0 Jul 26 01:17 stats
srw------- 1 root root 0 Jul 26 01:17 stats1
srw------- 1 root root 0 Jul 26 01:17 stats2

Haproxy算法

静态算法

static-rr
  • 不支持运行时利用socat进行权重的动态调整(只支持0和1,不支持其它值)
  • 不支持端服务器慢启动
    • 慢启动是指在服务器刚刚启动上不会把他所应该承担的访问压力全部给它,而是先给一部分,当没 问题后在给一部分
  • 其后端主机数量没有限制,相当于LVS中的 wrr
[root@HAProxy ~]# vim /etc/haproxy/haproxy.cfg80 listen webculster81     bind        *:8082     mode        http83     balance     static-rr		#静态rr轮询算法84     server web1 172.25.254.10:80 check inter 5s fall 3 weight 285     server web2 172.25.254.20:80 check inter 5s fall 3 weight 1[root@HAProxy ~]# systemctl restart haproxy.service

在这里插入图片描述

测试
/home/mobaxterm > for i in {1..10}; do curl 172.25.254.100; done

在这里插入图片描述

first
  • 根据服务器在列表中的位置,自上而下进行调度
  • 其只会当第一台服务器的连接数达到上限,新请求才会分配给下一台服务
  • 其会忽略服务器的权重设置
  • 不支持用socat进行动态修改权重,可以设置0和1,可以设置其它值但无效
[root@HAProxy ~]# vim /etc/haproxy/haproxy.cfg80 listen webculster81     bind        *:8082     mode        http83     balance     first84     server web1 172.25.254.10:80 maxconn 1 check inter 5s fall 3	#添加maxconn 1 最大连接数 效果更容易出现	#去除了权重值85     server web2 172.25.254.20:80 check inter 5s fall 3	#去除了权重值#first算法忽略权重值的设定#换句话说谁排第一谁权重值最大直到它倒下[root@HAProxy ~]# systemctl restart haproxy.service

在这里插入图片描述

测试

我们使用while死循环增加RS1的负载,直到RS1承受不了这么多的负载,调度器才会分配给RS2

/home/mobaxterm > while true
> do
> curl 172.25.254.100
> done
......

在这里插入图片描述

在这里插入图片描述

动态算法

  • 基于后端服务器状态进行调度适当调整
  • 新请求将优先调度至当前负载较低的服务器
  • 权重可以在haproxy运行时动态调整无需重启
roundrobin
概念
  1. 基于权重的轮询动态调度算法
  2. 支持权重的运行时调整,不同于lvs中的rr轮训模式
  3. HAProxy中的roundrobin支持慢启动(新加的服务器会逐渐增加转发数)
  4. 其每个后端backend中最多支持4095个real server
  5. 支持对real server权重动态调整
  6. roundrobin为默认调度算法,此算法使用广泛
[root@HAProxy ~]# vim /etc/haproxy/haproxy.cfg80 listen webculster81     bind        *:8082     mode        http83     balance     roundrobin			#更改为roundrobin动态算法84     server web1 172.25.254.10:80 check inter 5s fall 3 weight 1			#设置权重85     server web2 172.25.254.20:80 check inter 5s fall 3 weight 1			#设置权重[root@HAProxy ~]# systemctl restart haproxy.service

在这里插入图片描述

测试
 /home/mobaxterm > for i in {1..10}; do curl 172.25.254.100; done

在这里插入图片描述

[!CAUTION]

这个roundrobin算法并不是常规理解的轮询,即使你设置了两台RS服务器的权值一样,但是HAproxy会根据实际的负载量来动态调整每个RS服务器的流量分发

更改权重后,按常规rr轮询应该是两次

在这里插入图片描述

在这里插入图片描述

leastconn
  • leastconn加权的最少连接的动态
  • 支持权重的运行时调整和慢启动,即:根据当前连接最少的后端服务器而非权重进行优先调度(新客户端连接)
  • 比较适合长连接的场景使用,比如:MySQL等场景。
listen webserver_80bind 172.25.254.100:80mode httpbalance leastconnserver webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5
source

源地址hash,基于用户源地址hash并将请求转发到后端服务器,后续同一个源地址请求将被转发至同一 个后端web服务器。此方式当后端服务器数据量发生变化时,会导致很多用户的请求转发至新的后端服 务器,默认为静态方式,但是可以通过hash-type支持的选项更改这个算法一般是在不插入Cookie的TCP 模式下使用,也可给拒绝会话cookie的客户提供最好的会话粘性,适用于session会话保持但不支持 cookie和缓存的场景源地址有两种转发客户端请求到后端服务器的服务器选取计算方式,分别是取模法 和一致性hash。

[root@HAProxy ~]# vim /etc/haproxy/haproxy.cfg
listen webserverbind    172.25.254.100:80mode    httpbalance sourceserver webserver1 172.25.254.10:80 weight 1 check inter 3s fall 3 rise 5server webserver2 172.25.254.20:80 weight 1 check inter 3s fall 3 rise 5
[root@HAProxy ~]# systemctl restart haproxy.service

我们分别在ip为172.25.254.1和172.25.254.88这两个不同的源地址对172.25.254.100的haproxy服务器进行访问

在这里插入图片描述

在这里插入图片描述

我们可以看到source算法已经生效,已经对于同一源ip访问时分配给同一服务器

[!NOTE]

如果访问客户端是一个家庭,那么所有的家庭的访问流量都会被定向到一台服务器,这时source算法的缺陷,这会造成那个服务器访问压力激增。

一致性hash

一致性哈希,当服务器的总权重发生变化时,对调度结果影响是局部的,不会引起大的变动

该hash算法是动态的,支持使用socat等工具进行在线权重调整,支持慢启动。

算法:

1、后端服务器哈希环点keyA=hash(后端服务器虚拟ip)%(2^32)
2、客户机哈希环点key1=hash(client_ip)%(2^32)        得到的值在[0---4294967295]之间,
3、将keyA和key1都放在hash环上,将用户请求调度到离key1最近的keyA对应的后端服务器

在这里插入图片描述

hash环偏移问题

增加虚拟服务器IP数量,比如:一个后端服务器根据权重为1生成1000个虚拟IP,再hash。而后端服务器权重为2则生成2000的虚拟IP,再bash,最终在hash环上生成3000个节点,从而解决hash环偏斜问题

在这里插入图片描述

假如有三台服务器

那么我们假设

1000%3=1 分配给第二台服务器

1001%3=2 分配给第三台服务器

1002%3=0 分配给第一台服务器

1003%3=1 分配给第二台服务器

那么我们这时候假设我们有一台服务器挂了

1000%2=0 分配给第一台服务器

1001%2=1 分配给第二台服务器

1002%2=0 分配给第一台服务器

1003%2=1 分配给第一台服务器

那么假设我们这时候有五台服务器

1000%5=0 分配给第一台服务器

1001%5=1 分配给第二台服务器

1002%5=2 分配给第三台服务器

1003%5=3 分配给第四台服务器

而哈希环解决的是

比如1,2,3号服务器分布在一个环里按逆时针排布

然后我们客户访问的是1000,1001,1002也是逆时针分布在同一个环里

如下顺序->1000->1->1001->2->1002->3->1000

那么当1号服务器挂机后

在哈希一致性和哈希环的作用下

环内就会变成这样

->1000->2-1001->2-1002->3->1000

也就是说当1号服务器挂机后,1000请求会随着哈希环找到2号服务器,并访问2号服务器,从而得到回复。

uri

基于对用户请求的URI的左半部分或整个uri做hash,再将hash结果对总权重进行取模后根据最终结果将请求转发到后端指定服务器适用于后端是缓存服务器场景 默认是静态算法,也可以通过hash-type指定map-based和consistent,来定义使用取模法还是一致性 hash。

[!CAUTION]

注意:此算法基于应用层,所以只支持 mode http ,不支持 mode tcp

#静态
static-rr--------->tcp/http  
first------------->tcp/http  
#动态
roundrobin-------->tcp/http 
leastconn--------->tcp/http 
random------------>tcp/http#以下静态和动态取决于hash_type是否consistentsource------------>tcp/httpUri--------------->httpurl_param--------->http     hdr--------------->http

高级功能及配置

基于cookie的会话保持

cookie value:为当前server指定cookie值,实现基于cookie的会话黏性,相对于基于 source 地址hash 调度算法对客户端的粒度更精准,但同时也加大了haproxy负载,目前此模式使用较少, 已经被session 共享服务器代替

[!CAUTION]

注意:不支持 tcp mode,使用 http mode

在这里插入图片描述

当我们使用浏览器访问时,我们可以查询到cookie

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

指定cookie值访问

在这里插入图片描述

haproxy的状态界面

通过web界面,显示当前HAProxy的运行状态

状态页配置项
[root@HAProxy ~]# vim /etc/haproxy/haproxy.cfg
listen statusmode        httpbind        *:9999stats       enablelog         globalstats       uri /statusstats       auth vb:vb
#打开状态页时需要用户验证

我们关停RS2上的nginx,模拟服务器坏了

[root@RS2 ~]# systemctl stop nginx.service

在这里插入图片描述

在这里插入图片描述

这样我们自己手动刷新很麻烦

所以我们可以设置自动刷新

自动刷新
[root@HAProxy ~]# vim /etc/haproxy/haproxy.cfg
listen status......stats       refresh 1

再次打开状态页,可以发现网页每隔1秒自动刷新

在这里插入图片描述

在这里插入图片描述

[root@RS2 ~]# systemctl start nginx.service

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

IP透传

七层中
[root@HAProxy ~]# vim /etc/haproxy/haproxy.cfg

在这里插入图片描述

目前运行在七层,可以看到option forwardfor是打开的,所以会自动采集IP透传信息

/home/mobaxterm  for i in {1..10}; do curl 172.25.254.100; done
RS1 - 172.25.254.10
RS1 - 172.25.254.10
RS2 - 172.25.254.20
RS2 - 172.25.254.20
RS2 - 172.25.254.20
RS1 - 172.25.254.10
RS2 - 172.25.254.20
RS2 - 172.25.254.20
RS1 - 172.25.254.10
RS2 - 172.25.254.20[root@RS1 ~]# cat /var/log/nginx/access.log
172.25.254.100 - - [20/Jul/2025:09:37:19 +0800] "GET / HTTP/1.1" 200 20 "-" "curl/7.65.0" "172.25.254.1"
172.25.254.100 - - [20/Jul/2025:09:37:19 +0800] "GET / HTTP/1.1" 200 20 "-" "curl/7.65.0" "172.25.254.1"
172.25.254.100 - - [20/Jul/2025:09:50:21 +0800] "GET / HTTP/1.1" 200 20 "-" "curl/7.65.0" "172.25.254.1"
172.25.254.100 - - [20/Jul/2025:09:50:21 +0800] "GET / HTTP/1.1" 200 20 "-" "curl/7.65.0" "172.25.254.1"
172.25.254.100 - - [20/Jul/2025:09:50:21 +0800] "GET / HTTP/1.1" 200 20 "-" "curl/7.65.0" "172.25.254.1"
172.25.254.100 - - [20/Jul/2025:09:50:21 +0800] "GET / HTTP/1.1" 200 20 "-" "curl/7.65.0" "172.25.254.1"

在这里插入图片描述

当我们关闭option forwardfor后,再次访问测试

[root@HAProxy ~]# vim /etc/haproxy/haproxy.cfg51 defaults57     #option forwardfor       except 127.0.0.0/8
[root@HAProxy ~]# systemctl restart haproxy.service

在这里插入图片描述

在这里插入图片描述

不难发现,IP透传功能关闭了

四层中

在这里插入图片描述

在这里插入图片描述

[root@RS1 ~]# vim /etc/nginx/nginx.conf
server {listen       80 proxy_protocol;				#在原来的只有80的后面加上proxy_protocollisten       [::]: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 {}error_page 500 502 503 504 /50x.html;location = /50x.html {}
#启用proxy_protocol此项,将无法直接访问此网站,只能通过四层代理
#在客户主机上进行模拟测试
[root@client ~]# for i in {1..10}; do curl 172.25.254.100; done
<html><body><h1>502 Bad Gateway</h1>
The server returned an invalid or incomplete response.
</body></html>
<html><body><h1>502 Bad Gateway</h1>
The server returned an invalid or incomplete response.
</body></html>
RS2 - 172.25.254.20
<html><body><h1>502 Bad Gateway</h1>
The server returned an invalid or incomplete response.
</body></html>
<html><body><h1>502 Bad Gateway</h1>
The server returned an invalid or incomplete response.
</body></html>
<html><body><h1>502 Bad Gateway</h1>
The server returned an invalid or incomplete response.
</body></html>
RS2 - 172.25.254.20
<html><body><h1>502 Bad Gateway</h1>
The server returned an invalid or incomplete response.
</body></html>
<html><body><h1>502 Bad Gateway</h1>
The server returned an invalid or incomplete response.
</body></html>
<html><body><h1>502 Bad Gateway</h1>
The server returned an invalid or incomplete response.
</body></html>
#可以看出RS1已经能正常访问了

在这里插入图片描述

在这里插入图片描述

ACL

访问控制列表ACL,Access Control Lists)是一种基于包过滤的访问控制技术

它可以根据设定的条件对经过服务器传输的数据包进行过滤(条件匹配)即对接收到的报文进行匹配和过滤,基于请求报文头部中的源地址、源端口、目标地址、目标端口、请求方法、URL、文件后缀等信息内 容进行匹配并执行进一步操作,比如允许其通过或丢弃。

ACL配置选项

在这里插入图片描述

1匹配域名
[root@HAProxy ~]# vim /etc/haproxy/haproxy.cfg72 frontend hahahehe73     bind        *:8074     mode        http75     balance     roundrobin7677     acl test hdr_dom(host) -i www.vb.com		#请求的host名称7879     #http-request8081     use_backend haha if test82     default_backend hehe8384 backend haha85     server web1 172.25.254.10:8086 backend hehe87     server web2 172.25.254.20:80
[root@HAProxy ~]# systemctl restart haproxy.service

在这里插入图片描述

在这里插入图片描述

2匹配URL是否含某个元素

匹配请求的URL中资源的结尾

在这里插入图片描述

[root@RS1 ~]# mkdir -p /usr/share/nginx/html/
404.html                 a/                       index.html               poweredby.png
50x.html                 icons/                   nginx-logo.png           system_noindex_logo.png
[root@RS1 ~]# mkdir -p /usr/share/nginx/html/ab/
[root@RS1 ~]# echo ab > /usr/share/nginx/html/ab/index.html[root@client ~]# curl  172.25.254.100/ab/
ab
[root@client ~]# curl  172.25.254.100/a/
RS1 - 172.25.254.10 - a
请求路径是否匹配 test转发后端
/a✅ 是haha
/api✅ 是(包含 /ahaha
/b❌ 否hehe
/abc✅ 是(包含 /ahaha
3.禁止使用wget(方法)

定义一个 ACL,判断 User-Agent 中是否包含 wget

[root@HAProxy ~]# vim /etc/haproxy/haproxy.cfg	acl badagent hdr_sub(User-Agent) -i wgethttp-request deny if badagent[root@HAProxy ~]# systemctl restart haproxy.service[root@HAProxy ~]# wget 172.25.254.100
--2025-07-27 01:20:45--  http://172.25.254.100/
Connecting to 172.25.254.100:80... connected.
HTTP request sent, awaiting response... 403 Forbidden
2025-07-27 01:20:45 ERROR 403: Forbidden.

在这里插入图片描述

4拒绝指定ip

拒绝指定ip

#用111访问就会被拒绝
[root@client ~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00inet 127.0.0.1/8 scope host lovalid_lft forever preferred_lft foreverinet6 ::1/128 scope hostvalid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000link/ether 00:0c:29:62:a5:25 brd ff:ff:ff:ff:ff:ffaltname enp3s0altname ens160inet 172.25.254.111/24 brd 172.25.254.255 scope global noprefixroute eth0valid_lft forever preferred_lft foreverinet6 fe80::3974:552:50e6:b2f1/64 scope link noprefixroutevalid_lft forever preferred_lft forever
[root@client ~]# curl 172.25.254.100
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>

在这里插入图片描述

拒绝多人

!src

5匹配浏览器类型
haproxy ~]# vim /etc/haproxy/haproxy.cfg...上面内容省略...frontend testaclbind :80mode http###########     
ACL settings    
#######################acl user_agent_block hdr_sub(User-Agent) -i curl wgetacl user_agent_redirect hdr_sub(User-Agent) -i Mozilla/5.0###########     
###########     
host        
###########################http-request deny if user_agent_blockredirect prefix https://www.baidu.com if user_agent_redirectdefault server      
default_backend default_webserver###################backend ip_test-host
mode httpserver web1 192.168.0.101:80 check weight 1 inter 3s fall 3 rise 5backend default_webservermode httpserver web1 172.25.254.10:80 check weight 1 inter 3s fall 3 rise 5

测试:

1[root@node10 ~]# curl 172.25.254.100<html><body><h1>403 Forbidden</h1>Request forbidden by administrative rules.</body></html>2.[root@node10 ~]# wget http://172.25.254.100/index.html--2024-07-11 23:04:36--  http://172.25.254.100/index.htmlConnecting to 172.25.254.100:80... connected.HTTP request sent, awaiting response... 403 Forbidden2024-07-11 23:04:36 ERROR 403: Forbidden.3.浏览器中测试
6.基于文件后缀名实现动静分离
haproxy ~]# vim /etc/haproxy/haproxy.cfg...上面内容省略...frontend testaclbind :80mode http###########     
ACL settings    
#######################acl url_static  path_end -i .jpg .png .css .js .htmlacl url_php     
path_end -i .php###########     
host        
###########################use_backend static_host if url_staticuse_backend php_host if url_php###########     
default server      
default_backend default_webserver###################backend static_hostmode httpserver web2 192.168.0.101:80 check weight 1 inter 3s fall 3 rise 5backend php_hostmode httpserver web1 192.168.0.102:80 check weight 1 inter 3s fall 3 rise 5
backend default_webservermode httpserver web1 172.25.254.10:80 check weight 1 inter 3s fall 3 rise 5

测试:

[root@rs1 ~]# echo css 192.168.0.101 >  /usr/share/nginx/html/index.css[root@rs2 ~]# echo php 192.168.0.102  > /var/www/html/index.php[root@node10 ~]# curl 172.25.254.100/index.phpphp 192.168.0.102[root@node10 ~]# curl 172.25.254.100/index.csscss 192.168.0.101
自定义错误页面

对指定的报错进行重定向,进行优雅的显示错误页面 使用errorfile和errorloc指令的两种方法,可以实现自定义各种错误页面

#haproxy默认使用的错误错误页面
[root@haproxy ~]# rpm -ql  haproxy24z-2.4.27-1.el7.zenetys.x86_64 | grep -E http$/usr/share/haproxy/400.http/usr/share/haproxy/403.http/usr/share/haproxy/408.http/usr/share/haproxy/500.http/usr/share/haproxy/502.http/usr/share/haproxy/503.http/usr/share/haproxy/504.http
#自定义错误页
errorfile <code> <file> 
<code> #HTTP status code.支持200, 400, 403, 405, 408, 425, 429, 500, 502,503,504<file> #包含完整HTTP响应头的错误页文件的绝对路径。 建议后缀".http",以和一般的html文件相区分
#示例:
errorfile 503 /haproxy/errorpages/503page.http
haproxy ~]# vim /etc/haproxy/haproxy.cfg...上面内容省略...defaults
测试:5.5.2 基于http重定向错误页面 
范例:mode                    http...内容省略...timeout client          1mtimeout server          1mtimeout http-keep-alive 10stimeout check           10smaxconn                 1000000errorfile 503 /haproxy/errorpages/503page.http[root@haproxy ~]# mkdir /haproxy/errorpages/ -p[root@haproxy ~]# cp /usr/share/haproxy/503.http /haproxy/errorpages/503page.http[root@haproxy ~]# vim /haproxy/errorpages/503page.httpHTTP/1.0 503 Service UnavailableCache-Control: no-cacheConnection: closeContent-Type: text/html;charset=UTF-8^M<html><body><h1>什么动物生气最安静</h1>
大猩猩!!
</body></html>

测试

关闭后端的RS主机
然后用浏览器去访问172.25.254.100
HAProxy 四层负载

我们选择mysql作为测试对象

四层负载示例

注意:如果使用frontend和backend,一定在 frontend 和 backend 段中都指定mode tcp

listen mysql-portbind 10.0.0.7:6379mode tcpbalance leastconnserver server1 10.0.0.17:3306 checkserver server2 10.0.0.27:3306 check backup
对 MySQL 服务实现四层负载
haproxy ~]# vim /etc/haproxy/haproxy.cfg...上面内容省略...listen mysql_portbind :3306mode tcpbalance leastconnserver mysql1 192.168.0.101:3306 checkserver mysql2 192.168.0.102:3306 check#或者使用frontend和backend实现
haproxy ~]# vim /etc/haproxy/haproxy.cfg...上面内容省略...frontend mysql_portbind :3306mode tcpuse_backend mysql_rs
backend mysql_rsmode tcpbalance leastconnserver mysql1 192.168.0.101:3306 checkserver mysql2 192.168.0.102:3306 checkhaproxy ~]# systemctl restart haproxy.service#在后端服务器安装和配置mariadb服务
rs1 ~]# yum install mariadb-server  -yrs2 ~]# yum install mariadb-server  -yrs1 ~]# vim /etc/my.cnf[mysqld]server-id=1 #在另一台主机为
rs2 ~]# vim /etc/my.cnf[mysqld]server-id=2 #在另一台主机为rs1 ~]# systemctl start mariadbrs2 ~]# systemctl start mariadbrs1 ~]# mysql -e "grant all on *.* to vb@'%' identified by 'vb';"rs2 ~]# mysql -e "grant all on *.* to vb@'%' identified by 'vb';"#测试
[root@node10 ~]# mysql -uvb -pvb   -h 172.25.254.100 -e "show variables like 
'hostname'"+---------------+-------+| Variable_name | Value |+---------------+-------+| hostname      | rs2   |+---------------+-------+[root@node10 ~]# mysql -uvb -pvb   -h 172.25.254.100 -e "show variables like 
'hostname'"+---------------+-------+| Variable_name | Value |+---------------+-------+| hostname      | rs1   |+---------------+-------+[root@node10 ~]# mysql -uvb -pvb   -h172.25.254.100 -e "select @@server_id"+-------------+| @@server_id |+-------------+|           1 |+-------------+[root@node10 ~]# mysql -uvb -pvb   -h172.25.254.100 -e "select @@server_id"+-------------+| @@server_id |+-------------+|           2 |+-------------+
HAProxy https 实现

haproxy可以实现https的证书安全,从用户到haproxy为https,从haproxy到后端服务器用http通信 但基于性能考虑,生产中证书都是在后端服务器比如nginx上实现

#配置HAProxy支持https协议,支持ssl会话;
bind *:443 ssl crt /PATH/TO/SOME_PEM_FILE 
#指令 crt 后证书文件为PEM格式,需要同时包含证书和所有私钥
cat demo.key demo.crt > demo.pem 
#把80端口的请求重向定443bind *:80redirect scheme https if !{ ssl_fc } 
[root@HAProxy ~]# openssl req -newkey rsa:2048 -nodes -sha256 -keyout /etc/haproxy/certs/vb.com.key -x509 -days 365 -out /etc/haproxy/certs/vb.com.crt
https配置示例
haproxy ~]#  vim /etc/haproxy/haproxy.cfgfrontend webserverbind *:80redirect scheme https if !{ ssl_fc }mode httpuse_backend webclusterfrontend webserver-httpsbind *:443 ssl  crt  /etc/haproxy/vb.org.pemmode httpuse_backend webclusterbackend  webclustermode httpbalance roundrobinserver web1 172.25.254.200:80 check inter 3s fall 3 rise 5server web2 172.25.254.201:80 check inter 3s fall 3 rise 5
 [root@client ~]#curl -IkL http://172.25.254.100HTTP/1.1 302 Foundcontent-length: 0
location: https://www.vb.org/cache-control: no-cacheHTTP/1.1 200 OKdate: Sat, 04 Apr 2020 02:31:31 GMTserver: Apache/2.4.6 (CentOS) PHP/5.4.16last-modified: Thu, 02 Apr 2020 01:44:13 GMTetag: "a-5a244f01f8adc"accept-ranges: bytescontent-length: 10content-type: text/html; charset=UTF-8[root@centos6 ~]#curl -Ik https://www.vb.orgHTTP/1.1 200 OKdate: Sat, 04 Apr 2020 02:31:50 GMTserver: Apache/2.4.6 (CentOS) PHP/5.4.16last-modified: Thu, 02 Apr 2020 01:44:28 GMTetag: "a-5a244f0fd5175"accept-ranges: bytescontent-length: 10content-type: text/html; charset=UTF-8

sl crt /PATH/TO/SOME_PEM_FILE
#指令 crt 后证书文件为PEM格式,需要同时包含证书和所有私钥
cat demo.key demo.crt > demo.pem
#把80端口的请求重向定443
bind *:80
redirect scheme https if !{ ssl_fc }

[root@HAProxy ~]# openssl req -newkey rsa:2048 -nodes -sha256 -keyout /etc/haproxy/certs/vb.com.key -x509 -days 365 -out /etc/haproxy/certs/vb.com.crt


##### https配置示例

haproxy ~]# vim /etc/haproxy/haproxy.cfg
frontend webserver
bind *:80
redirect scheme https if !{ ssl_fc }
mode http
use_backend webcluster
frontend webserver-https
bind *:443 ssl crt /etc/haproxy/vb.org.pem
mode http
use_backend webcluster
backend webcluster
mode http
balance roundrobin
server web1 172.25.254.200:80 check inter 3s fall 3 rise 5
server web2 172.25.254.201:80 check inter 3s fall 3 rise 5

```bash[root@client ~]#curl -IkL http://172.25.254.100HTTP/1.1 302 Foundcontent-length: 0
location: https://www.vb.org/cache-control: no-cacheHTTP/1.1 200 OKdate: Sat, 04 Apr 2020 02:31:31 GMTserver: Apache/2.4.6 (CentOS) PHP/5.4.16last-modified: Thu, 02 Apr 2020 01:44:13 GMTetag: "a-5a244f01f8adc"accept-ranges: bytescontent-length: 10content-type: text/html; charset=UTF-8[root@centos6 ~]#curl -Ik https://www.vb.orgHTTP/1.1 200 OKdate: Sat, 04 Apr 2020 02:31:50 GMTserver: Apache/2.4.6 (CentOS) PHP/5.4.16last-modified: Thu, 02 Apr 2020 01:44:28 GMTetag: "a-5a244f0fd5175"accept-ranges: bytescontent-length: 10content-type: text/html; charset=UTF-8
http://www.dtcms.com/a/303340.html

相关文章:

  • Java 笔记 serialVersionUID
  • 50etf的实值期权和虚值期权谁涨得快?
  • gdb调试教程
  • 图像轮廓与凸包
  • 网络编程接口htonl学习
  • 如何进行DAP-seq的数据挖掘,筛选验证位点
  • Baumer工业相机堡盟工业相机如何通过YoloV8深度学习模型实现面部口罩的检测识别(C#代码,UI界面版)
  • C++-关于协程的一些思考
  • json取值,如果字段不存在,匹配下一个字段
  • 自定义View学习记录 plinko游戏View
  • 恒坤新材IPO被暂缓审议:收入确认法遭质疑,募资缩水约2亿元
  • 元宇宙经济与数字经济的异同:虚实交织下的经济范式对比
  • 基于Springboot的宠物救助管理系统的设计与实现
  • 【VUE3】搭建项目准备工作
  • 艾格文服装软件怎么用?
  • Windows中查看GPU和Cuda信息的DOS命令总结
  • AI产品经理手册(Ch1-2)AI Product Manager‘s Handbook学习笔记
  • uvm sequence Arbitration
  • AI 驱动、设施扩展、验证器强化、上线 EVM 测试网,Injective 近期动态全更新!
  • git stash apply 冲突合并方法解决
  • 希尔排序(缩小增量排序)面试专题解析
  • unisS5800XP-G交换机配置命令之登录篇
  • 洛谷 P10448 组合型枚举-普及-
  • Visual Studio Code使用
  • 25世界职业院校技能大赛国内赛区承办名单确定,各赛区需全力筹备
  • 【Spring Boot 快速入门】二、请求与响应
  • CGA围手术期:全周期保障老年手术安全
  • 基于深度学习的医学图像分析:使用YOLOv5实现细胞检测
  • TI 2025全国电赛猜题
  • 刘润探展科大讯飞WAIC,讯飞医疗AI该咋看?