全网最详细解读haproxy七层代理

一.负载均衡

1.1.什么是负载均衡

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

1.2.为什么用负载均衡

  • Web服务器的动态水平扩展-->对用户无感知

  • 增加业务并发访问及处理能力-->解决单服务器瓶颈问题

  • 节约公网IP地址-->降低IT支出成本

  • 隐藏内部服务器IP-->提高内部服务器安全性

  • 配置简单-->固定格式的配置文件

  • 功能丰富-->支持四层和七层,支持动态下线主机

  • 性能较强-->并发数万甚至数十万

1.3.负载均衡类型

1.3.1硬件:

F5                    美国F5网络公司             https://f5.com/zh
Netscaler        美国思杰公司                https://www,citrix.com.cn/products/citrix-adc/
Array                    华耀                           https://www.arraynetworks.com.cn/
AD-1000            深信服                         http://www.sangfor.com.cn/

1.3.2.四层负载均衡

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

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

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

4.支持四层的软件 lvs:重量级四层负载均衡器。 Nginx:轻量级四层负载均衡器,可缓存。(nginx四层是通过upstream模块) Haproxy:模拟四层转发

1.3.4 四层和七层的区别

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

四层的负载均衡,就是通过发布三层的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是法国开发者 威利塔罗(Willy Tarreau) 在2000年使用C语言开发的一个开源软件是一款具备高并发(万级以上)、高性能的TCP和HTTP负载均衡器支持基于cookie的持久性,自动故障切换,支持正则表达式及web状态统计

企业版网站:https://www.haproxy.com
社区版网站:http://www,haproxy.org
github:https://github.com/haprox
企业版本和社区版功能对比

三.haproxy的安装和服务信息

3.1实验环境

准备工作

主机名IP地址角色
haproxy  172.25.254.100/24客户端  
webserver1172.25.254.10/24web1服务器(RS1)
webserver2172.25.254.20/24web2服务器(RS2)
3.1.1proxies参数说明proxies
参数类型作用
defaults[]proxies默认配置项,针对以下的frontend、backend和listen生效,可以多个name也可以没有name
frontendproxies前端servername,类似于Nginx的一个虚拟主机 server和LVS服务集群。
backendproxies#后端服务器组,等于nginx的upstream和LVS中的RS服务器
listenproxies#将frontend和backend合并在一起配置,相对于frontend和backend配置更简洁,生产常用
3.1.1.1frontend 配置参数:

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

3.2软件安装

3.2.1软件包下载地址

https://github.com/haproxy/wiki/wiki/Packages

3.2.2安装软件包

[root@haproxy ~]# dnf install haproxy -y

两台服务器都需安装nginx

[root@webserver1 ~]# dnf install nginx -y ​

[root@webserver2 ~]# dnf install nginx -y

安装完nginx后都可以写入一部分内容然后用客户机去访问

[root@webserver1 ~]# echo webserver1 - 172.25.254.10 > /usr/share/nginx/html/index.html [root@webserver1 ~]# systemctl enable --now nginx ​ [

root@webserver2 ~]# echo webserver1 - 172.25.254.20 > /usr/share/nginx/html/index.html [root@webserver2 ~]# systemctl enable --now nginx

3.2.3在haproxy上检测环境是否配置成功

3.2.4安装完成后就可以查看一下配置文件

3.2.5编辑frontend配置文件第一种配置

frontend webcluster
    bind*:80
    mode http
    use_backend webcluster-host
backend webcluster-host
    balance roundrobin
    server web1 172.25.254.10:80
    server web2 172.25.254.20:80    

3.2.6测试

如果暂停其中一台服务器的话那么在访问的时候就只会访问到另一台服务器 做完测试之后一定记得吧把暂停的服务器重新起起来 第二种配置和测试结果

两种配置的显示结果没有区别

3.3全局配置

3.3.1多线程

添加两个进程,并不是越多越好,最好是cpu几核开几个,但是有可能会出现cpu漂移,避免出现漂移可以用cpu-map使其只用一个 查看子进程

3.3.2设定多线程

如果多线程和多进程同时开启使用就会报错,所以我们需要将多进程删除或者注释掉

3.3.3自定义日志

定义日志前得先打开udp端口

vim /etc/rsyslog.conf

定向haproxy日志的位置

3.3.4 Proxies配置-defaults

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>%{X-Forwarded-For}i
#后在webserer中看日志即可看到地址透传信息
option redispatch #当server Id对应的服务器挂掉后,强制定向到其他健康的服务器,重新派发
option http-keep-alive #开启与客户端的会话保持
retries 3 #连接后端服务器失败次数
timeout http-request 1000s #等待客户端请求完全被接收和处理的最长时间
timeout queue 60s #设置删除连接和客户端收到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

3.4server 配置

针对一个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的最大并发连接数

3.4.1常用配置参数

listen webcluster
        bind *:80
        mode http
        balance roundrobin
        server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
        server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1

3.4.2backup

在haproxy上做
Listen 8080                ----       backup--sorry server端口

测试一下8080端口可不可以用 两台服务器都不能用的情况下才会显示”sorry 下班了“,如果有一台服务器可以用那么都不会显示”sorry 下班了“,因为只要有一台服务器能正常使用的话8080端口就不会出现在正常轮询过程中。

3.4.3disabled

如果现在服务器需要维护了,那么有一台是不能让其访问,只能访问一台

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 

server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2 disabled

[root@haproxy ~]# systemctl restart haproxy.service

访问时就只会显示一台服务器的内容 上线时只需将disabled删除就行了

3.4.4redirect

redirect prefix http://www.baidu.com/  此网页重定向你在网页上访问172.25.254.100将会跳转到百度网站

直接搜索www.baidu.com出现的是官网是安全并且有证书的,而通过172.25.254.100显示的不安全且没有证书的

3.4.5maxconn

```
maxconn <maxconn> #当前后端server的最大并发连接数
```

server web1 172.25.254.10:80 maxconn 2  check inter 2 fall 3 rise 5 weight 2         #在企业中是不允许这样改的

