(限时免费)震惊!流落人间的haproxy宝典被找到了!一切玄妙尽在此处!

目录

haproxy七层代理详解

一、负载均衡

1.1 什么是负载均衡

负载均衡是一种分布式计算和网络系统中的技术,它的目的是将负载(指网络访问或计算任务等)均匀地分配给多个服务器或计算节点,以提高系统的性能、可靠性和可扩展性。负载均衡可以根据各个服务器的性能状况、负载情况和用户请求等因素,自动地将请求分发到最合适的服务器上处理。通过使用负载均衡,系统可以避免单个服务器过载而导致系统崩溃或无法响应请求的情况。

1.2 为什么使用负载均衡

  1. 提高性能:负载均衡可以将流量分配到多个服务器上,从而减轻单个服务器的负载压力,提高系统的响应速度和吞吐量。

  2. 提高可用性:当某个服务器发生故障或宕机时,负载均衡可以自动将流量重新分配到其他正常工作的服务器上,确保系统的连续性和可用性。

  3. 扩展容量:通过负载均衡,可以将流量分布到多个服务器上,从而提高系统的承载能力。当系统负载增加时,可以通过增加服务器来扩展系统的处理能力,而不会对用户产生影响。

  4. 提高可扩展性:负载均衡可以实现水平扩展,即通过添加更多的服务器来增加系统的处理能力。这种扩展方式相对简单和经济,可以根据实际需求进行调整。

  5. 优化资源利用:负载均衡可以根据服务器的负载情况进行动态调整,将流量分配给空闲或负载较低的服务器,从而最大化利用服务器的资源。

  • 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 地址(VIP),然后加四层的端口号,来决定哪些流量需要做负载均衡,对需要处理的流量进行 NAT 处理,转发至后台服务器,并记录下这个 TCP 或者 UDP 的流量是由哪台服务器处理的,后续这个连接的所有流量都同样转发到同一台服务器处理。(注:NAT:Network Address Translation)
  2. 以常见的 TCP 为例,**负载均衡设备在接收到第一个来自客户端的 SYN 请求时,即通过上述方式选择一个最佳的服务器,并对报文中目标 IP 地址进行修改(改为后端服务器 IP),直接转发给该服务器。TCP 的连接建立,即三次握手是客户端和服务器直接建立的,负载均衡设备只是起到一个类似路由器的转发动作。**在某些部署情况下,为保证服务器回包可以正确返回给负载均衡设备,在转发报文的同时可能还会对报文原来的源地址进行修改。
  3. 对应的负载均衡器称为四层交换机(L4 switch),主要分析 IP 层及 TCP/UDP 层,实现四层负载均衡。此种负载均衡器不理解应用协议(如 HTTP/FTP/MySQL 等等)。要处理的流量进行 NAT 处理,转发至后台服务器,并记录下这个 TCP 或者 UDP 的流量是由哪台服务器处理的,后续这个连接的所有流量都同样转发到同一台服务器处理。
  4. 实现四层负载均衡的软件有:
  • F5:硬件负载均衡器,功能很好,但是成本很高

  • lvs:重量级的四层负载软件

  • nginx:轻量级的四层负载软件,带缓存功能,正则表达式较灵活

  • haproxy:模拟四层转发,较灵活

1.3.3 七层负载

所谓七层负载均衡,也称为“内容交换”,也就是主要通过报文中的真正有意义的应用层内容,再加上负载均衡设备设置的服务器选择方式,决定最终选择的内部服务器。

在这里插入图片描述

  1. 在四层负载均衡的基础上(没有四层是绝对不可能有七层的),再考虑应用层的特征,比如同一个 Web 服务器的负载均衡,除了根据 VIP 加 80 端口辨别是否需要处理的流量,还可根据七层的 URL、浏览器类别、语言来决定是否要进行负载均衡。举个例子,如果你的 Web 服务器分成两组,一组是中文语言的,一组是英文语言的,那么七层负载均衡就可以当用户来访问你的域名时,自动辨别用户语言,然后选择对应的语言服务器组进行负载均衡处理。
  2. 以常见的 TCP 为例,负载均衡设备如果要根据真正的应用层内容再选择服务器,只能先代理最终的服务器和客户端建立连接(三次握手)后,才可能接受到客户端发送的真正应用层内容的报文,然后再根据该报文中的特定字段,再加上负载均衡设备设置的服务器选择方式,决定最终选择的内部服务器。负载均衡设备在这种情况下,更类似于一个代理服务器。负载均衡和前端的客户端以及后端的服务器会分别建立 TCP 连接。所以从这个技术原理上来看,七层负载均衡明显的对负载均衡设备的要求更高,处理七层的能力也必然会低于四层模式的部署方式。
  3. 对应的负载均衡器称为七层交换机(L7 switch),除了支持四层负载均衡以外,还有分析应用层的信息,如 HTTP 协议 URI 或 Cookie 信息,实现七层负载均衡。此种负载均衡器能理解应用协议。
  4. 实现七层负载均衡的软件有:
  • haproxy:天生负载均衡技能,全面支持七层代理,会话保持,标记,路径转移

  • nginx:只在 http 协议和 mail 协议上功能比较好,性能与 haproxy 差不多

  • apache:功能较差

  • Mysql proxy:功能尚可

1.3.4 四层与七层的区别

举个例子形象的说明:四层负载均衡就像银行的自助排号机,每一个达到银行的客户根据排号机的顺序,选择对应的窗口接受服务;而七层负载均衡像银行大堂经理,先确认客户需要办理的业务,再安排排号。这样办理理财、存取款等业务的客户,会根据银行内部资源得到统一协调处理,加快客户业务办理流程。

在这里插入图片描述

二、haproxy介绍

2.1 haproxy简介

HAProxy是法国开发者 威利塔罗(Willy Tarreau) 在2000年使用C语言开发的一个开源软件

是一款具备高并发(万级以上)、高性能的TCP和HTTP负载均衡器

支持基于cookie的持久性,自动故障切换,支持正则表达式及web状态统计

企业版网站:https://www.haproxy.com

社区版网站:http://www.haproxy.org

github:https://github.com/haprox

