什么是haproxy七层代理

一.负载均衡

1.1.什么是负载均衡

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

1.2.为什么用负载均衡

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

1.3.负载均衡类型

1.3.1硬件:

F5
Netscaler
Array
AD-1000

1.3.2.四层负载均衡

1.通过ip+port决定负载均衡的去向。
2.对流量请求进行NAT处理,转发至后台服务器。
3.记录tcp、udp流量分别是由哪台服务器处理,后续该请求连接的流量都通过该服务器处理。
4.支持四层的软件
lvs:重量级四层负载均衡器。
Nginx:轻量级四层负载均衡器,可缓存。(nginx四层是通过upstream模块)
Haproxy:模拟四层转发。

1.3.3.七层负载均衡

1.通过虚拟ur|或主机ip进行流量识别,根据应用层信息进行解析,决定是否需要进行负载均衡。
2.代理后台服务器与客户端建立连接,如nginx可代理前后端,与前端客户端tcp连接,与后端服务器建立
tcp连接,
3.支持7层代理的软件:
Nginx:基于http协议(nginx七层是通过proxy_pass)
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
客户端eth0:172.,25.254.10
haproxyeth0:172.25.254.100,eth1:192.168.0.10
RS1eth0:192.168.0.101
RS2eth0:192.168.0.102

3.2.软件安装

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

3.3.haproxy的基本配置信息

官方文档:
http://cbonte.github.io/haproxy-dconv/
HAProxy 的配置文件haproxy.cfg由两大部分组成,分别是:
global:全局配置段
进程及安全配置相关的参数
性能调整相关参数
Debug参数
proxies:代理配置段
defaults:为frontend, backend, listen提供默认配置
frontend:前端,相当于nginx中的server {}
backend:后端,相当于nginx中的upstream {}
listen:同时拥有前端和后端配置,配置简单,生产推荐使用

haproxy

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

请添加图片描述

web1

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

web2

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

测试

[root@haproxy ~]# curl 172.25.254.10
webserver1 - 172.25.254.10
[root@haproxy ~]# curl 172.25.254.20
webserver2 - 172.25.254.20

global全局设置

相关参数
chroot:锁定运行目录

deamon:以守护进程运行

user,group,uid,gid:运行haproxy的用户身份

static socket:套接字文件

nbproc N:开启的haproxy worker进程数,默认是进程数是1个

nbthread 1:指定每个haproxy进程开启的线程数,默认每个进程的线程数为1

cpu-map 1 0:绑定haproxy worker进程至指定CPU,将第一个work进程绑定至0号CPU

maxconn N:每个haproxy进程的最大并发连接数

maxsslconn N:每个haproxy进程ssl最大连接数

maxconnrate N:每个进程每秒创建的最大连接数

spread-checks N:后端server状态check随机提前或延迟百分比时间,默认值0

pidfile:指定pid文件路径

log 127.0.0.1 local2 info:定义全局的syslog服务器

多进程和多线程互斥,设置了多进程就不能设置多线程

开两个进程
请添加图片描述
请添加图片描述
多进程
请添加图片描述

cpu-map 1 0  #进程和cpu核心绑定防止cpu抖动从而减少系统资源消耗
cpu-map 2 1  #2 表示第二个进程,1表示第二个cpu核心

haproxy日志定向

[root@haproxy ~]# vim /etc/rsyslog.conf

请添加图片描述

3、proxies配置

proxies参数
defaults:提供默认配置,这些配置可以自动应用到frontend、backend和listen部分,从而简化了特定配置的重复定义。例如,在defaults中设定的超时时间、选项如option http-keep-alive,将自动应用于所有未明确指定这些值的其他配置段。

frontend:定义了接收客户端请求的前端虚拟服务。在frontend配置中,可以指定HAProxy监听的地址和端口,以及与之关联的后端服务器组。这一部分是自HAProxy 1.3版本引入的新概念,旨在简化配置管理。

backend:这里配置的是实际处理客户端请求的后端服务器组。每个backend可以定义一个或多个服务器,并为它们指定相关的负载均衡算法和其他选项。比如使用balance roundrobin来设置轮询式的负载均衡方法。

listen:它是frontend和backend的组合体,通常用于TCP模式的代理场景。在这种模式下,listen元素直接定义了frontend及相关的backend,简化了配置结构。

default参数
运行模式:通过mode参数设置,可以选择http、tcp或health三种模式。在http模式下,HAProxy会深度分析客户端请求,确保其与RFC格式兼容。tcp模式则建立全双工连接,不对七层报文进行检查。