如果你只在webserver1上测试的话是不会出现迸发链接超过的情况,因为都是一次一次过去的,如果在两台服务器上同时运行上述代码是有可能会出现错误的。

while true; do curl 172.25.254.100; sleep 0.1; done

想要优化的话就改其值,将其改大

3.5socat工具

3.5.1安装软件包

dnf install socat -y               -------这个工具作用是动态调整haproxy中的参数

安装完成后可以查看它的用法

[root@haproxy ~]# echo "help" | socat stdio /var/lib/haproxy/stats 

 vim    /etc/haproxy/haproxy.cfg
 stats socket /var/lib/haproxy/stats mode 600 level admin        #修改配置文件

每次编辑完文件都要记得重启,查看一下套接字文件的权限

[root@haproxy ~]# systemctl restart haproxy.service 
[root@haproxy ~]# ll /var/lib/haproxy/stats 

3.5.2常用示例
3.5.3查看haproxy状态

[root@haproxy ~]# echo "show info" | socat stdio /var/lib/haproxy/stats 
Name: HAProxy
Version: 2.4.7-b5e51a5
Release_date: 2021/10/04
Nbthread: 2
Nbproc: 1                             --#单进程
Process_num: 1
Pid: 3564
Uptime: 0d 0h12m07s
Uptime_sec: 727
Memmax_MB: 0
PoolAlloc_MB: 0
PoolUsed_MB: 0
PoolFailed: 0
Ulimit-n: 8037
Maxsock: 8037
Maxconn: 4000
Hard_maxconn: 4000
CurrConns: 0
CumConns: 391070
CumReq: 2
MaxSslConns: 0
CurrSslConns: 0
CumSslConns: 0
Maxpipes: 0

3.5.4查看server集群状态

[root@haproxy ~]# echo "show servers state" | socat stdio /var/lib/haproxy/stats

1

# be_id be_name srv_id srv_name srv_addr srv_op_state srv_admin_state srv_uweight srv_iweight srv_time_since_last_change srv_check_status srv_check_result srv_check_health srv_check_state srv_agent_state bk_f_forced_id srv_f_forced_id srv_fqdn srv_port srvrecord srv_use_ssl srv_check_port srv_check_addr srv_agent_addr srv_agent_port

2 webcluster 1 web1 172.25.254.10 2 0 2 2 886 6 3 7 6 0 0 0 - 80 - 0 0 - - 0
2 webcluster 2 web2 172.25.254.20 2 0 1 1 131 6 3 7 6 0 0 0 - 80 - 0 0 - - 0
2 webcluster 3 web_sorry 172.25.254.20 2 0 1 1 886 1 0 2 0 0 0 0 - 8080 - 0 0 - - 0
4 static 1 static 127.0.0.1 0 0 1 1 885 8 2 0 6 0 0 0 - 4331 - 0 0 - - 0
5 app 1 app1 127.0.0.1 0 0 1 1 885 8 2 0 6 0 0 0 - 5001 - 0 0 - - 0
5 app 2 app2 127.0.0.1 0 0 1 1 885 8 2 0 6 0 0 0 - 5002 - 0 0 - - 0
5 app 3 app3 127.0.0.1 0 0 1 1 884 8 2 0 6 0 0 0 - 5003 - 0 0 - - 0
5 app 4 app4 127.0.0.1 0 0 1 1 884 8 2 0 6 0 0 0 - 5004 - 0 0 - - 0

3.5.5查看集群权重

[root@haproxy ~]# echo get weight webcluster/web1 | socat stdio /var/lib/haproxy/stats
2 (initial 2)

[root@haproxy ~]# echo "set weight webcluster/web1 1" | socat stdio /var/lib/haproxy/stats

[root@haproxy ~]# echo get weight webcluster/web1 | socat stdio /var/lib/haproxy/stats
1 (initial 2)

下线一台服务器web1

[root@haproxy ~]# echo "disable server webcluster/web1" | socat stdio /var/lib/haproxy/stats

[root@haproxy ~]# echo "enable server webcluster/web1" | socat stdio /var/lib/haproxy/stats   #重新起起来

3.5.5针对多进程处理方法

#多进程如何热处理
# turn on stats unix socket

stats socket /var/lib/haproxy/stats1 mode 600 level admin process 1
stats socket /var/lib/haproxy/stats2 mode 600 level admin process 2

# utilize system-wide crypto-policies

ssl-default-bind-ciphers PROFILE=SYSTEM
ssl-default-server-ciphers PROFILE=SYSTEM
nbproc 2
cpu-map 1 0
cpu-map 2 1

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg                                 #编辑上述配置文件
[root@haproxy ~]# systemctl restart haproxy.service                         #重启服务
[root@haproxy ~]# ll /var/lib/haproxy/                                        #查看重启以后的状态
total 0
srw------- 1 root root 0 Aug 10 23:46 stats
srw------- 1 root root 0 Aug 11 00:28 stats1
srw------- 1 root root 0 Aug 11 00:28 stats2
[root@haproxy ~]# 

stats已经没用但是系统并没有删除

[root@haproxy ~]# echo "show info" | socat stdio /var/lib/haproxy/stats 
2024/08/11 00:31:40 socat[3854] E connect(5, AF=1 "/var/lib/haproxy/stats", 24): Connection refused

四.haproxy的算法

HAProxy通过固定参数 balance 指明对后端服务器的调度算法 balance参数可以配置在listen或backend选项中。 HAProxy的调度算法分为静态和动态调度算法 有些算法可以根据参数在静态和动态算法中相互转换。

4.1 静态算法

静态算法:按照事先定义好的规则轮询公平调度,不关心后端服务器的当前负载、连接数和响应速度 等,且无法实时修改权重(只能为0和1,不支持其它值),只能靠重启HAProxy生效。

4.1.1 static-rr:基于权重的轮询调度