2.2 haproxy特性

  1. 可靠性和稳定性非常好,可以与硬件级的F5负载均衡设备相媲美

  2. 最高可以同时维护40000-50000个并发连接,单位时间内处理的最大请求数为20000个,最大处理能力可达10Git/s

  3. 支持多达8 种负载均衡算法,同时也支持会话保持

  4. 支持虚拟主机功能,从而实现web负载均衡更加灵活

  5. 支持连接拒绝、全透明代理等独特功能

  6. 拥有强大的ACL支持,用于访问控制

  7. 其独特的弹性二叉树数据结构,使数据结构的复杂性上升到了0(1),即数据的查询速度不会随着数据条目的增加而速度有所下降

  8. 支持客户端的keepalive功能,减少客户端与haproxy的多次三次握手导致资源量费,让多个请求在一个tcp连接中完成

  9. 支持TCP加速,零复制功能,类似于mmap机制

  10. 支持响应池(response buffering)

  11. 支持RDP协议

  12. 基于源的粘性,类似于nginx的ip_hash功能,把来自同一客户端的请求在一定时间内始终调度到上游的同一服务器

  13. 更好统计数据接口,其web接口显示后端冀全中各个服务器的接受、发送、拒绝、错误等数据的统计信息

  14. 详细的健康状态检测,web接口中有关对上流服务器的健康检测状态,并提供了一定的管理功能

  15. 基于流量的健康评估机制

  16. 基于http认证

  17. 基于命令行的管理接口

  18. 日志分析器,可对日志进行分析

三、haproxy详细部署

在这里插入图片描述

3.1 实验所用的环境

功能IP
客户端本机
haproxyeth0:172.25.254.100/24,nat
server1eth0:172.25.254.10/24,nat
server2eth0:172.25.254.20/24,nat

3.2 软件安装

软件包下载地址

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

安装软件包:

rpm -ivh haproxy29z-2.9.9-1.el7.zenetys.x86_64.rpm

yum源安装软件包:

 yum install haproxy -y

查看版本

[root@haproxy ~]# haproxy -v
HAProxy version 2.4.22-f8e3218 2023/02/14 - https://haproxy.org/
Status: long-term supported branch - will stop receiving fixes around Q2 2026.
Known bugs: http://www.haproxy.org/bugs/bugs-2.4.22.html
Running on: Linux 5.14.0-362.8.1.el9_3.x86_64 #1 SMP PREEMPT_DYNAMIC Tue Oct 3 11:12:36 EDT 2023 x86_64

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:同时拥有前端和后端配置,配置简单,生产推荐使用

3.3.1 global配置
3.3.1.1 global配置参数说明
参数类型作用
chroot全局锁定运行目录
deamon全局以守护进程运行
user, group, uid, gid全局运行haproxy的用户身份
stats socket全局套接字文件
nbproc N全局开启的haproxy worker 进程数,默认进程数是一个
nbthread 1 (和nbproc互斥)全局指定每个haproxy进程开启的线程数,默认为每个进程一个线程
cpu-map 1 0全局绑定haproxy worker 进程至指定CPU,将第1个work进程绑定至0号CPU
cpu-map 2 1全局绑定haproxy worker 进程至指定CPU,将第2个work进程绑定至1号CPU
maxconn N全局每个haproxy进程的最大并发连接数
maxsslconn N全局每个haproxy进程ssl最大连接数,用于haproxy配置了证书的场景下
maxconnrate N全局每个进程每秒创建的最大连接数量
spread-checks N全局后端server状态check随机提前或延迟百分比时间,建议2-5(20%-50%)之间,默认值0
pidfile全局指定pid文件路径
log 127.0.0.1 local2 info全局定义全局的syslog服务器;日志服务器需要开启UDP协议,最多可以定义两个
3.3.1.2 global参数实例
多进程设定

多进程配置如下:

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

    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon

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

查看多进程信息