超时时间:包括timeout connect(连接超时)、timeout client(客户端数据传输超时)和timeout server(服务器响应超时)。这些超时时间设定对保持有效连接至关重要。

失败重试次数: retries参数定义了连接后端服务器失败时的重试次数。超过设定值,HAProxy将服务器标记为不可用。

选项功能: 如option http-keep-alive支持长连接,提高HTTP性能;option forwardfor保留客户端真实IP信息供后端服务器使用。

日志记录: 设定是否记录空会话的日志等。合理配置这些选项可以优化HAProxy的性能和日志记录功能。

frontend参数
绑定地址:通过bind参数,可以指定HAProxy监听的IP地址和端口。例如,使用bind *:80会监听所有IPv4地址的80端口。

运行模式:mode参数设置运行的模式,如http或tcp。在http模式下,HAProxy将解析HTTP请求,而在tcp模式下则不会解析。

日志记录:option httplog启用对HTTP请求的日志记录,这有助于后续的问题排查和监控。

前向IP:option forwardfor允许后端服务器通过"X-Forwarded-For"头部信息看到客户端的真实IP地址,这个选项在反向代理配置中非常有用。

连接关闭:option httpclose指示HAProxy在完成每次请求后主动关闭TCP连接,这可以提高性能并减少资源消耗。

默认后端:default_backend定义了没有特别指定的请求应该路由到哪个后端服务器组处理。

backend参数
负载均衡算法:通过balance参数设置,可以选择不同的负载均衡算法如roundrobin, leastconn等。例如,roundrobin基于权重进行轮询调度,而leastconn将连接请求转发给具有最少连接数目的服务器。

服务器状态监控:option httpchk允许对后端服务的状态进行检查,这确保了只有健康的服务器才会接收新的请求。

会话保持:option redispatch用于在cookie保持的环境中,确保会话的持久性。如果后端服务器出现故障,此选项会将客户请求强制定向到其他健康的服务器上。

服务器定义:在backend内,通过server参数定义具体的后端服务器地址和端口,还可以设置额外的选项如weight(权重),cookie(插入SESSION_COOKIE)等。

断开策略:option abortonclose会在服务器负载过高的情况下自动结束当前处理时间较长的连接。

backend-server参数
服务器地址和端口:通过server

[:port]定义了后端服务器的名称、IP地址和端口。例如,server web1 192.168.0.1:80表示一个名为web1的服务器,其IP地址为192.168.0.1,端口为80。

权重设置:使用weight参数可以为服务器指定一个权重,这个权重会影响负载均衡算法的选择。例如,weight 6会给当前服务器分配更多的请求。

cookie插入:通过cookie 可以在服务器上插入指定的cookie值,这有助于实现会话保持等功能。

健康检查:设置check启用对此后端服务器的健康状态检查。这是确保只有健康的服务器响应客户端请求的重要选项。

检查间隔:inter设置健康状态检查的时间间隔,合理的间隔可以及时检测到服务器的状态变化。

转换状态:rise和fall参数分别设置从故障状态转换至正常状态和从正常状态转换为不可用状态需要成功检查的次数。这有助于避免由于网络波动造成的误判。

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 

请添加图片描述

sorryserver配置

haproxy

#下载apache服务

yum install httpd -y

echo web_sorry - 172.25.254.100 > /var/www/html/index.html

#编辑http配置文件

vim /etc/httpd/conf/httpd.con
......(省略)
listen 8080
......
#重启httpd服务

systemctl enable --now httpd

#编辑haproxy配置文件 

vim /etc/haproxy/haproxy.cfg

.....
server web1...
server web2...
server web_sorry 172.25.254.100:8080 backup  

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

server 配置

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

演示 网页重定向

请添加图片描述
浏览器访问172.25.254.100 ,到了百度,成功

3.4.socat 工具

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

#修改配置文件
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
 stats socket /var/lib/haproxy/stats mode 600 level admin
 #查看帮助
haproxy ~]# socat -h
 haproxy ~]# echo "help" | socat stdio /var/lib/haproxy/stats
 The following commands are valid at this level:
 help           
: this message
 prompt         
quit           
get weight     
set weight     
: disconnect
 : toggle interactive mode with prompt
。。。省略 。。。
enable server : enable a disabled server (use 'set server' instead)   #启用服务器
set maxconn server : change a server's maxconn setting
 set server     