不支持运行时利用socat进行权重的动态调整(只支持0和1,不支持其它值) 不支持端服务器慢启动 其后端主机数量没有限制,相当于LVS中的 wrr

示例:

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
listen webcluster
        bind *:80
        mode http
        balance static-rr
        #balance roundrobin
        #redirect prefix http://www.baidu.com/
        server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
        server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1
        #server web_sorry 172.25.254.20:8080 backup

测试一下能不能通,为了方便演示看结果需要关掉多进程

 # turn on stats unix socket

stats socket /var/lib/haproxy/stats mode 600 level admin 
#stats socket /var/lib/haproxy/stats2 mode 600 level admin process 2

# utilize system-wide crypto-policies

ssl-default-bind-ciphers PROFILE=SYSTEM
ssl-default-server-ciphers PROFILE=SYSTEM
#nbproc 2
#cpu-map 1 0
#cpu-map 2 1

[root@haproxy ~]# for i in {1..10}
> do
> curl 172.25.254.100
> done

正常情况来说static-rr是不可以在外面直接用socat直接更改权重

[root@haproxy ~]# echo "set weight webcluster/web1 1 " | socat stdio /var/lib/haproxy/stats 
2024/08/11 08:13:56 socat[4163] E connect(5, AF=1 "/var/lib/haproxy/stats", 24): Connection refused

4.1.2first

根据服务器在列表中的位置,自上而下进行调度

其只会当第一台服务器的连接数达到上限,新请求才会分配给下一台服务

其会忽略服务器的权重设置

不支持用socat进行动态修改权重,可以设置0和1,可以设置其它值但无效

示例:

listen webcluster
        bind *:80
        mode http
        balance first
        #balance static-rr
        #balance roundrobin
        #redirect prefix http://www.baidu.com/
        server web1 172.25.254.10:80 maxconn 1 check inter 2 fall 3 rise 5 weight 2    #为了演示效果把最大连接数改为1,在企业中是不允许这么做的
        server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1
        #server web_sorry 172.25.254.20:8080 backup

在多台主机中执行死循环测试效果

[root@webserver1 ~]# while true; do curl 172.25.254.100; sleep 0.1; done

[root@webserver2 ~]# while true;  do curl 172.25.254.100;  sleep 0.1;  done

测试完成后一定记得把添加的最大连接数maxconn 1删除掉不然会影响到后续实验效果

4.2 动态算法

动态算法

基于后端服务器状态进行调度适当调整,

新请求将优先调度至当前负载较低的服务器

权重可以在haproxy运行时动态调整无需重启

4.2.1 roundrobin
  1. 基于权重的轮询动态调度算法,

  2. 支持权重的运行时调整,不同于lvs中的rr轮训模式,

  3. HAProxy中的roundrobin支持慢启动(新加的服务器会逐渐增加转发数),

  4. 其每个后端backend中最多支持4095个real server,

  5. 支持对real server权重动态调整,

  6. roundrobin为默认调度算法,此算法使用广泛

示例:

#动态权重调整
[root@haproxy ~]# echo "set weight webcluster/web1 1 " | socat stdio /var/lib/haproxy/stats 

[root@haproxy ~]# echo "get weight webcluster/web1 1 " | socat stdio /var/lib/haproxy/stats 
1 (initial 2)

[root@haproxy ~]# systemctl restart haproxy.service 
[root@haproxy ~]# echo "get weight webcluster/web1 1 " | socat stdio /var/lib/haproxy/stats 
2 (initial 2)

[root@haproxy ~]# echo "set weight webcluster/web1 1 " | socat stdio /var/lib/haproxy/stats 

[root@haproxy ~]# echo "get weight webcluster/web1 1 " | socat stdio /var/lib/haproxy/stats 
1 (initial 2)

看上述显示是支持roundrobin的

4.2.2 leastconn

leastconn加权的最少连接的动态

支持权重的运行时调整和慢启动,即:根据当前连接最少的后端服务器而非权重进行优先调度(新客户端连接)

比较适合长连接的场景使用,比如:MySQL等场景。

示例:

listen webcluster
        bind *:80
        mode http
        balance first
        balance leastconn
        server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
        server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1

4.3 其他算法

其它算法即可作为静态算法,又可以通过选项成为动态算法

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

4.3.1 source

示例:

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
[root@haproxy ~]# systemctl restart haproxy.service 

listen webcluster
        bind *:80
        mode http
        balance source
        server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
        server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1

测试:

4.3.1.1 map-base 取模法

map-based:取模法,对source地址进行hash计算,再基于服务器总权重的取模,最终结果决定将此请求转发至对应的后端服务器。 此方法是静态的,即不支持在线调整权重,不支持慢启动,可实现对后端服务器均衡调度 缺点是当服务器的总权重发生变化时,即有服务器上线或下线,都会因总权重发生变化而导致调度结果整体改变

比如当源hash值时1111,1112,1113,三台服务器a b c的权重均为1,

即abc的调度标签分别会被设定为 0 1 2(1111%3=1,1112%3=2,1113%3=0)

1111 ----- > nodea

1112 ------> nodeb

1113 ------> nodec

如果c下线后,权重数量发生变化

1111%2=1,1112%2=0,1113%2=1

1112和1113被调度到的主机都发生变化,这样会导致会话丢失

1111%2
1
1112%2
0
1113%2
1

4.3.1.2 一致性hash

一致性哈希,当服务器的总权重发生变化时,对调度结果影响是局部的,不会引起大的变动hash(o)mod n 该hash算法是动态的,支持使用 socat等工具进行在线权重调整,支持慢启动

1、后端服务器哈希环点keyA=hash(后端服务器虚拟ip)%(2^32)

2、客户机哈希环点key1=hash(client_ip)%(2^32) 得到的值在[0---4294967295]之间,

3、将keyA和key1都放在hash环上,将用户请求调度到离key1最近的keyA对应的后端服务器

一致性哈希算法将整个哈希值空间映射成一个虚拟的圆环。整个哈希空间的取值范围为0~2^32-1,按顺时针方向开始从0~2^32-1排列,最后的节点2^32-1在0开始位置重合,形成一个虚拟的圆环。如下图所示:

hash环偏斜问题

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

一致性hash示意图

后端服务器在线与离线的调度方式

拓展

生成或区随机数
echo $RANDOM

取10以内的随机数

[root@haproxy ~]# echo $[$RANDOM%10]

6

[root@haproxy ~]# echo $[$RANDOM%10]

1

[root@haproxy ~]# echo $[$RANDOM%10]

4

一致性hash配置示例

这是没加hash-type consisent

#这是加上 hash_type consistent
listen webcluster
        bind *:80
        mode http
        balance source
        hash-type consistent
        server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
        server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1

[root@haproxy ~]# echo "set weight webcluster/web1 1 " | socat stdio /var/lib/haproxy/stats 

[root@haproxy ~]# echo "get weight webcluster/web1 1 " | socat stdio /var/lib/haproxy/stats 
1 (initial 2)

4.3.2 uri

基于对用户请求的URI的左半部分或整个uri做hash,再将hash结果对总权重进行取模后

根据最终结果将请求转发到后端指定服务器

适用于后端是缓存服务器场景

默认是静态算法,也可以通过hash-type指定map-based和consistent,来定义使用取模法还是一致性hash

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

<scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<frag>
左半部分:/<path>;<params>
整个uri:/<path>;<params>?<query>#<frag>

4.3.2.1 uri 取模法配置示例

#server1上
[root@webserver1 ~]# echo 172.25.254.10 -index1.html > /usr/share/nginx/html/index1.html
[root@webserver1 ~]# echo 172.25.254.10 -index2.html > /usr/share/nginx/html/index2.html
[root@webserver1 ~]# echo 172.25.254.10 -index3.html > /usr/share/nginx/html/index3.html

#server2上
[root@webserver2 ~]# echo 172.25.254.20 -index1.html > /usr/share/nginx/html/index1.html
[root@webserver2 ~]# echo 172.25.254.20 -index2.html > /usr/share/nginx/html/index2.html
[root@webserver2 ~]# echo 172.25.254.20 -index3.html > /usr/share/nginx/html/index3.html

测试

[root@haproxy ~]# curl 172.25.254.100/index1.html
172.25.254.20 -index1.html
[root@haproxy ~]# curl 172.25.254.100/index2.html
172.25.254.20 -index2.html

4.3.2.2 uri 一致性hash配置示例

listen webcluster
        bind *:80
        mode http
        balance uri
        hash-type consistent
        server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
        server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1

测试效果 用uri算法的话只要第一次访问的地址是什么那么后面访问的地址就是什么

4.3.3 url_param

url_param对用户请求的url中的 params 部分中的一个参数key对应的value值作hash计算,并由服务器总权重相除以后派发至某挑出的服务器,后端搜索同一个数据会被调度到同一个服务器,多用与电商

通常用于追踪用户,以确保来自同一个用户的请求始终发往同一个realserver

如果无没key,将按roundrobin算法

#假设:
url = http://www.timinglee.com/foo/bar/index.php?key=value
#则:
host = "www.timinglee.com"
url_param = "key=value"

4.3.3.1 url_param取模法配置示例

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
[root@haproxy ~]# systemctl restart haproxy.service 

listen webcluster
        bind *:80
        mode http
        balance url_param name,userid
        hash-type consistent
        server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 1         #涉及权重平均
        server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1

4.3.3.2测试访问

[root@haproxy ~]# curl 172.25.254.100/index1.html?name=lee
172.25.254.20 -index1.html
[root@haproxy ~]# curl 172.25.254.100/index1.html?name=lee
172.25.254.20 -index1.html

[root@haproxy ~]# curl 172.25.254.100/index1.html?name=test
172.25.254.10 -index1.html
[root@haproxy ~]# curl 172.25.254.100/index1.html?name=test
172.25.254.20 -index1.html

建议使用name进行测试,因为userid涉及到一个链接的问题

4.3.4 hdr

针对用户每个http头部(header)请求中的指定信息做hash,

此处由 name 指定的http首部将会被取出并做hash计算,

然后由服务器总权重取模以后派发至某挑出的服务器,如果无有效值,则会使用默认的轮询调度。

4.3.4.1 hdr配置示例

listen webcluster
        bind *:80
        mode http
        balance hdr(User-Agent)
        hash-type consistent
        server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 1
        server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1

4.3.4.1测试访问

会一直显示同一浏览器上的内容,想要更改可以用下面的代码去指定

[root@haproxy ~]# curl -vA "firefox" 172.25.254.100/index.html
[root@haproxy ~]# curl -vA "sogo" 172.25.254.100/index.html

4.3.5算法总结

#静态
static-rr--------->tcp/http
first------------->tcp/http
#动态
roundrobin-------->tcp/http
leastconn--------->tcp/http
#以下静态和动态取决于hash_type是否consistent
source------------>tcp/http
Uri--------------->http
url_param--------->http
hdr--------------->http

4.3.6 各算法使用场景

irst                             #使用较少
static-rr                     #做了session共享的web集群
roundrobin
leastconn               #数据库
source                    #基于客户端公网IP的会话保持
Uri        --------------->http #缓存服务器,CDN服务商,蓝汛、百度、阿里云、腾讯
url_param  --------->http #可以实现session保持
hdr                         #基于客户端请求报文头部做下一步处理

五.高级功能及配置

介绍HAProxy高级配置及实用案例

5.1 基于cookie的会话保持

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

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

5.1.1 配置选项

cookie name [ rewrite | insert | prefix ][ indirect ] [ nocache ][ postonly ] [
preserve ][ httponly ] [ secure ][ domain ]* [ maxidle <idle> ][ maxlife ]
name: #cookie 的 key名称,用于实现持久连接
insert: #插入新的cookie,默认不插入cookie
indirect: #如果客户端已经有cookie,则不会再发送cookie信息
nocache: #当client和hapoxy之间有缓存服务器(如:CDN)时,不允许中间缓存器缓存cookie,
#因为这会导致很多经过同一个CDN的请求都发送到同一台后端服务器