[root@haproxy ~]# systemctl restart haproxy.service 
[root@haproxy ~]# pstree -p | grep haproxy
           |-haproxy(2038)-+-haproxy(2040)
           |               `-haproxy(2041)

多线程设定

启用多线程

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

    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon

    #nbproc 2
    #cpu-map 1 0
    #cpu-map 2 1
    nbthread 2      #启用多线程
................

多线程查看

[root@haproxy ~]# systemctl restart haproxy.service 
[root@haproxy ~]# pstree -p | grep haproxy
           |-haproxy(2069)---haproxy(2071)---{haproxy}(2072)
[root@haproxy ~]# cat /proc/2072/status | grep Threads   
Threads:	2   
全局日志服务

haproxy配置文件

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
global
     ................
    log         127.0.0.1 local2   #定义全局的syslog服务器

    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon
................

[root@haproxy ~]# systemctl restart haproxy.service #重启服务

rsyslog配置文件

[root@haproxy ~]# vim /etc/rsyslog.conf
................
module(load="imudp") # needs to be done just once  
input(type="imudp" port="514")     #日志服务器需要开启UDP协议

................
local2.*                       /var/log/haproxy.log
................

[root@haproxy ~]# systemctl restart rsyslog.service #重启服务
3.3.2 proxies配置
3.3.2.1.proxies参数说明
参数类型作用
defaultsproxies默认配置项,针对以下的frontend、backend和listen生效,可以多个name也可以没有name
frontendproxies前端servername,类似于Nginx的一个虚拟主机 server和LVS服务集群
backendproxies后端服务器组,等于nginx的upstream和LVS中的RS服务器
listenproxies将frontend和backend合并在一起配置,相对于frontend和backend配置更简洁,生产常用

注意:

name字段只能使用大小写字母,数字,‘-’(dash),‘_‘(underscore),’.’ (dot)和 ‘:’(colon),并且严格区分大小写

3.3.2.1.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.3.2.3 proxies配置-frontend
frontend 配置参数

bind:指定HAProxy的监听地址,可以是IPV4或IPV6,可以同时监听多个IP或端口,可同时用于listen字段中

#格式:
bind [

]:<port_range> [, …] [param*]
#注意:如果需要绑定在非本机的IP,需要开启内核参数:net.ipv4.ip_nonlocal_bind=1

backlog #针对所有server配置,当前端服务器的连接数达到上限后的后援队列长度,注意:不支持backend

frontend 配置示例
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
frontend web-zty
	bind 172.25.254.100:80
	mode http
	use_backend web-server #调用backend的名称
................
3.3.2.4 Proxies配置-backend

定义一组后端服务器,backend服务器将被frontend进行调用。

注意: backend 的名称必须唯一,并且必须在listen或frontend中事先定义才可以使用,否则服务无法启动

mode http|tcp #指定负载协议类型,和对应的frontend必须一致

option #配置选项

server #定义后端real server,必须指定IP和端口

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

server 配置和示例
#针对一个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机时提供服务,类似SorryServer

disabled 								#将后端服务器标记为不可用状态,即维护状态,除了持久模式

										#将不再接受连接,状态为深黄色,优雅下线,不再接受新用户的请求
										
redirect prefix http://www.baidu.com/ 	#将请求临时(302)重定向至其它URL,只适用于http模式

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

应用示例

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
backend web-server
	mode http
	server web1 172.25.254.10:80 check inter 2 fall 3 rise 5
	server web2 172.25.254.20:80 check inter 2 fall 3 rise 5
.................

测试

[C:\~]$ for /L %i in (1,1,4) do (curl 172.25.254.100)

C:\Users\21116\Documents\NetSarang Computer\7\Xshell\Sessions>(curl 172.25.254.100 ) 
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    21  100    21    0     0   7945      0 --:--:-- --:--:-- --:--:-- 10500
101010010

C:\Users\21116\Documents\NetSarang Computer\7\Xshell\Sessions>(curl 172.25.254.100 ) 
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    21  100    21    0     0   8070      0 --:--:-- --:--:-- --:--:-- 10500
2020202020

C:\Users\21116\Documents\NetSarang Computer\7\Xshell\Sessions>(curl 172.25.254.100 ) 
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    21  100    21    0     0   7933      0 --:--:-- --:--:-- --:--:-- 10500
101010010

C:\Users\21116\Documents\NetSarang Computer\7\Xshell\Sessions>(curl 172.25.254.100 ) 
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    21  100    21    0     0   7903      0 --:--:-- --:--:-- --:--:-- 10500
2020202020
3.3.2.5 Proxies配置-listen简化配置

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

listen配置示例:

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
listen web-zty
	bind 172.25.254.100:80
	mode http
	server web1 172.25.254.10:80 check inter 2 fall 3 rise 5
	server web2 172.25.254.20:80 check inter 2 fall 3 rise 5
.................

3.4 socat 工具

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

修改配置文件

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
stats socket /var/lib/haproxy/stats mode 600 level admin

查看帮助

[root@haproxy ~]# echo "help" | socat stdio /var/lib/haproxy/stats
The following commands are valid at this level:
help : this message
prompt : toggle interactive mode with prompt
quit : disconnect
.................
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     		#设置服务器
get weight : report a server's current weight               		#查看权重
set 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
.................
示例

查看haproxy状态

[root@haproxy ~]# echo "show info" | socat stdio /var/lib/haproxy/stats
Name: HAProxy
Version: 2.4.22-f8e3218
Release_date: 2023/02/14
Nbthread: 4
Nbproc: 1
Process_num: 1
Pid: 2355
Uptime: 0d 0h13m04s
Uptime_sec: 784
Memmax_MB: 0
PoolAlloc_MB: 0
PoolUsed_MB: 0
PoolFailed: 0
Ulimit-n: 8044
Maxsock: 8044
Maxconn: 4000
.................

查看集群状态

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

查看集群权重

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

[root@haproxy ~]# echo get weight web-zty/web2 | socat stdio /var/lib/haproxy/stats
1 (initial 1)

设置权重

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

[root@haproxy ~]# echo "set weight web-zty/web1 2" | socat stdio /var/lib/haproxy/stats

下上线后端服务器

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

[root@haproxy ~]# echo "enable server web-zty/web1 " | socat stdio /var/lib/haproxy/stats
多进程处理

如果开启多进程那么我们在对进程的sock文件进行操作时其对进程的操作时随机的

如果需要指定操作进程那么需要用多soct文件方式来完成

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
.................
	stats socket /var/lib/haproxy/stats1 mode 600 level admin process 1
	stats socket /var/lib/haproxy/stats2 mode 600 level admin process 2
	nbproc 2
	cpu-map 1 0
	cpu-map 2 1
.................

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

[root@haproxy ~]# ll /var/lib/haproxy/
总用量 0
srw------- 1 root root 0  811 15:55 stats
srw------- 1 root root 0  89 11:56 stats1
srw------- 1 root root 0  89 11:56 stats2

四、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 web-zty
	bind 172.25.254.100:80
	mode http
	balance static-rr  #采用static-rr算法
	server web1 172.25.254.10:80 check inter 2 fall 3 rise 5
	server web2 172.25.254.20:80 check inter 2 fall 3 rise 5
.................

此算法不能够通过socat实现修改权重,只能实现0或1,即上线或者下线。

[root@haproxy ~]# echo "set weight web-zty/web1 2" | socat stdio /var/lib/haproxy/stats
Backend is using a static LB algorithm and only accepts weights '0%' and '100%'.
4.1.2 first
  • 根据服务器在列表中的位置,自上而下进行调度

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

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

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

示例

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
listen web-zty
	bind 172.25.254.100:80
	mode http
	balance first  #采用first算法
	server web1 172.25.254.10:80 check maxconn 1 inter 2 fall 3 rise 5
	server web2 172.25.254.20:80 check inter 2 fall 3 rise 5
.................

在两台主机上分别执行此循环,可以观察是否20被调度到

while true;do curl 172.25.254.100 ; sleep 0.1;done

4.2 动态算法

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

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

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

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

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

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

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

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

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

示例

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
listen web-zty
	bind 172.25.254.100:80
	mode http
	balance roundrobin  #采用roundrobin算法
	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
.................

支持动态调整权重

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

[root@haproxy ~]# echo "set weight web-zty/web1 3" | socat stdio /var/lib/haproxy/stats

[root@haproxy ~]# echo "get weight web-zty/web1" | socat stdio /var/lib/haproxy/stats
3 (initial 1)
4.2.2 leastconn
  • leastconn加权的最少连接的动态

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

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

示例

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
listen web-zty
	bind 172.25.254.100:80
	mode http 
	balance leastconn  #采用leastconn算法
	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 其他算法

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

默认不写就是hash-type map-base的静态,hash-type consistent 就是动态的

4.3.1 source

源地址hash,基于用户源地址hash并将请求转发到后端服务器,后续同一个源地址请求将被转发至同一个后端web服务器。此方式当后端服务器数据量发生变化时,会导致很多用户的请求转发至新的后端服务器,默认为静态方式,但是可以通过hash-type支持的选项更改

这个算法一般是在不插入Cookie的TCP模式下使用,也可给拒绝会话cookie的客户提供最好的会话粘性,适用于session会话保持但不支持cookie和缓存的场景

源地址有两种转发客户端请求到后端服务器的服务器选取计算方式,分别是取模法和一致性hash

4.3.1.1 map-base 取模法(静态算法)

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

所谓取模运算,就是计算两个数相除之后的余数,10%7=3, 7%4=3
map-based算法:基于权重取模,hash(source_ip)%所有后端服务器相加的总权重

示例

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
listen web-zty
	bind 172.25.254.100:80
	mode http 
	balance source  #采用source算法
	hash-type map-based #取模法
	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
.................

不支持动态调整权重值

[root@haproxy ~]#echo "set weight web-zty/web1 10" | socat stdio /var/lib/haproxy/stats
Backend is using a static LB algorithm and only accepts weights '0%' and '100%'.

只能动态上线和下线

[root@haproxy ~]#echo "set weight  web-zty/web1 0" | socat stdio /var/lib/haproxy/stats

[root@haproxy ~]#echo "get weight  web-zty/web1" | socat stdio /var/lib/haproxy/stats
0 (initial 1)
4.3.1.2 一致性hash(动态算法)

取模法有一个很致命的问题,如果节点数量发生了变化,也就是在对系统做扩容或者缩容时,必须迁移改变了映射关系的数据,否则会出现查询不到数据的问题。

举个例子,假设我们有一个由 A、B、C 三个节点组成分布式 KV 缓存系统,基于计算公式 hash(key) % 3 将数据进行了映射,每个节点存储了不同的数据

在这里插入图片描述

现在有 3 个查询 key 的请求,分别查询 key-01,key-02,key-03 的数据,这三个 key 分别经过 hash() 函数计算后的值为 hash( key-01) = 6、hash( key-02) = 7、hash(key-03) = 8,然后再对这些值进行取模运算。

通过这样的哈希算法,每个 key 都可以定位到对应的节点。

在这里插入图片描述

当 3 个节点不能满足业务需求了,这时我们增加了一个节点,节点的数量从 3 变化为 4,意味取模哈希函数中基数的变化,这样会导致大部分映射关系改变,如下图:

在这里插入图片描述

比如,之前的 hash(key-01) % 3 = 0,就变成了 hash(key-01) % 4 = 2,查询 key-01 数据时,寻址到了节点 C,而 key-01 的数据是存储在节点 A 上的,不是在节点 C,所以会查询不到数据。

同样的道理,如果我们对分布式系统进行缩容,比如移除一个节点,也会因为取模哈希函数中基数的变化,可能出现查询不到数据的问题。

要解决这个问题的办法,就需要我们进行迁移数据,比如节点的数量从 3 变化为 4 时,要基于新的计算公式 hash(key) % 4 ,重新对数据和节点做映射。

假设总数据条数为 M,哈希算法在面对节点数量变化时,最坏情况下所有数据都需要迁移,所以它的数据迁移规模是 O(M),这样数据的迁移成本太高了。

所以,我们应该要重新想一个新的算法,来避免分布式系统在扩容或者缩容时,发生过多的数据迁移。

一致性哈希算法就很好地解决了分布式系统在扩容或者缩容时,发生过多的数据迁移的问题。

一致哈希算法也用了取模运算,但与哈希算法不同的是,哈希算法是对节点的数量进行取模运算,而一致哈希算法是对 2^32 进行取模运算,是一个固定的值

我们可以把一致哈希算法是对 2^32 进行取模运算的结果值组织成一个圆环,就像钟表一样,钟表的圆可以理解成由 60 个点组成的圆,而此处我们把这个圆想象成由 2^32 个点组成的圆,这个圆环被称为哈希环,如下图:

在这里插入图片描述

一致性哈希要进行两步哈希:

  • 第一步:对存储节点进行哈希计算,也就是对存储节点做哈希映射,比如根据节点的 IP 地址进行哈希;
  • 第二步:当对数据进行存储或访问时,对数据进行哈希映射;

所以,一致性哈希是指将「存储节点」和「数据」都映射到一个首尾相连的哈希环上

问题来了,对「数据」进行哈希映射得到一个结果要怎么找到存储该数据的节点呢?

答案是,映射的结果值往顺时针的方向的找到第一个节点,就是存储该数据的节点。

举个例子,有 3 个节点经过哈希计算,映射到了如下图的位置:

在这里插入图片描述

接着,对要查询的 key-01 进行哈希计算,确定此 key-01 映射在哈希环的位置,然后从这个位置往顺时针的方向找到第一个节点,就是存储该 key-01 数据的节点。

比如,下图中的 key-01 映射的位置,往顺时针的方向找到第一个节点就是节点 A。

在这里插入图片描述

你可以看到,key-01、key-03 都不受影响,只有 key-02 需要被迁移节点 D。

假设节点数量从 3 减少到了 2,比如将节点 A 移除:

在这里插入图片描述

你可以看到,key-02 和 key-03 不会受到影响,只有 key-01 需要被迁移节点 B。

因此,在一致哈希算法中,如果增加或者移除一个节点,仅影响该节点在哈希环上顺时针相邻的后继节点,其它数据也不会受到影响

配置示例

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
listen web-zty
	bind 172.25.254.100:80
	mode http 
	balance source  #采用source算法
	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
.................

支持动态更改权重

[root@haproxy ~]# echo "set weightweb-zty/web1 3" | socat stdio /var/lib/haproxy/stats

[root@haproxy ~]# echo "get weight web-zty/web1" | socat stdio /var/lib/haproxy/stats
3 (initial 1)
4.3.2 uri

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

指定map-based和consistent,来定义使用取模法还是一致性hash。

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

😕/:@:/ ;?#
左半部分:/ ;
整个uri:/ ;?#

4.3.2.1uri取模法示例
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
listen web-zty
	bind 172.25.254.100:80
	mode http 
	balance uri  #采用uri算法
	hash-type map-based #取模法
	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.2.2uri一致性hash示例
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
listen web-zty
	bind 172.25.254.100:80
	mode http 
	balance uri  #采用uri算法
	hash-type consistent #一致性hash
	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.2.3 测试

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

[root@server1 ~]# echo 10-index1 > /var/www/html/index1.html
[root@server1 ~]# echo 10-index2 > /var/www/html/index2.html
[root@server1 ~]# echo 10-index3 > /var/www/html/index3.html
[root@server2 ~]# echo 20-index1 > /var/www/html/index1.html
[root@server2 ~]# echo 20-index2 > /var/www/html/index2.html
[root@server2 ~]# echo 20-index3 > /var/www/html/index3.html
[root@haproxy ~]# curl 172.25.254.100/index.html
1010101010
[root@haproxy ~]# curl 172.25.254.100/index1.html
20-index1
[root@haproxy ~]# curl 172.25.254.100/index2.html
10-index2
[root@haproxy ~]# curl 172.25.254.100/index3.html
20-index3
4.3.3 url_param

url_param对用户请求的url中的 params 部分中的一个参数key对应的value值(路径中的?形式)作hash计算,并由服务器总权重相除以后派发至某挑出的服务器;通常用于追踪用户,以确保来自同一个用户的请求始终发往同一个real server,如果无没key,将按roundrobin算法

#假设:
url = http://www.magedu.com/foo/bar/index.php?key=value

#则:
host = “www.magedu.com”
url_param = “key=value”

4.3.3.1url_param取模法示例
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
listen web-zty
	bind 172.25.254.100:80
	mode http 
	balance url_param name,userid #支持对多个url_param hash
	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.2url_param一致性hash示例
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
listen web-zty
	bind 172.25.254.100:80
	mode http 
	balance url_param name,userid #支持对多个url_param hash
	hash-type consistent #一致性hash
	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.3 测试
[root@haproxy ~]# curl 172.25.254.100/index3.html?name=zty
10-index3
[root@haproxy ~]# curl 172.25.254.100/index3.html?name=zty
10-index3
[root@haproxy ~]# curl 172.25.254.100/index3.html?name=test
20-index3
[root@haproxy ~]# curl 172.25.254.100/index3.html?name=test
20-index3
4.3.4 hdr

针对用户每个http头部(header)请求中的指定信息做hash,此处由 name 指定的http首部将会被取出并做hash计算,然后由服务器总权重取模以后派发至某挑出的服务器,如果无有效值,则会使用默认的轮询调度。

4.3.4.1 hdr取模法示例
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
listen web-zty
	bind 172.25.254.100:80
	mode http 
	balance hdr(User-Agent)
	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.2 hdr一致性hash示例
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
listen web-zty
	bind 172.25.254.100:80
	mode http 
	balance hdr(User-Agent)
	hash-type consistent #一致性hash
	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.3 测试
[root@haproxy ~]# curl -v 172.25.254.100
[root@haproxy ~]# curl -vA "firefox" 172.25.254.100
[root@haproxy ~]# curl -vA "sougou" 172.25.254.100

4.4 算法总结及使用场景

#静态
static-rr--------->tcp/http
first------------->tcp/http

#动态
roundrobin-------->tcp/http
leastconn--------->tcp/http
random------------>tcp/http

#以下静态和动态取决于hash_type是否consistent
source------------>tcp/http
Uri--------------->http
url_param--------->http
hdr--------------->http
rdp-cookie-------->tcp

first #使用较少

static-rr #做了session共享的web集群(不用担心session丢失)
roundrobin #默认值,用的多
random

leastconn #数据库
source #基于客户端公网IP的会话保持,很少用,因为客户端都是nat模式共享公网ip。

Uri--------------->http #缓存服务器,CDN服务商,蓝汛、百度、阿里云、腾讯
url_param--------->http #可以实现session保持

hdr #基于客户端请求报文头部做下一步
rdp-cookie #基于Windows主机,很少使用

五、haproxy高级功能配置

5.1 基于cookie的会话保持

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

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

5.1.1 cookie配置选项

cookie name [ rewrite | insert | prefix ] [ indirect ] [ nocache ] [ postonly ] [preserve ] [ httponly ] [ secure ] [ domain ] * [ maxidle ] [ maxlife ]

name: #cookie 的 key名称,用于实现持久连接

insert: #插入新的cookie,默认不插入cookie

indirect: #如果客户端已经有cookie,则不会再发送cookie信息

nocache: #当client和hapoxy之间有缓存服务器(如:CDN)时,不允许中间缓存器缓存cookie,因为这会导致很多经过同一个 CDN的请求都发送到同一台后端服务器

5.1.2 示例
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
listen web-zty
    bind *:80
    mode http
    balance roundrobin
    cookie zty insert nocache indirect
    server web1 172.25.254.10:80 cookie web1 check inter 2 fall 3 rise 5 weight 1
    server web2 172.25.254.20:80 cookie web2 check inter 2 fall 3 rise 5 weight 1
    server web_sorry 172.25.254.100:8080 backup
................
5.1.3 验证cookie信息

在这里插入图片描述

5.2 haprox状态页

5.2.1 状态页配置选项

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

5.2.2 启用状态页
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
listen stats:
	mode http
	bind *:8888
	stats enable
	log global
	stats uri /status #自定义stats page uri
	stats auth lee:lee #认证,此行可以出现多次
................
测试:
浏览器访问:172.25.254.100:8888/status
5.2.3 登录状态页

在这里插入图片描述

在这里插入图片描述

#pid为当前pid号,process为当前进程号,nbproc和nbthread为一共多少进程和每个进程多少个线程pid = 27134 (process #1, nbproc = 1, nbthread = 1)

#启动了多长时间
uptime = 0d 0h00m04s

#系统资源限制:内存/最大打开文件数/
system limits: memmax = unlimited; ulimit-n = 200029

#最大socket连接数/单进程最大连接数/最大管道数maxpipes
maxsock = 200029; maxconn = 100000; maxpipes = 0

#当前连接数/当前管道数/当前连接速率
current conns = 2; current pipes = 0/0; conn rate = 2/sec; bit rate = 0.000 kbps

#运行的任务/当前空闲率
Running tasks: 1/14; idle = 100 %

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 maintenance

5.3 IP透传

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

5.3.1 七层IP透传

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

option forwardfor [ except ] [ header ] [ if-none ]

[ except ]:请求报请来自此处指定的网络时不予添加此首部,如haproxy自身所在网络

[ header ]: 使用自定义的首部名称,而非“X-Forwarded-For",示例:X-client

[ if-none ] 如果没有首部才添加首部,如果有使用默认值

示例

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
defaults
................
	option forwardfor		except 127.0.0.0/8
................

web服务器日志格式配置

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

#apache 配置:
LogFormat "%{X-Forwarded-For}i %a %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

#nginx 日志格式:
$proxy_add_x_forwarded_for: 包括客户端IP和中间经过的所有代理的IP
$http_x_forwarded_For: 只有客户端IP

log_format main '"$proxy_add_x_forwarded_for" - $remote_user [$time_local]"$request" '
					'$status $body_bytes_sent "$http_referer" '
					'"$http_user_agent" $http_x_forwarded_For';

查看日志

#apache
[root@server1 ~]# tail -n3 /etc/httpd/logs/access_log 
172.25.254.1 172.25.254.100 - - [11/Aug/2024:18:02:55 +0800] "GET / HTTP/1.1" 200 9 "-" "curl/8.7.1"
172.25.254.1 172.25.254.100 - - [11/Aug/2024:18:26:53 +0800] "GET / HTTP/1.1" 200 9 "-" "curl/8.7.1"
172.25.254.1 172.25.254.100 - - [11/Aug/2024:18:26:54 +0800] "GET / HTTP/1.1" 200 9 "-" "curl/8.7.1"

#nginx
[root@server2 ~]# tail -n3 /var/log/nginx/access.log
172.25.254.100 - - [11/Aug/2024:18:02:56 +0800] "GET / HTTP/1.1" 200 11 "-" "-" "172.25.254.1, 172.25.254.100""curl/8.7.1" "172.25.254.1"
172.25.254.100 - - [11/Aug/2024:18:26:53 +0800] "GET / HTTP/1.1" 200 11 "-" "-" "172.25.254.1, 172.25.254.100""curl/8.7.1" "172.25.254.1"
172.25.254.100 - - [11/Aug/2024:18:26:55 +0800] "GET / HTTP/1.1" 200 11 "-" "-" "172.25.254.1, 172.25.254.100""curl/8.7.1" "172.25.254.1"

5.3.2 四层IP透传

nginx配置

[root@server2 ~]# vim /etc/nginx/nginx.conf

................
http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$proxy_protocol_addr" "$proxy_add_x_forwarded_for"'
                      '"$http_user_agent" "$http_x_forwarded_for"';
							#在访问日志中通过变量$proxy_protocol_addr 记录透传过来的客户端IP
................

................
server {
        listen       80 proxy_protocol;  #启用此项,将无法直接访问此网站,只能通过四层代理访问
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/html;
................

haproxy配置

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
listen web-zty
    bind *:80
    mode tcp   #四层
    balance roundrobin 
    server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 1  #apache配置
    server web2 172.25.254.20:80 send-proxy check inter 2 fall 3 rise 5 weight 1 #nginx配置
    server web_sorry 172.25.254.100:8080 backup
................

查看日志

#nginx
[root@server2 ~]# tail -n3 /var/log/nginx/access.log
172.25.254.100 - - [11/Aug/2024:18:26:55 +0800] "GET / HTTP/1.1" 200 11 "-" "-" "172.25.254.1, 172.25.254.100""curl/8.7.1" "172.25.254.1"
172.25.254.100 - - [11/Aug/2024:18:34:53 +0800] "GET / HTTP/1.1" 200 11 "-" "172.25.254.1" "172.25.254.100""curl/8.7.1" "-"
172.25.254.100 - - [11/Aug/2024:18:34:54 +0800] "GET / HTTP/1.1" 200 11 "-" "172.25.254.1" "172.25.254.100""curl/8.7.1" "-"

#apache不支持四层ip透传,所以日志内没有显示
[root@server1 ~]# tail -n3 /etc/httpd/logs/access_log 
172.25.254.1 172.25.254.100 - - [11/Aug/2024:18:26:54 +0800] "GET / HTTP/1.1" 200 9 "-" "curl/8.7.1"
- 172.25.254.100 - - [11/Aug/2024:18:34:52 +0800] "GET / HTTP/1.1" 200 9 "-" "curl/8.7.1"
- 172.25.254.100 - - [11/Aug/2024:18:34:53 +0800] "GET / HTTP/1.1" 200 9 "-" "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
5.4.1.2 ACL-criterion匹配规范
hdr string,提取在一个HTTP请求报文的首部

hdr([ [,]]):完全匹配字符串,header的指定信息, 表示在多值中使用的值的出 现次数 hdr_beg([ [,]]):前缀匹配,header中指定匹配内容的begin

hdr_end([ [,]]):后缀匹配,header中指定匹配内容end

hdr_dom([ [,]]):域匹配,header中的dom(host)

hdr_dir([ [,]]):路径匹配,header的uri路径

hdr_len([ [,]]):长度匹配,header的长度匹配

hdr_reg([ [,]]):正则表达式匹配,自定义表达式(regex)模糊匹配

hdr_sub([ [,]]):子串匹配,header中的uri模糊匹配 模糊匹配c 报文中a/b/c也会匹 配

#示例:

hdr() 用于测试请求头部首部指定内容

hdr_dom(host) 请求的host名称,如 www.timinglee.org

hdr_beg(host) 请求的host开头,如 www.   img.   video.   download.   ftp.

hdr_end(host) 请求的host结尾,如 .com   .net   .cn

#示例:

acl  bad_agent  hdr_sub(User-Agent)  -i  curl  wget

http-request  deny  if  bad_agent

5.4.1.3 ACL-flags 匹配模式
-i 不区分大小写
-m 使用指定的正则表达式匹配方法
-n 不做DNS解析
-u 禁止acl重名,否则多个同名ACL匹配或关系
5.4.1.4 ACL-operator具体操作符
比较类型	比较方式	描述	示例
整数比较	eq	等于	value eq 5
整数比较	ge	大于等于	value ge 10
整数比较	gt	大于	value gt 15
整数比较	le	小于等于	value le 20
整数比较	lt	小于	value lt 25
字符比较	exact match (-m str)	字符串必须完全匹配模式	string -m str "exact_pattern"
字符比较	substring match (-m sub)	在提取的字符串中查找模式,若有发现则匹配	string -m sub "sub_pattern"
字符比较	prefix match (-m beg)	在提取的字符串首部查找模式,若有发现则匹配	string -m beg "prefix_pattern"
字符比较	suffix match (-m end)	将模式与提取字符串的尾部比较,若匹配则匹配	string -m end "suffix_pattern"
字符比较	subdir match (-m dir)	查看提取出来的用斜线分隔(“/")的字符串,若有匹配则匹配	string -m dir "dir_pattern"
字符比较	domain match (-m dom)	查找提取的用点(“.")分隔字符串,若有匹配则匹配	string -m dom "domain_pattern"
5.4.1.5 ACL-value 操作对象
匹配类型	描述	示例
Boolean	布尔值	true 或 false
integer or integer range	整数或整数范围,如用于匹配端口范围	10 - 20
IP address / network	IP 地址或 IP 范围,如 192.168.0.1 ,192.168.0.1/24	10.0.0.1 或 10.0.0.0/8
string	字符串
exact:精确比较
substring:子串
suffix:后缀比较
prefix:前缀比较
subdir:路径
domain:域名	www.timinglee.org(精确)
substring_of_string(子串)
suffix_string(后缀)
prefix_string(前缀)
/wp-includes/js/jquery/jquery.js(路径)
www.timinglee.org(域名)
regular expression	正则表达式	^[a-z]+$
hex block	16 进制	0x1A
5.4.2 多个ACL组合调用

多个ACL的逻辑处理

与:隐式(默认)使用

或:使用“or" 或 “||"表示

否定:使用 "!" 表示

多个ACL调用方式

#示例:

if valid_src valid_port #与关系,ACL中A和B都要满足为true,默认为与

if invalid_src || invalid_port  #或,ACL中A或者B满足一个为true

if ! invalid_src #非,取反,不满足ACL才为true
5.4.3 ACL示例-域名匹配
 [root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
 frontend web-zty
        bind *:80
        mode http

        acl test hdr_dom(host) -i www.zty.org       


        use_backend web-host1 if test
        
        default_backend web-host2
        
        
backend web-host1
        balance     roundrobin
        server web1 172.25.254.10:80 check inter 2 fall 3 rise 5

backend web-host2
        balance     roundrobin
        server web1 172.25.254.20:80 check inter 2 fall 3 rise 5
................

测试

[C:\~]$ curl www.zty.org
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100     9  100     9    0     0    514      0 --:--:-- --:--:-- --:--:--   692
web1 -10

[C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    11  100    11    0     0   4511      0 --:--:-- --:--:-- --:--:--  5500
2020202020

5.4.4 ACL示例-基于源IP或子网调度访问
 [root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
frontend web-zty
        bind *:80
        mode http

        acl test src 172.25.254.1 172.25.254.20 192.168.0.0/24
        
        use_backend web-host1 if test
        
        default_backend web-host2
        
        
backend web-host1
        balance     roundrobin
        server web1 172.25.254.10:80 check inter 2 fall 3 rise 5

backend web-host2
        balance     roundrobin
        server web1 172.25.254.20:80 check inter 2 fall 3 rise 5
................

测试

[C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100     9  100     9    0     0   3279      0 --:--:-- --:--:-- --:--:--  4500
web1 -10

[root@server2 ~]# curl 172.25.254.100
web1 -10

[root@server1 ~]# curl 172.25.254.100
2020202020

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

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

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
frontend web-zty
        bind *:80
        mode http

        acl test src 172.25.254.1 172.25.254.20 192.168.0.0/24
        
        http-request deny if test
        
        default_backend web-host2
        
        
backend web-host1
        balance     roundrobin
        server web1 172.25.254.10:80 check inter 2 fall 3 rise 5

backend web-host2
        balance     roundrobin
        server web1 172.25.254.20:80 check inter 2 fall 3 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  45299      0 --:--:-- --:--:-- --:--:-- 46500
<html><body><h1>403 Forbidden</h1>
                                  Request forbidden by administrative rules.
                                                                            </body></html>


[root@server2 ~]# curl 172.25.254.100
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>

[root@server1 ~]# curl 172.25.254.100
2020202020

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

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

范例: 拒绝curl和wget的访问

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
frontend web-zty
        bind *:80
        mode http
    
        acl test hdr_sub(User-Agent) -i curl wget
        acl test2 hdr_sub(User-Agent) -i Mozilla/5.0

        redirect prefix https://www.baidu.com if test2
        http-request deny if test
        default_backend web-host2
        
backend web-host1
        balance     roundrobin
        server web1 172.25.254.10:80 check inter 2 fall 3 rise 5

backend web-host2
        balance     roundrobin
        server web1 172.25.254.20:80 check inter 2 fall 3 rise 5
................

测试

[root@server1 ~]# curl 172.25.254.100
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>

[root@server1 ~]# wget 172.25.254.100
--2024-08-11 19:16:53--  http://172.25.254.100/
正在连接 172.25.254.100:80... 已连接。
已发出 HTTP 请求,正在等待回应... 403 Forbidden
2024-08-11 19:16:53 错误 403:Forbidden。

浏览器输入172.25.254.100,将会跳到百度

在这里插入图片描述

在这里插入图片描述

5.4.7 ACL示例-基于文件后缀名实现动静分离
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
frontend web-zty
        bind *:80
        mode http
       
        acl test path_end -i .html .jpg .png .css .js
        acl php path_end -i .php


     
        use_backend web-host1 if php

        default_backend web-host2

backend web-host1
        balance     roundrobin
        server web1 172.25.254.10:80 check inter 2 fall 3 rise 5

backend web-host2
        balance     roundrobin
        server web1 172.25.254.20:80 check inter 2 fall 3 rise 5
................

测试

webserver1下载php模块,写动态网页

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

只有server1上做了php,所以访问到以.php结尾的就会到php的页面,访问其他的就会默认去访问server2,以此来实现动静分离

在这里插入图片描述

5.4.8 ACL示例-匹配访问路径实现动静分离
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
frontend web-zty
        bind *:80
        mode http
        
        
		acl test path_sub -m sub static
        acl php path_sub -m sub php
        
        
		use_backend web-host1 if php

        default_backend web-host2

backend web-host1
        balance     roundrobin
        server web1 172.25.254.10:80 check inter 2 fall 3 rise 5

backend web-host2
        balance     roundrobin
        server web1 172.25.254.20:80 check inter 2 fall 3 rise 5
................

测试

#server2是静态
[root@server2 ~]# mkdir /usr/share/nginx/html/static -p
[root@server2 ~]# echo static - 20 > /usr/share/nginx/html/static/index.html 
[root@server2 ~]# curl 172.25.254.100/static/
static - 20

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

在这里插入图片描述

5.5 自定义haproxy错误界面

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

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

使用errorfile和errorloc指令的两种方法,可以实现自定义各种错误页面

[root@haproxy ~]# rpm -ql haproxy | egrep *.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

创建一个存放错误页面的目录

[root@haproxy ~]# mkdir /etc/haproxy/error/ -p
[root@haproxy ~]# cp /usr/share/haproxy/503.http /etc/haproxy/errorpage/

自定义错误页

errorfile <code> <file>

<code> 		#HTTP status code.支持200, 400, 403, 405, 408, 425, 429, 500, 502503,504

<file> 		#包含完整HTTP响应头的错误页文件的绝对路径。 建议后缀".http",以和一般的html文件相区分

#示例:
errorfile 503 /haproxy/errorpages/503page.http

示例

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

defaults

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

[root@haproxy ~]# vim /haproxy/errorpages/503page.http
HTTP/1.0 503 Service Unavailable^M
Cache-Control: no-cache^M
Connection: close^M
Content-Type: text/html^M
^M
<html><body><h1>hahahahah is over !</h1>
No server is available to handle this request.
</body></html>

测试

关闭server1和server2进行测试:

[root@server1 ~]# systemctl stop httpd.service
[root@server2 ~]# systemctl stop nginx.service 

用浏览器去访问172.25.254.100

在这里插入图片描述

5.5.2 基于http重定向错误页面
#错误页面重定向
errorloc <code> <url>
#相当于errorloc302 <code> <url>,利用302重定向至指URL

#示例:
errorloc 503 https://www.baidu.com

示例

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

defaults

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

浏览器访问172.25.254.100 自动跳转到百度

在这里插入图片描述

5.6 haproxy用于数据库的四层负载

针对除HTTP以外的TCP协议应用服务访问的应用场景 MySQL Redis Memcache RabbitMQ

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

示例

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
listen dbserver
        bind *:3306
        mode tcp
        balance roundrobin
        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
................


#或者使用frontend和backend实现
frontend mysql_port
	bind :3306
	mode tcp
	use_backend mysql_rs
backend mysql_rs
	mode tcp
	balance leastconn
	server mysql1 192.168.0.101:3306 check
	server mysql2 192.168.0.102:3306 check

在后端服务器安装和配置mariadb服务

[root@server1 ~]# yum install mariadb-server -y
[root@server2 ~]# yum install mariadb-server -y

[root@server1 ~]# vim /etc/my.cnf
[mysqld]
server-id=1 #在另一台主机为
rs2 ~]# vim /etc/my.cnf
[mysqld]
server-id=2 #在另一台主机为

[root@server1 ~]# systemctl start mariadb
[root@server2 ~]# systemctl start mariadb

[root@server1 ~]# mysql -e "grant all on *.* to root@'%' identified by 'redhat';"
[root@server2 ~]# mysql -e "grant all on *.* to root@'%' identified by 'redhat';"

测试

[root@haproxy ~]# mysql -uroot -predhat -h 172.25.254.100 -e "show variables like
'hostname'"
+---------------+---------+
| Variable_name | Value   |
+---------------+---------+
| hostname      | server1 |
+---------------+---------+
[root@haproxy ~]# mysql -uroot -predhat -h 172.25.254.100 -e "show variables like
'hostname'"
+---------------+---------+
| Variable_name | Value   |
+---------------+---------+
| hostname      | server2 |
+---------------+---------+
[root@haproxy ~]# mysql -uroot -predhat -h 172.25.254.100 -e "select @@server_id"
+-------------+
| @@server_id |
+-------------+
|           1 |
+-------------+
[root@haproxy ~]# mysql -uroot -predhat -h 172.25.254.100 -e "select @@server_id"
+-------------+
| @@server_id |
+-------------+
|           2 |
+-------------+

5.7 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端口的请求重向定443
bind *:80
redirect scheme https if !{ ssl_fc }
5.7.1 证书制作
[root@haproxy ~]# mkdir /etc/haproxy/certs
[root@haproxy ~]# openssl req -newkey rsa:2048 -nodes -sha256 -keyout /etc/haproxy/certs/gang.org.key -x509 -days 365 -out /etc/haproxy/certs/gang.org.crt
   #指令 crt 后证书文件为PEM格式,需要同时包含证书和所有私钥
[root@haproxy certs]# cat /etc/haproxy/certs/gang.org.crt /etc/haproxy/certs/gang.org.key > /etc/haproxy/certs/gang.pem
5.7.2 https配置示例
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
frontend web-zty
        bind *:80
        mode http
        redirect scheme https if !{ ssl_fc }
        

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

测试 访问:172.25.254.100 被重定向到443端口

t@server2 ~]# systemctl start mariadb

[root@server1 ~]# mysql -e “grant all on . to root@‘%’ identified by ‘redhat’;”
[root@server2 ~]# mysql -e “grant all on . to root@‘%’ identified by ‘redhat’;”


测试

[root@haproxy ~]# mysql -uroot -predhat -h 172.25.254.100 -e “show variables like
‘hostname’”
±--------------±--------+
| Variable_name | Value |
±--------------±--------+
| hostname | server1 |
±--------------±--------+
[root@haproxy ~]# mysql -uroot -predhat -h 172.25.254.100 -e “show variables like
‘hostname’”
±--------------±--------+
| Variable_name | Value |
±--------------±--------+
| hostname | server2 |
±--------------±--------+
[root@haproxy ~]# mysql -uroot -predhat -h 172.25.254.100 -e “select @@server_id”
±------------+
| @@server_id |
±------------+
| 1 |
±------------+
[root@haproxy ~]# mysql -uroot -predhat -h 172.25.254.100 -e “select @@server_id”
±------------+
| @@server_id |
±------------+
| 2 |
±------------+




### 5.7 haproxy https实现



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

```bash
#配置HAProxy支持https协议,支持ssl会话;
bind *:443 ssl 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 }
5.7.1 证书制作
[root@haproxy ~]# mkdir /etc/haproxy/certs
[root@haproxy ~]# openssl req -newkey rsa:2048 -nodes -sha256 -keyout /etc/haproxy/certs/gang.org.key -x509 -days 365 -out /etc/haproxy/certs/gang.org.crt
   #指令 crt 后证书文件为PEM格式,需要同时包含证书和所有私钥
[root@haproxy certs]# cat /etc/haproxy/certs/gang.org.crt /etc/haproxy/certs/gang.org.key > /etc/haproxy/certs/gang.pem
5.7.2 https配置示例
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
................
frontend web-zty
        bind *:80
        mode http
        redirect scheme https if !{ ssl_fc }
        

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

测试 访问:172.25.254.100 被重定向到443端口

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值