: change a server's state, weight or address           
: report a server's current weight                     
: change a server's weight (deprecated)                
#设置服务器   
#查看权重
#设置权重
show startup-logs : report logs emitted during HAProxy startup
 how peers [peers section]: dump some information about all the peers or this 
peers section
 set maxconn global : change the per-process maxconn setting
 set rate-limit : change a rate limiting value
 set severity-output [none|number|string] : set presence of severity level in
 feedback information
 set timeout   : change a timeout setting
 show env [var] : dump environment variables known to the process
 show cli sockets : dump list of cli sockets
 show cli level   : display the level of the current CLI session
 show fd [num] : dump list of file descriptors in use
。。。省略 。。

请添加图片描述
请添加图片描述

下载socat 工具

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

#查看帮助

echo "help" | socat stdio /var/lib/haproxy/stats

#设置权重

echo " set weight webcluster/web1 2 " | socat stdio /var/lib/haproxy/stats

#查看权重

echo " get weight webcluster/web1 " | socat stdio /var/lib/haproxy/stats

#查看haproxy基本信息

echo show info | socat stdio /var/lib/haproxy/stats

haproxy多进程热处理

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

请添加图片描述

四.haproxy的算法

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

4.1 静态算法

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

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

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

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

请添加图片描述
测试结果
请添加图片描述

4.1.2 first

根据服务器在列表中的位置,自上而下进行调度
其只会当第一台服务器的连接数达到上限,新请求才会分配给下一台服务
其会忽略服务器的权重设置
不支持用socat进行动态修改权重,可以设置0和1,可以设置其它值但无效

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

请添加图片描述
测试
请添加图片描述

4.2动态算法

基于后端服务器状态进行调度适当调整,
新请求将优先调度至当前负载较低的服务器
权重可以在haproxy运行时动态调整无需重启

4.2.1 roundrobin

  1. 基于权重的轮询动态调度算法,
  2. 支持权重的运行时调整,不同于lvs中的rr轮训模式,
  3. HAProxy中的roundrobin支持慢启动(新加的服务器会逐渐增加转发数),
  4. 其每个后端backend中最多支持4095个real server,
  5. 支持对real server权重动态调整,
  6. roundrobin为默认调度算法,此算法使用广泛
haproxy ~]# vim /etc/haproxy/haproxy.cfg
 ...上面内容省略...
 listen webserver_80
 bind 172.25.254.100:80
 mode http
 balance roundrobin                 
server webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5 
server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5
 ...上面内容省略...

4.2.2 leastconn

leastconn加权的最少连接的动态支持权重的运行时调整和慢启动,即:根据当前连接最少的后端服务器而非权重进行优先调度(新客户端连接)
比较适合长连接的场景使用,比如:MySQL等场景。

haproxy ~]# vim /etc/haproxy/haproxy.cfg
 ...上面内容省略...
 listen webserver_80
 bind 172.25.254.100:80
 mode http
 balance leastconn
 server webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5 
server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5
 ...上面内容省略...

4.3 其他算法

4.3.1 source

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

haproxy ~]# vim /etc/haproxy/haproxy.cfg
 ...上面内容省略...
 listen webserver_80
 bind 172.25.254.100:80
 mode http
 balance source
 server webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5 
server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5
 ...上面内容省略...

测试

[root@node10 ~]# for N in  {1..6}; do curl 172.25.254.100; done
 RS1 server - 192.168.0.101
 RS1 server - 192.168.0.101
 RS1 server - 192.168.0.101
 RS1 server - 192.168.0.101
 RS1 server - 192.168.0.101
 RS1 server - 192.168.0.101
4.3.1.1 map-base 取模法

map-based:取模法,对source地址进行hash计算,再基于服务器总权重的取模,最终结果决定将此请求转发至对应的后端服务器。
此方法是静态的,即不支持在线调整权重,不支持慢启动,可实现对后端服务器均衡调度
缺点是当服务器的总权重发生变化时,即有服务器上线或下线,都会因总权重发生变化而导致调度结果整体改变hash-type 指定的默值为此算法
所谓取模运算,就是计算两个数相除之后的余数,10%7=3, 7%4=3
map-based算法:基于权重取模,hash(source_ip)%所有后端服务器相加的总权重

比如当源hash值时1111,1112,1113,三台服务器a b c的权重均为1,
即abc的调度标签分别会被设定为 0 1 2(1111%3=1,1112%3=2,1113%3=0)
1111 ----- > nodeb
 1112 ------> nodec
 1113 ------> nodea