5.1.2 配置示例

listen webcluster
        bind *:80
        mode http
        balance roundrobin
        cookie WEBCOOKIE insert nocache indirect
        server web1 172.25.254.10:80 cookie lee1 check inter 2 fall 3 rise 5 weight 1
        server web2 172.25.254.20:80 cookie lee2 check inter 2 fall 3 rise 5 weight 1

5.1.3验证cookie信息

通过代码行验证:

[root@haproxy ~]# curl -i 172.25.254.100
HTTP/1.1 200 OK
server: nginx/1.20.1
date: Sun, 11 Aug 2024 07:33:47 GMT
content-type: text/html
content-length: 27
last-modified: Fri, 09 Aug 2024 09:39:46 GMT
etag: "66b5e3e2-1b"
accept-ranges: bytes
set-cookie: WEBCOOKIE=lee1; path=/
cache-control: private

webserver1 - 172.25.254.10

#curl访问时指定cookie
[root@haproxy ~]# curl -b WEBCOOKIE=web1 172.25.254.100
webserver2 - 172.25.254.20
[root@haproxy ~]# curl -b WEBCOOKIE=web1 172.25.254.100
webserver1 - 172.25.254.10

[root@haproxy ~]# curl -vb WEBCOOKIE=web1 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: */*
> Cookie: WEBCOOKIE=web1

Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< server: nginx/1.20.1
< date: Sun, 11 Aug 2024 07:36:35 GMT
< content-type: text/html
< content-length: 27
< last-modified: Fri, 09 Aug 2024 12:07:28 GMT
< etag: "66b60680-1b"
< accept-ranges: bytes
< set-cookie: WEBCOOKIE=lee2; path=/
< cache-control: private

webserver2 - 172.25.254.20

Connection #0 to host 172.25.254.100 left intact

5.2 haproxy状态页

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

5.2.1 状态页配置项

stats enable                     #基于默认的参数启用stats page
stats hide-version                 #将状态页中haproxy版本隐藏
stats refresh <delay>             #设定自动刷新时间间隔,默认不自动刷新
stats uri <prefix>                 #自定义stats page uri,默认值:/haproxy?stats
stats auth <user>:<passwd>        #认证时的账号和密码,可定义多个用户,每行指定一个用户
                                #默认:no authentication
stats admin { if | unless } <cond> #启用stats page中的管理功能

5.2.2 启用状态页

listen stats
        mode http
        bind *:9999
        stats enable
        stats uri /status
        stats auth lee:lee

5.2.3 登录状态页

#### 

```
#pid为当前pid号,process为当前进程号,nbproc和nbthread为一共多少进程和每个进程多少个线程
**pid =** 4821 (process #1, nbproc = 1, nbthread = 2)
#启动了多长时间
**uptime =** 0d 0h01m19s
#系统资源限制:内存/最大打开文件数/
**system limits:** memmax = unlimited; ulimit-n = 8038
#最大socket连接数/单进程最大连接数/最大管道数maxpipes
**maxsock =** 8038; **maxconn =** 4000; **maxpipes =** 0
#当前连接数/当前管道数/当前连接速率
current conns = 2; current pipes = 0/0; conn rate = 0/sec; bit rate = 0.000 kbps
#运行的任务/当前空闲率
Running tasks: 0/23; idle = 97 %
```

active UP: #在线服务器
backup UP: #标记为backup的服务器
active UP, going down: #监测未通过正在进入down过程
backup UP, going down: #备份服务器正在进入down过程
active DOWN, going up: #down的服务器正在进入up过程
backup DOWN, going up: #备份服务器正在进入up过程
active or backup DOWN: #在线的服务器或者是backup的服务器已经转换成了down状态
not checked: #标记为不监测的服务器

#active或者backup服务器人为下线的
active or backup DOWN for maintenance (MAINT)

#active或者backup被人为软下线(人为将weight改成0)
active or backup SOFT STOPPED for maintenanc

5.2.4 backend server信息

session rate(每秒的连接会话信息);     Errors(错误统计信息):
cur:每秒的当前会话数量 ;             Req:错误请求量
max:每秒新的最大会话数量                 conn:错误链接量
limit:每秒新的会话限制量             Resp:错误响应量
sessions(会话信息): Warnings(警告统计信息):
cur:当前会话量 Retr:重新尝试次数
max:最大会话量 Redis:再次发送次数
limit: 限制会话量
Total:总共会话量 Server(real server信息):
LBTot:选中一台服务器所用的总时间 Status:后端机的状态,包括UP和DOWN
Last:和服务器的持续连接时间 LastChk:持续检查后端服务器的时间
Wght:权重
Bytes(流量统计): Act:活动链接数量
In:网络的字节输入总量 Bck:备份的服务器数量
Out:网络的字节输出总量 Chk:心跳检测时间
Dwn:后端服务器连接后都是DOWN的数量
Denied(拒绝统计信息): Dwntme:总的downtime时间
Req:拒绝请求量 Thrtle:server 状态
Resp:拒绝回复量

5.3 IP透传

web服务器中需要记录客户端的真实IP地址,用于做访问统计、安全防护、行为分析、区域排行等场景。

5.3.3 四层和七层IP透传
5.3.3.1 HAProxy配置

在由haproxy发往后端主机的请求报文中添加“X-Forwarded-For"首部,其值为前端客户端的地址;用于 向后端主发送真实的客户端IP

七层配置

5.3.3.2 web服务器日志格式配置

配置web服务器,记录负载均衡透传的客户端IP地址