如果a下线后,权重数量发生变化
1111%2=1,1112%2=0,1113%2=1
 1112和1113被调度到的主机都发生变化,这样会导致会话丢失
haproxy ~]# vim /etc/haproxy/haproxy.cfg
 ...上面内容省略...
 listen webserver_80
 bind 172.25.254.100:80
 mode http
 balance source
 server webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5 
server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5
 ...上面内容省略...
 #不支持动态调整权重值
[root@haproxy ~]# echo "set weight webserver_80/webserver1 2" | socat stdio 
/var/lib/haproxy/haproxy.sock
 Backend is using a static LB algorithm and only accepts weights '0%' and '100%'.
 #只能动态上线和下线
[root@haproxy ~]# echo "set weight webserver_80/webserver1 0" | socat stdio 
/var/lib/haproxy/haproxy.sock
 [root@haproxy ~]# echo "get  weight webserver_80/webserver1" | socat stdio 
/var/lib/haproxy/haproxy.sock
 0 (initial 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对应的后端服务器

hash环偏斜问题

增加虚拟服务器IP数量,比如:一个后端服务器根据权重为1生成1000个虚拟IP,再hash。而后端服务器权
重为2则生成2000的虚拟IP,再bash,最终在hash环上生成3000个节点,从而解决hash环偏斜问题
一致性hash配置
haproxy ~]# vim /etc/haproxy/haproxy.cfg
 ...上面内容省略...
 listen webserver_80
 bind 172.25.254.100:80
 mode http
 balance source
 hash-type consistent
 server webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5 
server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5
 ...上面内容省略...

4.3.2 uri

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

 <scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<frag>
左半部分:/<path>;<params>
整个uri:/<path>;<params>?<query>#<frag>
4.3.2.1 uri 取模法配置
haproxy ~]# vim /etc/haproxy/haproxy.cfg
 ...上面内容省略...
 listen webserver_80
 bind 172.25.254.100:80
 mode http
 balance uri
 server webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5 
server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5
 ...上面内容省略...
4.3.2.2 uri 一致性hash配置示例
haproxy ~]# vim /etc/haproxy/haproxy.cfg
 ...上面内容省略...
 listen webserver_80
 bind 172.25.254.100:80
 mode http
 balance uri
 hash-type consistent
 server webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5 
server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5
4.3.2.3 访问测试

访问不同的uri,确认可以将用户同样的请求转发至相同的服务器

[root@rs1 ~]# echo RS1  192.168.0.101 index1 > /var/www/html/index1.html
 [root@rs1 ~]# echo RS1  192.168.0.101 index2 > /var/www/html/index2.html
 [root@rs1 ~]# echo RS1  192.168.0.101 index3 > /var/www/html/index3.html
 [root@rs2 ~]# echo RS1  192.168.0.102 index1 > /var/www/html/index1.html
 [root@rs2 ~]# echo RS1  192.168.0.102 index2 > /var/www/html/index2.html
 [root@rs2 ~]# echo RS1  192.168.0.102 index3 > /var/www/html/index3.html
 [root@node10 ~]# curl  172.25.254.100/index.html
 RS2 server - 192.168.0.102
 [root@node10 ~]# curl  172.25.254.100/index1.html
 RS1 192.168.0.101 index1
[root@node10 ~]# curl  172.25.254.100/index2.html
 RS1 192.168.0.102 index2
 [root@node10 ~]# curl  172.25.254.100/index3.html
 RS1 192.168.0.101 index3

4.3.3 url_param

url_param对用户请求的url中的 params 部分中的一个参数key对应的value值作hash计算,并由服务器总权重相除以后派发至某挑出的服务器,后端搜索同一个数据会被调度到同一个服务器,多用与电商通常用于追踪用户,以确保来自同一个用户的请求始终发往同一个real server
如果无没key,将按roundrobin算法

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

算法总结

#静态
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

各算法使用场景

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

# 五.高级功能及配置
## 5.1 基于cookie的会话保持
cookie value:为当前server指定cookie值,实现基于cookie的会话黏性,相对于基于 source 地址hash 调度算法对客户端的粒度更精准,但同时也加大了haproxy负载,目前此模式使用较少, 已经被session共享服务器代替
**注意:不支持 tcp mode,使用 http mode**
### 5.1.1 配置选项

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

五.高级功能及配置

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:       
insert:     
#cookie 的 key名称,用于实现持久连接
#插入新的cookie,默认不插入cookie
 indirect:   #如果客户端已经有cookie,则不会再发送cookie信息
nocache:    
#当client和hapoxy之间有缓存服务器(如:CDN)时,不允许中间缓存器缓存cookie,
#因为这会导致很多经过同一个CDN的请求都发送到同一台后端服务器
[root@haproxy ~]# vi /etc/haproxy/haproxy.cfg 
[root@haproxy ~]# systemctl restart haproxy.service

请添加图片描述
访问浏览器
请添加图片描述

5.2 HAProxy状态页

5.2.1 状态页配置项

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

5.2.2 启用状态页

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

请添加图片描述

5.2.3 登录状态页

浏览器访问172.25.254.100:9999/status
请添加图片描述

5.2.4 backend server信息

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

5.3 IP透传

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

5.3.1 四层IP透传

haproxy

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

请添加图片描述
webserver

[root@web1 ~]# vi /etc/nginx/nginx.conf

请添加图片描述
请添加图片描述
测试
请添加图片描述
请添加图片描述

七层
请添加图片描述

5.4 ACL

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

5.4.1 ACL配置选项

#用acl来定义或声明一个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

5.4.1.2 ACL-criterion 匹配规范
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也会匹配 
 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
  #提取请求中的整个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 valid_method method GET HEAD
 http-request deny if ! valid_method

5.4.3 ACL示例-域名匹配

haproxy
请添加图片描述
请添加图片描述

5.4.4 ACL示例-基于源IP或子网调度访问

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

haproxy ~]# vim /etc/haproxy/haproxy.cfg
 ...上面内容省略...
frontend testacl
 bind :80
 mode http
 ###########     
ACL settings    
#######################
 acl ip_test src 172.25.254.1 192.168.0.0/24
 ###########     
host        
###########################
 use_backend ip_test-host if ip_test
 ###########     
default server      
default_backend default_webserver
 ###################
 backend ip_test-host
 mode http
 server web1 192.168.0.101:80 check weight 1 inter 3s fall 3 rise 5
 backend default_webserver
 mode http
 server web1 172.25.254.10:80 check weight 1 inter 3s fall 3 rise 5

测试

[172.25.254.10 root@node10 html]# curl  172.25.254.100
 default web server node10
 [172.25.254.1 Administrator.WIN-20240602BIS] ➤ curl 172.25.254.100
 RS1 192.168.0.101
 [192.168.0.102 root@rs1 ~]# curl  192.168.0.101
 RS1 192.168.0.101

5.4.5 ACL示例-基于源地址的访问控制

拒绝指定IP或者IP范围访问

haproxy ~]# vim /etc/haproxy/haproxy.cfg
 ...上面内容省略...
 frontend testacl
 bind :80
 mode http
 ###########     
ACL settings    
#######################
 acl web_host hdr_dom(host) www.timinglee.org
 acl ip_test src 172.25.254.1 192.168.0.0/24
 ###########     
host        
###########################
 http-request deny if web_host
 ###########     
default server      
###################
 default_backend default_webserver
backend ip_test-host
 mode http
 server web1 192.168.0.101:80 check weight 1 inter 3s fall 3 rise 5
 backend default_webserver
 mode http
 server web1 172.25.254.10:80 check weight 1 inter 3s fall 3 rise 5

测试

root@node10 ~]# curl www.timinglee.org
 <html><body><h1>403 Forbidden</h1>
 Request forbidden by administrative rules.
 </body></html>
 [root@node10 ~]# curl 172.25.254.100
 default web server node10

5.4.6 ACL示例-匹配浏览器类型

匹配客户端浏览器,将不同类型的浏览器调动至不同的服务器组

haproxy ~]# vim /etc/haproxy/haproxy.cfg
 ...上面内容省略...
 frontend testacl
 bind :80
 mode http
 ###########     
ACL settings    
#######################
 acl user_agent_block hdr_sub(User-Agent) -i curl wget
 acl user_agent_redirect hdr_sub(User-Agent) -i Mozilla/5.0
 ###########     
###########     
host        
###########################
 http-request deny if user_agent_block
 redirect prefix https://www.baidu.com if user_agent_redirect
 default server      
default_backend default_webserver
 ###################
 backend ip_test-host
mode http
 server web1 192.168.0.101:80 check weight 1 inter 3s fall 3 rise 5
 backend default_webserver
 mode http
 server web1 172.25.254.10:80 check weight 1 inter 3s fall 3 rise 5