[root@webserver1 ~]# vim /etc/httpd/conf/httpd.conf 
[root@webserver1 ~]# systemctl restart httpd
[root@webserver1 ~]# cat /etc/httpd/logs/access_log 
172.25.254.100 - - [11/Aug/2024:16:26:27 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/8.7.1"

5.3.3.3访问测试

[C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    27  100    27    0     0   6250      0 --:--:-- --:--:-- --:--:--  6750
webserver1 - 172.25.254.10


[root@webserver1 ~]# cat /etc/httpd/logs/access_log 
172.25.254.100 - - [11/Aug/2024:16:26:27 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/8.7.1"
172.25.254.1 172.25.254.100 - - [11/Aug/2024:16:36:24 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/8.7.1"

apache手册

[root@webserver1 ~]# dnf install httpd-manual -y
systemctl restart httpd

现在七层是可以正常访问但由于版本的更新四层已经访问不到了

[root@webserver1 ~]# cat /var/log/httpd/access_log 
172.25.254.100 - - [11/Aug/2024:17:04:27 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/8.7.1"
172.25.254.1 172.25.254.100 - - [11/Aug/2024:17:07:52 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/8.7.1"
172.25.254.1 172.25.254.100 - - [11/Aug/2024:17:09:16 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/8.7.1"

5.4 ACL

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

5.4.1 ACL配置格式

#用acl来定义或声明一个acl
acl <aclname>     <criterion>    [flags]   [operator]         [<value>]
acl 名称           匹配规范         匹配模式   具体操作符          操作对象类型

5.4.1.1 ACL-Name 名称

acl             test         path_end         -m         sub         /a
#ACL名称,可以使用大字母A-Z、小写字母a-z、数字0-9、冒号:、点.、中横线和下划线,并且严格区分大小写,比如:my_acl和My_Acl就是两个完全不同的acl5.8.1.2 ACL-criterion

示例:hdr_dom(host) 请求的host名称

vim /etc/haproxy/haproxy.cfg
systemctl restart haproxy.service
frontend webbacluster
        bind *:80
        mode http
        acl test hdr_dom(host) -i www.timinglee.org
        use_backend webcluter-host if test
        default_backend default-host

backend webcluter-host
        mode http
        server web1 172.25.254.10:80 check inter 2 fall 2 rise 5

backend default-host
        mode http
        server web2 172.25.254.20:80 check inter 2 fall 2 rise 5

测试

[C:\~]$ curl  172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    27  100    27    0     0   4990      0 --:--:-- --:--:-- --:--:--  5400
webserver2 - 172.25.254.20

[C:\~]$ curl  172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    27  100    27    0     0   6696      0 --:--:-- --:--:-- --:--:--  9000
webserver2 - 172.25.254.20

目前curl www.timinglee.org是访问不到的需要在windows下面做解析

测试

[C:\~]$ curl  www.timinglee.org
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    27  100    27    0     0   1637      0 --:--:-- --:--:-- --:--:--  2076
webserver1 - 172.25.254.10

5.4.1.2 ACL-criterion 匹配规范

定义ACL匹配规范,即:判断条件

dr 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也会匹配

查看数据报文

[C:\~]$ curl -v 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0*   Trying 172.25.254.100:80...

*Connected to 172.25.254.100 (172.25.254.100) port 80

> GET / HTTP/1.1
> Host: 172.25.254.100
> User-Agent: curl/8.7.1
> Accept: */*

*Request completely sent off
< HTTP/1.1 200 OK
< date: Sun, 11 Aug 2024 09:30:26 GMT
< server: Apache/2.4.51 (Red Hat Enterprise Linux)
< last-modified: Sun, 11 Aug 2024 08:25:44 GMT
< etag: "1b-61f641f657ff4"
< accept-ranges: bytes
< content-length: 27
< content-type: text/html; charset=UTF-8
< set-cookie: WEBCOOKIE=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/
< cache-control: private

{ [27 bytes data]
100    27  100    27    0     0   4313      0 --:--:-- --:--:-- --:--:--  4500

*Connection #0 to host 172.25.254.100 left intact
webserver1 - 172.25.254.10

以什么结尾hdr_end(host) 请求的host结尾

acl test hdr_end(host) -i .org

[C:\~]$ curl  www.timinglee.com
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    27  100    27    0     0   2208      0 --:--:-- --:--:-- --:--:--  3375
webserver2 - 172.25.254.20

#以什么开头hdr_beg(host) 请求的host开头

acl test hdr_beg(host) -i bbs

[C:\~]$ curl  bbs.timinglee.org
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    27  100    27    0     0   2616      0 --:--:-- --:--:-- --:--:--  4500
webserver1 - 172.25.254.10

base

以lee开头

acl test base_sub -m sub lee

[C:\~]$ curl  www.test.com           #在用这个域名是要在windows下做解析
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    27  100    27    0     0   2522      0 --:--:-- --:--:-- --:--:--  4500
webserver2 - 172.25.254.20

解析

[root@webserver1 ~]# mkdir /var/www/html/lee -p
[root@webserver1 ~]# echo 172.25.254.10 lee > /var/www/html/lee/index.html
[root@webserver1 ~]# curl 172.25.254.10/lee/index.html
172.25.254.10 lee

[C:\~]$ curl  www.test.com/lee/           #lee后面一定要加/表示目录,不加/表示文件
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    18  100    18    0     0   1460      0 --:--:-- --:--:-- --:--:--  2571
172.25.254.10 lee

以lee结尾

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
[root@haproxy ~]# systemctl restart haproxy.service 
acl test base_reg -i lee/$

path : string

#提取请求的URL路径,该路径从第一个斜杠开始,并在问号之前结束(无主机部分)

acl test path_sub -m sub lee

[C:\~]$ curl  www.timinglee.org
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    27  100    27    0     0   1450      0 --:--:-- --:--:-- --:--:--  2076
webserver2 - 172.25.254.20

[C:\~]$ curl  www.timinglee.org/lee/
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    18  100    18    0     0    987      0 --:--:-- --:--:-- --:--:--  1500
172.25.254.10 lee

[C:\~]$ curl  www.test.com/lee/
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    18  100    18    0     0    867      0 --:--:-- --:--:-- --:--:--  1125
172.25.254.10 lee

这表明看的是文件路径的后面部分

!表示符合的到web2不符合的到web1

 use_backend webcluter-host if ! test
 [root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
[root@haproxy ~]# systemctl restart haproxy.service


[root@webserver2 ~]# mkdir -p /usr/share/nginx/html/lee
[root@webserver2 ~]# echo 172.25.254.20 lee > /usr/share/nginx/html/lee/index.html

[C:\~]$ curl  www.test.com/lee/
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    18  100    18    0     0    784      0 --:--:-- --:--:-- --:--:--  1058
172.25.254.20 lee

[C:\~]$ curl  www.test.com
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    27  100    27    0     0   1018      0 --:--:-- --:--:-- --:--:--  1500
webserver1 - 172.25.254.10

两者都可以的 ||

 [root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
    [root@haproxy ~]# systemctl restart haproxy.service
    acl domain hdr_beg(host) -i bbs
    acl test path_sub -m sub lee
    use_backend webcluter-host if test || domain

[C:\~]$ curl  bbs.timinglee.org
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    27  100    27    0     0   1461      0 --:--:-- --:--:-- --:--:--  2076
webserver1 - 172.25.254.10

[C:\~]$ curl  bbs.timinglee.org/lee/
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    18  100    18    0     0    689      0 --:--:-- --:--:-- --:--:--   900
172.25.254.10 lee

[C:\~]$ curl  www.test.com
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    27  100    27    0     0   1232      0 --:--:-- --:--:-- --:--:--  1928
webserver2 - 172.25.254.20

与关系两者都要满足

[C:\~]$ curl  bbs.timinglee.org/lee/
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    18  100    18    0     0    576      0 --:--:-- --:--:-- --:--:--   857
172.25.254.10 lee

5.4.1.3 ACL-flags 匹配模式

-i 不区分大小写
-m 使用指定的正则表达式匹配方法
-n 不做DNS解析
-u 禁止acl重名,否则多个同名ACL匹配或关系

5.4.2 多个ACL的组合调用方式

        use_backend webcluter-host if test              #满足test
        use_backend webcluter-host if ! test            #表示不满test
        use_backend webcluter-host if test  domain        #表示两者都要满足
        use_backend webcluter-host if test || domain    #满足两者之一即可

5.4.3 ACL示例-域名匹配

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
[root@haproxy ~]# systemctl restart haproxy.service 

frontend webbacluster
        bind *:80
        mode http
        acl domain hdr_dom(host) -i www.timinglee.org

        ############################
    
        use_backend webcluter-host if domain
        default_backend default-host


backend webcluter-host
        mode http
        server web1 172.25.254.10:80 check inter 2 fall 2 rise 5

backend default-host
        mode http
        server web2 172.25.254.20:80 check inter 2 fall 2 rise 5

测试结果

#只有域名相匹配才会访问到10否则访问20
[C:\~]$ curl  www.timinglee.org
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    27  100    27    0     0   1155      0 --:--:-- --:--:-- --:--:--  1500
webserver1 - 172.25.254.10

[C:\~]$ curl  www.test.com
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    27  100    27    0     0   1477      0 --:--:-- --:--:-- --:--:--  3375
webserver2 - 172.25.254.20

5.4.4 基于源IP或子网调度访问

将指定的源地址调度至指定的web服务器组。

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
[root@haproxy ~]# systemctl restart haproxy.service 

frontend webbacluster
        bind *:80
        mode http
        acl ctrl_ip src 172.25.254.1 172.25.254.20 192.168.0.0/24

        use_backend webcluter-host if ctrl_ip
        default_backend default-host


backend webcluter-host
        mode http
        server web1 172.25.254.10:80 check inter 2 fall 2 rise 5

backend default-host
        mode http
        server web2 172.25.254.20:80 check inter 2 fall 2 rise 5

测试

[root@haproxy ~]# curl 172.25.254.100
webserver2 - 172.25.254.20

拒绝

http-request deny if ctrl_ip

测试

5.4.5匹配浏览器类型

匹配客户端浏览器,将不同类型的浏览器调动至不同的服务器组、 范例: 拒绝curl和wget的访问

frontend webbacluster
        bind *:80
        mode http
        acl badwebrowers hdr_sub(User-Agent) -i curl wgent
        ############################

        #use_backend webcluter-host if ctrl_ip
        http-request deny if badwebrowers
        default_backend default-host


backend webcluter-host
        mode http
        server web1 172.25.254.10:80 check inter 2 fall 2 rise 5

backend default-host
        mode http
        server web2 172.25.254.20:80 check inter 2 fall 2 rise 5

测试

[C:\~]$ curl  172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    93  100    93    0     0  11623      0 --:--:-- --:--:-- --:--:-- 13285
<html><body><h1>403 Forbidden</h1>
                                  Request forbidden by administrative rules.
                                                                            </body></html>

在浏览器上访问是可以的        

5.4.6基于文件后缀名实现动静分离

[root@webserver1 ~]# dnf install php -y
[root@webserver1 ~]# vim /var/www/html/index.php
[root@webserver1 ~]# cat /var/www/html/index.php
<?php
    phpinfo();
?>

配置完成后先看能不能访问

配置文件

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
[root@haproxy ~]# systemctl restart haproxy.service

frontend webbacluster
        bind *:80
        mode http
        acl static path_end -i .html .jpg .png .css .js
        acl php path_end -i .php
        ############################

        use_backend webcluter-host if php
        default_backend default-host

测试

什么都不写显示的默认显示

后缀加上index.php 这就实现了动静分离

5.4.7基于访问路径实现动静分离

[root@webserver2 ~]# mkdir /usr/share/nginx/html/static -p
[root@webserver2 ~]# echo static - 172.25.254.20 > /usr/share/nginx/html/static/index.html
[root@webserver2 ~]# curl 172.25.254.20/static/
static - 172.25.254.20

[root@webserver1 ~]# mkdir -p /var/www/html/php
[root@webserver1 ~]# cp /var/www/html/index.php /var/www/html/php/

配置文件

frontend webbacluster
        bind *:80
        mode http
        acl static path_sub -i sub static
        acl php path_sub -i sub php
        ############################

        use_backend webcluter-host if php
        default_backend default-host

测试

5.5 自定义haproxy 错误界面

对指定的报错进行重定向,进行优雅的显示错误页面

使用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

先暂停web上面的服务

[root@webserver1 ~]# systemctl stop httpd

[root@webserver2 ~]# systemctl stop nginx

5.5.1 基于自定义的错误页面文件

errorfile 503 /etc/haproxy/errorpage/503.http 

配置文件

[root@haproxy ~]# mkdir /etc/haproxy/errorpage -p
[root@haproxy ~]# vim /etc/haproxy/errorpage/503.http
[root@haproxy ~]# cat /etc/haproxy/errorpage/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>

测试

5.5.2 基于http重定向错误页面

errorloc 503 https://www.baidu.com

测试

5.6 haproxy 四层负载

用数据库来做,安装软件,两台服务器都要安装

[root@webserver1 ~]# dnf install mariadb-server -y
[root@webserver2 ~]#  dnf install mariadb-server -y

#编辑配置文件,便于观察现象

[root@webserver1 ~]# vim /etc/my.cnf.d/mariadb-server.cnf

[root@webserver1 ~]# vim /etc/my.cnf.d/mariadb-server.cnf 
[root@webserver1 ~]# systemctl start mariadb
[root@webserver1 ~]# mysql 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 10.5.13-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> SELECT @@server_id;
+-------------+
| @@server_id |
+-------------+
|           1 |
+-------------+
1 row in set (0.000 sec)

MariaDB [(none)]> 

[root@webserver2 ~]# vim /etc/my.cnf.d/mariadb-server.cnf 
[root@webserver2 ~]# systemctl start mariadb

[root@webserver2 ~]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 10.5.13-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> SELECT @@server_id
    -> ;
+-------------+
| @@server_id |
+-------------+
|           2 |
+-------------+
1 row in set (0.000 sec)

MariaDB [(none)]> 

两台服务器做允许远程登陆

MariaDB [(none)]> CREATE USER lee@'%' identified by 'lee';
Query OK, 0 rows affected (0.001 sec)

MariaDB [(none)]> GRANT ALL ON *.* TO lee@'%';
Query OK, 0 rows affected (0.001 sec)

查看端口是否开启

[root@webserver1 ~]# netstat -atnlupe | grep 3306
tcp6       0      0 :::3306                 :::*                    LISTEN      27         95935      4880/mariadbd

测试

[root@haproxy ~]# mysql -ulee -p -h 172.25.254.10
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 5
Server version: 10.5.13-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> 

在客户端做负载

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
[root@haproxy ~]# systemctl restart haproxy.service

listen dbserver
        bind *:3306
        mode tcp
        balance static-rr
        server db1 172.25.254.10:3306 check inter 2 fall 2 rise 5
        server db2 172.25.254.20:3306 check inter 2 fall 2 rise 5

[root@haproxy ~]# mysql -ulee -plee -h 172.25.254.100
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 4
Server version: 10.5.13-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> 

[root@haproxy ~]# mysql -ulee -plee -h 172.25.254.100
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 9
Server version: 10.5.13-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> SELECT @@server_id;
+-------------+
| @@server_id |
+-------------+
|           1 |
+-------------+
1 row in set (0.001 sec)

MariaDB [(none)]> qiut

[root@webserver1 ~]# mysql -ulee -plee -h 172.25.254.100
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 7
Server version: 10.5.13-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> SELECT @@server_id;
+-------------+
| @@server_id |
+-------------+
|           2 |
+-------------+
1 row in set (0.001 sec)

MariaDB [(none)]> 

5.7https加密访问

5.7.1证书制作

#创建目录并生成证书
[root@haproxy ~]# mkdir -p /etc/haproxy/certs
[root@haproxy ~]# openssl req -newkey rsa:2048 -nodes -sha256 -keyout /etc/haproxy/certs/timing.lee.org.key -x509 -days 365 -out /etc/haproxy/certs/timinglee.org.crt


Country Name (2 letter code) [XX]:CN      
State or Province Name (full name) []:Shanxi
Locality Name (eg, city) [Default City]:Xi'An 
Organization Name (eg, company) [Default Company Ltd]:timinglee
Organizational Unit Name (eg, section) []:webserver
Common Name (eg, your name or your server's hostname) []:www.timinglee.org     
Email Address []:admin@timinglee.org


[root@haproxy ~]# ls /etc/haproxy/certs/
timinglee.org.crt  timing.lee.org.key

[root@haproxy ~]# cat /etc/haproxy/certs/timing.lee.org.key /etc/haproxy/certs/timinglee.org.crt > /etc/haproxy/certs/timinglee.pem
[root@haproxy ~]# cat /etc/haproxy/certs/timinglee.pem

5.7.2https配置示例

listen  web-https
        bind *:443 ssl crt /etc/haproxy/certs/timinglee.pem
        mode http
        balance roundrobin
        server web1 172.25.254.10:80 check inter 2 fall 2 rise 5
        server web2 172.25.254.20:80 check inter 2 fall 2 rise 5 

查看端口是否开启

[root@haproxy ~]# systemctl restart haproxy.service 
[root@haproxy ~]# netstat -antlupe | grep haproxy
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      0          35936435   6836/haproxy        
tcp        0      0 0.0.0.0:9999            0.0.0.0:*               LISTEN      0          35936432   6836/haproxy        
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      0          35936433   6836/haproxy        
tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      0          35936434   6836/haproxy        
udp        0      0 0.0.0.0:57894           0.0.0.0:*                           991        35936441   6836/haproxy        
udp        0      0 0.0.0.0:49951           0.0.0.0:*                           991        35936097   6836/haproxy  

网页访问,一定保证web1和web2都正常开启 查看证书

全站加密参数

frontend webbacluster
        bind *:80
        mode http
        redirect scheme https if !{ ssl_fc }

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值