测试

 [root@node10 ~]# wget http://172.25.254.100/index.html--2024-07-11 23:04:36--  http://172.25.254.100/index.html
 Connecting to 172.25.254.100:80... connected.
 HTTP request sent, awaiting response... 403 Forbidden
 2024-07-11 23:04:36 ERROR 403: Forbidden.

5.4.7 ACL示例-基于文件后缀名实现动静分离

haproxy ~]# vim /etc/haproxy/haproxy.cfg
 ...上面内容省略...
 frontend testacl
 bind :80
 mode http
 ###########     
ACL settings    
#######################
 acl url_static  path_end -i .jpg .png .css .js .html
 acl url_php     
path_end -i .php
 ###########     
host        
###########################
 use_backend static_host if url_static
 use_backend php_host if url_php
 ###########     
default server      
default_backend default_webserver
 ###################
 backend static_host
 mode http
 server web2 192.168.0.101:80 check weight 1 inter 3s fall 3 rise 5
 backend php_host
 mode http
 server web1 192.168.0.102:80 check weight 1 inter 3s fall 3 rise 5
backend default_webserver
 mode http
 server 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.php
 php 192.168.0.102
 [root@node10 ~]# curl 172.25.254.100/index.css
 css 192.168.0.101

5.4.8 ACL-匹配访问路径实现动静分离

haproxy ~]# vim /etc/haproxy/haproxy.cfg
 ...上面内容省略...
 frontend testacl
 bind :80
 mode http
 ###########     
ACL settings    
#######################
 acl url_static  path_end -i .jpg .png .css .js .html
 acl url_static  path_end -m sub /static /images /javascript
 acl acl_app     
path_beg -m sub /api
 ###########     
###########     
host        
###########################
 use_backend static_host if url_static
 use_backend api_host if acl_app
 default server      
default_backend default_webserver
 ###################
 backend static_host
 mode http
 server web2 192.168.0.101:80 check weight 1 inter 3s fall 3 rise 5
 backend api_host
 mode http
 server web1 192.168.0.102:80 check weight 1 inter 3s fall 3 rise 5
 backend default_webserver
 mode http
 server web1 172.25.254.10:80 check weight 1 inter 3s fall 3 rise 5
#创建相关文件
[root@rs1 ~]# mkdir /usr/share/nginx/html/static
 [root@rs1 ~]# echo static 192.168.0.101 > /usr/share/nginx/html/static/index.html
 [root@rs2 ~]# mkdir  /var/www/html/api/
 [root@rs2 ~]# echo api 192.168.0.102 > /var/www/html/api/index.html
 #测试访问
[root@node10 ~]# curl 172.25.254.100/api/
 api 192.168.0.102
 [root@node10 ~]# curl 172.25.254.100/static/
 static 192.168.0.101

5.5 自定义HAProxy 错误界面

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

mkdir -p /etc/haproxy/errorpage/

cp /usr/share/haproxy/503.http /etc/haproxy/errorpage/503page.http

vim /etc/haproxy/errorpage/503page.http
vim /etc/nginx/nginx.conf

webserver

systemctl stop nginx

请添加图片描述
测试
访问172.25.254.100出现503报错

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

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

#自定义错误页
errorfile <code> <file> 
<code> #HTTP status code.支持200, 400, 403, 405, 408, 425, 429, 500, 502,503,504
 <file> #包含完整HTTP响应头的错误页文件的绝对路径。 建议后缀".http",以和一般的html文件相区分

web1

yum install mariadb-server -y

vim /etc/my.cnf.d/mariadb-server.cnf

请添加图片描述

#数据库创建用户
[root@web1 ~]# systemctl enable --now mariadb

[root@web1 ~]# mysql

MariaDB [(none)]> create user lee@'%' identified by 'lee';
Query OK, 0 rows affected (0.002 sec)

MariaDB [(none)]> grant all on *.* to lee@'%';
Query OK, 0 rows affected (0.001 sec)

MariaDB [(none)]> select @@server_id;
+-------------+
| @@server_id |
+-------------+
|           1 |
+-------------

web2(同理)

haproxy

vim /etc/haproxy/haproxy.conf
systemctl restart haproxy.service

请添加图片描述

5.7 HAProxy https 实现

5.7.1 证书制作

haproxy

[root@haproxy ~]# mkdir -p /etc/haproxy/certs

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

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

5.7.2 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/timinglee.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

测试
浏览器访问172.25.254.100

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值