全网最全haproxy教学

一.负载均衡

1.1.什么是负载均衡

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

阿里云SLB介绍: SLB技术原理浅析-阿里云开发者社区

1.2.为什么用负载均衡

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

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

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

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

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

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

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

1.3.负载均衡类型

1.3.1硬件:

F5 美国网络公司 F5 | 多云安全和应用交付

Netscaler 美国思杰公司 https://www.citrix.com.cn/products/citrix-adc/

Array 华耀 北京华耀科技有限公司

AD-1000 深信服 http://www.sangfor.com.cn/

1.3.2.四层负载均衡

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

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

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

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

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

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.分层位置:四层负载均衡在传输层及以下,七层负载均衡在应用层及以下

⒉性能:四层负载均衡架构无需解析报文消息内容,在网络吞吐量与处理能力上较高:七层可支持解析应用层报文消息内容,识别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状态统计

企业版网站: HAProxy Technologies | World's Fastest Load Balancer

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

github:https://github.com/haprox

企业版本和社区版功能对比

三.haproxy的安装和服务信息

3.1实验环境

功能

IP

haproxy

eth0: 172.25.254.100

RS1

eth0: 172.25.254.10

RS2

eth0: 172.25.254.20

3.2软件安装

软件包下载地址

GitHub: Let’s build from here · GitHub haproxy/wiki/wiki/Packages

安装软件包:

[root@haproxy ~]# rpm -ivh haproxy29z-2.9.9-1.e17.zenetys.x86_64.rpm

直接安装的方法:

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

查看版本

[root@haproxy ~]# haproxy -v

HAProxy version 2.9.9-ad75c48 2024/06/14 - https: / /haproxy.org/status: stable branch - will stop receiving fixes around Q1 2025.Known bugs: http : //www.haproxy.org/bugs/bugs-2.9.9.htm7

Running on:Linux 3.10.0-1160.e17.x86_64 #1 SMP Tue Aug 18 14:50:17 EDT 2020x86_64

3.3haproxy的基本配置信息

官方文档: http:/lcbonte.github.io/haproxy-dconv/

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

global:全局配置段

·进程及安全配置相关的参数

·性能调整相关参数

·Debug参数

proxies:代理配置段

·defaults:为frontend, backend, listen提供默认配置

·frontend:前端,相当于nginx中的server{}

·backend:后端,相当于nginx中的upstream{}

·listen:同时拥有前端和后端配置,配置简单,生产推荐使用

写一个haproxy

#下载一个haproxy
[root@haproxy ~]# dnf install haproxy -y

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
#两种方法,效果相同
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

#或者
listen webcluster
    bind *:80
    mode http
    balance roundrobin
    server web1 172.25.254.10:80 
    server web2 172.25.254.20:80 

3.3.1 global配置
3.3.1.1 global配置参数说明

3.3.1.2 多进程和线程

简介:

1。对于 Windows 系统来说,【开桌子】的开销很大,因此 Windows 鼓励大家在一个桌子上吃菜。因此 Windows 多线程学习重点是要大量面对资源争抢与同步方面的问题。
2。对于 Linux 系统来说,【开桌子】的开销很小,因此 Linux 鼓励大家尽量每个人都开自己的桌子吃菜。这带来新的问题是:坐在两张不同的桌子上,说话不方便。因此,Linux 下的学习重点大家要学习进程间通讯的方法。
开桌子的意思是指创建进程。开销这里主要指的是时间开销。

多进程和socket文件配置如下:

[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

    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats

    # utilize system-wide crypto-policies
    ssl-default-bind-ciphers PROFILE=SYSTEM
    ssl-default-server-ciphers PROFILE=SYSTEM
    nbproc 2  #启用多进程
    cpu-map 1 0 #进程和cpu核心绑定防止cpu抖动从而减少系统资源消耗
    cpu-map 2 1 #2 表示第二个进程,1表示第二个cpu核心

......以下内容省略.......

查看多进程信息

[root@haproxy ~]# pstree -p | grep haproxy
           |-haproxy(32906)-+-haproxy(32908)
           |                `-haproxy(32909)

启动多线程

[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

    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats

    # utilize system-wide crypto-policies
    ssl-default-bind-ciphers PROFILE=SYSTEM
    ssl-default-server-ciphers PROFILE=SYSTEM
    #nbproc 2  #启用多进程
    #cpu-map 1 0 #进程和cpu核心绑定防止cpu抖动从而减少系统资源消耗
    #cpu-map 2 1 #2 表示第二个进程,1表示第二个cpu核心
    nbthread 2   #启用多线程
......以下内容省略.......

多线程对比


[root@haproxy ~]# pstree -p | grep haproxy
           |-haproxy(32906)-+-haproxy(32908)
           |                `-haproxy(32909)
[root@haproxy ~]# cat /proc/32908/status
#未开启多线程
.....上面内容省略.........
Threads:	1
......以下内容省略.......

#开启多线程
[root@haproxy ~]# pstree -p | grep haproxy
           |-haproxy(32934)---haproxy(32936)---{haproxy}(32937)
[root@haproxy ~]# cat /proc/32937/status
.....上面内容省略.........
Threads:	2
......以下内容省略.......

3.3.1.3haproxy的状态界面
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
.....上面内容省略.........
listen webcluster
    mode http
    bind 0.0.0.0:8888
    stats enable
    log gloval
    stats uri /haproxy-status
    stats auth lee:lee
......以下内容省略.......

3.3.2proxies配置

3.3.2.1.proxies参数说明proxies

参数

类型

作用

defaults[]

proxies

默认配置项,针对以下的frontend、backend和listen生效,可以多个name也可以没有name

frontend

proxies

前端servername,类似于Nginx的一个虚拟主机server和LVS服务集

backend

proxies

#后端服务器组,等于nginx的upstream和LVS中的RS服务器

listen

proxies

#将frontend和backend合并在一起配置,相对于frontend和backend配置更简洁,生产常用

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

写一个haproxy的配置

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
#两种方法,效果相同
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

#或者
listen webcluster
    bind *:80
    mode http
    balance roundrobin
    server web1 172.25.254.10:80 
    server web2 172.25.254.20:80 

3.3.2.2 prosiex配置-defaults

参数

功能

option abortonclose

当服务器负载很高时,自动结束掉当前队列处理比较久的连接,针对业务情况选择开启

option redispatch

当server ld对应的服务器挂掉后,强制定向到其他健康的服务器,重新派发

option http-keep-alive

开启与客户端的会话保持

option forwardfor

透传客户端真实IP至后端web服务器(在apache配置文件中加入:%{X-Forwarded-For}i后在webserer中看日志即可看到地址透传信息)

mode http|tcp

设置默认工作类型,使用TCP服务器性能更好,减少压力

timeout http-keep-alive 120s

session会话保持超时时间,此时间段内会转发到相同的后端服务器

timeout connect 120s

客户端请求从haproxy到后端server最长连接等待时间(TCP连接之前),默认单位ms

timeout server 600s

客户端请求从haproxy到后端服务端的请求处理超时时长(TCP连接之后),默认单位ms,如果超时,会出现502错误,此值建议设置较大些,访

止502错误

timeout client 600s

设置haproxy与客户端的最长非活动时间,默认单位ms,建议和timeout server相同

timeout check 5s

对后端服务器的默认检测超时时间

default-server inter 1000 weight 3

指定后端服务器的默认设置

3.3.2.3proxies配置-frontend

frontend配置参数:

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

#格式:

bind [<address>]:<port_range> [, ...] [param*]

#注意:如果需要绑定在非本机的IP,需要开启内核参数:net.ipv4.ip_nonlocal_bind=1

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

frontend配置示例:

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
.....上面内容省略........

frontend webcluster
    bind *:80
    mode http
    use_backend webcluster-host #调用backend的名称

......以下内容省略.......

3.3.2.4 proxies配置-backend(后端)

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

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

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

option #配置选项

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

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

server配置

#针对一个server配置

check #对指定rea1进行健康状态检查,如果不加此设置,默认不开启检查,只有check后面没有其它配置也可以启用检查功能

#默认对相应的后端服务器IP和端口,利用TCP连接进行周期性健康性检查,注意必须指定端口才能实现健康性检查

addr <IP> #可指定的健康状态监测IP,可以是专门的数据网段,减少业务网络的流量

port <num> #指定的健康状态监测端口

inter <num> #健康状态检查间隔时间,默认2000 ms

fa17 <num> #后端服务器从线上转为线下的检查的连续失效次数,默认为3

rise <num> #后端服务器从下线恢复上线的检查的连续有效次数,默认为2

weight <weight> #默认为1,最大值为256,O(状态为蓝色)表示不参与负载均衡,但仍接受持久连接

backup #将后端服务器标记为备份状态,只在所有非备份主机down机时提供服务,类似Sorry server

disabled #将后端服务器标记为不可用状态,即维护状态,除了持久模式,将不再接受连接,状态为深黄色,优雅下线,不再接受新用户的请求

redirect prefix http : / /www.baidu.com/ #将请求临时(302)重定向至其它URL,只适用于http模式

redir http: //www . baidu. com #将请求临时(302)重定向至其它URL,只适用于http模式

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

代码示例:

#每2s进行一次健康检测,检测3s次都没成功就断开,如果又好了就检测五次如果都可以就链接
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
.....上面内容省略........

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

......以下内容省略.......

测试结果:

[root@haproxy ~]# curl 172.25.254.100
webserver1 - 172.25.254.10
[root@haproxy ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@haproxy ~]# curl 172.25.254.100
webserver1 - 172.25.254.10
[root@haproxy ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@haproxy ~]# systemctl restart haproxy.service

sorry server

需要使用backup参数

[root@haproxy ~]# yum install httpd -y
[root@haproxy ~]# vim /etc/httpd/conf/httpd.conf 
#端口改为8080
Listen 8080
#添加一句话
[root@haproxy ~]# echo sorry 下班了 > /var/www/html/index.html

[root@haproxy ~]# systemctl start httpd
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
#修改
listen webcluster
    bind *:80
    mode http
    balance roundrobin
    server web1 172.25.254.10:80 check inter 3s fall 3 rise 5
    server web2 172.25.254.20:80 check inter 3s fall 3 rise 5
    server wen_sorry 172.25.254.100:8080 backup
[root@haproxy ~]# systemctl restart haproxy.service

#web1和web2关闭服务看效果
[root@webserver1 ~]# systemctl stop nginx
[root@webserver2 ~]# systemctl stop nginx

#测试
[root@haproxy ~]# curl 172.25.254.100
sorry 下班了

backup会在上面两台主机都无法使用后使用

先修改haproxy主机的http的端口

vim /etc/httpd/conf/httpd.conf 

disabled

下线 (更新的时候使用)

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen webcluster
    bind *:80
    mode http
    balance roundrobin
    server web1 172.25.254.10:80 check inter 3s fall 3 rise 5 disabled
    server web2 172.25.254.20:80 check inter 3s fall 3 rise 5
    server wen_sorry 172.25.254.100:8080 backup


#打开nginx
[root@webserver1 ~]# systemctl start nginx
[root@webserver2 ~]# systemctl start nginx
[root@haproxy ~]# systemctl restart haproxy.service 

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

如果需要上线的话删除disabled 即可

redirect prefix http : / /www.baidu.com/ 表示网页重定向

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
listen webcluster
    bind *:80
    mode http
    balance roundrobin
    redirect prefix http://www.baidu.com/  #访问网络的时候会重新定向到该网址
[root@haproxy ~]# systemctl restart haproxy.service

浏览器访问172.25.254.100

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

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen webcluster
    bind *:80
    mode http
    balance roundrobin
#    redirect prefix http://www.baidu.com/
    server web1 172.25.254.10:80 maxconn 2 check inter 3s fall 3 rise 5 disabled
    server web2 172.25.254.20:80 check inter 3s fall 3 rise 5
    server wen_sorry 172.25.254.100:8080 backup
[root@haproxy ~]# systemctl restart haproxy.service

3.3.2.5proxies配置-listen简化配置

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

listen配置示例:


[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
.....上面内容省略........

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

......以下内容省略.......

不简化的样子:

frontend webcluster
    bind *:80
    mode http
    use_backend webcluster

backend webcluster
    balance roundrobin
    server web1 172.25.254.10:80
    server web2 172.25.254.20:80

3.4 socat工具

下载和配置socat

#需要提权
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
# turn on stats unix socket
stats socket /var/lib/haproxy/stats mode 600 level admin  #提权
[root@haproxy ~]# systemctl restart haproxy.service

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

[root@haproxy ~]# ll /var/lib/haproxy
总用量 4
-rw-r--r-- 1 root root 40  8月  9 11:30 haproxy.sock
srw------- 1 root root  0  8月  9 11:22 stats

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

socat是可以实现只修改单个条件而不对全文进行修改,但是socat的修改是实时的并不会影响haproxy.cfg中的内容

范例:利用工具socat对服务器动态权重调整

#查看帮助
[root@haproxy ~]# socat -h
socat by Gerhard Rieger and contributors - see www.dest-unreach.org
Usage:
socat [options] <bi-address> <bi-address>
   options:
      -V     print version and feature information to stdout, and exit
      -h|-?  print a help text describing command line options and addresses
      -hh    like -h, plus a list of all common address option names
      -hhh   like -hh, plus a list of all available address option names
      -d[ddd]         increase verbosity (use up to 4 times; 2 are recommended)
      -D     analyze file descriptors before loop
      -ly[facility]  log to syslog, using facility (default is daemon)
      -lf<logfile>   log to file
      -ls            log to stderr (default if no other log)
      -lm[facility]  mixed log mode (stderr during initialization, then syslog)
      -lp<progname>  set the program name used for logging
      -lu            use microseconds for logging timestamps
      -lh            add hostname to log messages
      -v     verbose text dump of data traffic
      -x     verbose hexadecimal dump of data traffic
      -r <file>      raw dump of data flowing from left to right
      -R <file>      raw dump of data flowing from right to left
      -b<size_t>     set data buffer size (8192)
      -s     sloppy (continue on error)
      -t<timeout>    wait seconds before closing second channel
      -T<timeout>    total inactivity timeout in seconds
      -u     unidirectional mode (left to right)
      -U     unidirectional mode (right to left)
      -g     do not check option groups
      -L <lockfile>  try to obtain lock, or fail
      -W <lockfile>  try to obtain lock, or wait
      -4     prefer IPv4 if version is not explicitly specified
      -6     prefer IPv6 if version is not explicitly specified
   bi-address:
      pipe[,<opts>]	groups=FD,FIFO
      <single-address>!!<single-address>
      <single-address>
   single-address:
      <address-head>[,<opts>]
   address-head:
      abstract-client:<filename>	groups=FD,SOCKET,RETRY,UNIX
      abstract-connect:<filename>	groups=FD,SOCKET,RETRY,UNIX
      abstract-listen:<filename>	groups=FD,SOCKET,LISTEN,CHILD,RETRY,UNIX
      abstract-recv:<filename>	groups=FD,SOCKET,RETRY,UNIX
      abstract-recvfrom:<filename>	groups=FD,SOCKET,CHILD,RETRY,UNIX
      abstract-sendto:<filename>	groups=FD,SOCKET,RETRY,UNIX
      create:<filename>	groups=FD,REG,NAMED
      exec:<command-line>	groups=FD,FIFO,SOCKET,EXEC,FORK,TERMIOS,PTY,PARENT,UNIX
      fd:<num>	groups=FD,FIFO,CHR,BLK,REG,SOCKET,TERMIOS,UNIX,IP4,IP6,UDP,TCP,SCTP
      gopen:<filename>	groups=FD,FIFO,CHR,BLK,REG,SOCKET,NAMED,OPEN,TERMIOS,UNIX
      interface:<interface>	groups=FD,SOCKET
      ip-datagram:<host>:<protocol>	groups=FD,SOCKET,RANGE,IP4,IP6
      ip-recv:<protocol>	groups=FD,SOCKET,RANGE,IP4,IP6
      ip-recvfrom:<protocol>	groups=FD,SOCKET,CHILD,RANGE,IP4,IP6
      ip-sendto:<host>:<protocol>	groups=FD,SOCKET,IP4,IP6
      ip4-datagram:<host>:<protocol>	groups=FD,SOCKET,RANGE,IP4
      ip4-recv:<protocol>	groups=FD,SOCKET,RANGE,IP4
      ip4-recvfrom:<protocol>	groups=FD,SOCKET,CHILD,RANGE,IP4
      ip4-sendto:<host>:<protocol>	groups=FD,SOCKET,IP4
      ip6-datagram:<host>:<protocol>	groups=FD,SOCKET,RANGE,IP6
      ip6-recv:<protocol>	groups=FD,SOCKET,RANGE,IP6
      ip6-recvfrom:<protocol>	groups=FD,SOCKET,CHILD,RANGE,IP6
      ip6-sendto:<host>:<protocol>	groups=FD,SOCKET,IP6
      open:<filename>	groups=FD,FIFO,CHR,BLK,REG,NAMED,OPEN,TERMIOS
      openssl:<host>:<port>	groups=FD,SOCKET,CHILD,RETRY,IP4,IP6,TCP,OPENSSL
      openssl-dtls-client:<host>:<port>	groups=FD,SOCKET,CHILD,RETRY,IP4,IP6,UDP,OPENSSL
      openssl-dtls-server:<port>	groups=FD,SOCKET,LISTEN,CHILD,RETRY,RANGE,IP4,IP6,UDP,OPENSSL
      openssl-listen:<port>	groups=FD,SOCKET,LISTEN,CHILD,RETRY,RANGE,IP4,IP6,TCP,OPENSSL
      pipe:<filename>	groups=FD,FIFO,NAMED,OPEN
      proxy:<proxy-server>:<host>:<port>	groups=FD,SOCKET,CHILD,RETRY,IP4,IP6,TCP,HTTP
      pty	groups=FD,NAMED,TERMIOS,PTY
      readline	groups=FD,READLINE,TERMIOS
      sctp-connect:<host>:<port>	groups=FD,SOCKET,CHILD,RETRY,IP4,IP6,SCTP
      sctp-listen:<port>	groups=FD,SOCKET,LISTEN,CHILD,RETRY,RANGE,IP4,IP6,SCTP
      sctp4-connect:<host>:<port>	groups=FD,SOCKET,CHILD,RETRY,IP4,SCTP
      sctp4-listen:<port>	groups=FD,SOCKET,LISTEN,CHILD,RETRY,RANGE,IP4,SCTP
      sctp6-connect:<host>:<port>	groups=FD,SOCKET,CHILD,RETRY,IP6,SCTP
      sctp6-listen:<port>	groups=FD,SOCKET,LISTEN,CHILD,RETRY,RANGE,IP6,SCTP
      socket-connect:<domain>:<protocol>:<remote-address>	groups=FD,SOCKET,CHILD,RETRY
      socket-datagram:<domain>:<type>:<protocol>:<remote-address>	groups=FD,SOCKET,RANGE
      socket-listen:<domain>:<protocol>:<local-address>	groups=FD,SOCKET,LISTEN,CHILD,RETRY,RANGE
      socket-recv:<domain>:<type>:<protocol>:<local-address>	groups=FD,SOCKET,RANGE
      socket-recvfrom:<domain>:<type>:<protocol>:<local-address>	groups=FD,SOCKET,CHILD,RANGE
      socket-sendto:<domain>:<type>:<protocol>:<remote-address>	groups=FD,SOCKET
      socks4:<socks-server>:<host>:<port>	groups=FD,SOCKET,CHILD,RETRY,IP4,IP6,TCP,SOCKS4
      socks4a:<socks-server>:<host>:<port>	groups=FD,SOCKET,CHILD,RETRY,IP4,IP6,TCP,SOCKS4
      stderr	groups=FD,FIFO,CHR,BLK,REG,SOCKET,TERMIOS,UNIX,IP4,IP6,UDP,TCP,SCTP
      stdin	groups=FD,FIFO,CHR,BLK,REG,SOCKET,TERMIOS,UNIX,IP4,IP6,UDP,TCP,SCTP
      stdio	groups=FD,FIFO,CHR,BLK,REG,SOCKET,TERMIOS,UNIX,IP4,IP6,UDP,TCP,SCTP
      stdout	groups=FD,FIFO,CHR,BLK,REG,SOCKET,TERMIOS,UNIX,IP4,IP6,UDP,TCP,SCTP
      system:<shell-command>	groups=FD,FIFO,SOCKET,EXEC,FORK,TERMIOS,PTY,PARENT,UNIX
      tcp-connect:<host>:<port>	groups=FD,SOCKET,CHILD,RETRY,IP4,IP6,TCP
      tcp-listen:<port>	groups=FD,SOCKET,LISTEN,CHILD,RETRY,RANGE,IP4,IP6,TCP
      tcp4-connect:<host>:<port>	groups=FD,SOCKET,CHILD,RETRY,IP4,TCP
      tcp4-listen:<port>	groups=FD,SOCKET,LISTEN,CHILD,RETRY,RANGE,IP4,TCP
      tcp6-connect:<host>:<port>	groups=FD,SOCKET,CHILD,RETRY,IP6,TCP
      tcp6-listen:<port>	groups=FD,SOCKET,LISTEN,CHILD,RETRY,RANGE,IP6,TCP
      tun[:<ip-addr>/<bits>]	groups=FD,CHR,NAMED,OPEN,INTERFACE
      udp-connect:<host>:<port>	groups=FD,SOCKET,IP4,IP6,UDP
      udp-datagram:<host>:<port>	groups=FD,SOCKET,RANGE,IP4,IP6,UDP
      udp-listen:<port>	groups=FD,SOCKET,LISTEN,CHILD,RANGE,IP4,IP6,UDP
      udp-recv:<port>	groups=FD,SOCKET,RANGE,IP4,IP6,UDP
      udp-recvfrom:<port>	groups=FD,SOCKET,CHILD,RANGE,IP4,IP6,UDP
      udp-sendto:<host>:<port>	groups=FD,SOCKET,IP4,IP6,UDP
      udp4-connect:<host>:<port>	groups=FD,SOCKET,IP4,UDP
      udp4-datagram:<host>:<port>	groups=FD,SOCKET,RANGE,IP4,UDP
      udp4-listen:<port>	groups=FD,SOCKET,LISTEN,CHILD,RANGE,IP4,UDP
      udp4-recv:<port>	groups=FD,SOCKET,RANGE,IP4,UDP
      udp4-recvfrom:<port>	groups=FD,SOCKET,CHILD,RANGE,IP4,UDP
      udp4-sendto:<host>:<port>	groups=FD,SOCKET,IP4,UDP
      udp6-connect:<host>:<port>	groups=FD,SOCKET,IP6,UDP
      udp6-datagram:<host>:<port>	groups=FD,SOCKET,RANGE,IP6,UDP
      udp6-listen:<port>	groups=FD,SOCKET,LISTEN,CHILD,RANGE,IP6,UDP
      udp6-recv:<port>	groups=FD,SOCKET,RANGE,IP6,UDP
      udp6-recvfrom:<port>	groups=FD,SOCKET,CHILD,RANGE,IP6,UDP
      udp6-sendto:<host>:<port>	groups=FD,SOCKET,IP6,UDP
      unix-client:<filename>	groups=FD,SOCKET,NAMED,RETRY,UNIX
      unix-connect:<filename>	groups=FD,SOCKET,NAMED,RETRY,UNIX
      unix-listen:<filename>	groups=FD,SOCKET,NAMED,LISTEN,CHILD,RETRY,UNIX
      unix-recv:<filename>	groups=FD,SOCKET,NAMED,RETRY,UNIX
      unix-recvfrom:<filename>	groups=FD,SOCKET,NAMED,CHILD,RETRY,UNIX
      unix-sendto:<filename>	groups=FD,SOCKET,NAMED,RETRY,UNIX
      vsock-connect:<cid>:<port>	groups=FD,SOCKET,CHILD,RETRY
      vsock-listen:<port>	groups=FD,SOCKET,LISTEN,CHILD,RETRY

#查看帮助

[root@haproxy ~]# echo "help" | socat stdio /var/lib/haproxy/stats 
The following commands are valid at this level:
  abort ssl cert <certfile>               : abort a transaction for a certificate file
  add acl [@<ver>] <acl> <pattern>        : add an acl entry
  add map [@<ver>] <map> <key> <val>      : add a map entry (payload supported instead of key/val)
  add ssl crt-list <list> <cert> [opts]*  : add to crt-list file <list> a line <cert> or a payload
  clear acl [@<ver>] <acl>                : clear the contents of this acl
  clear counters [all]                    : clear max statistics counters (or all counters)
  clear map [@<ver>] <map>                : clear the contents of this map
  clear table <table> [<filter>]*         : remove an entry from a table (filter: data/key)
  commit acl @<ver> <acl>                 : commit the ACL at this version
  commit map @<ver> <map>                 : commit the map at this version
  commit ssl cert <certfile>              : commit a certificate file
  del acl <acl> [<key>|#<ref>]            : delete acl entries matching <key>
  del map <map> [<key>|#<ref>]            : delete map entries matching <key>
  del ssl cert <certfile>                 : delete an unused certificate file
  del ssl crt-list <list> <cert[:line]>   : delete a line <cert> from crt-list file <list>
  disable agent                           : disable agent checks
  disable dynamic-cookie backend <bk>     : disable dynamic cookies on a specific backend
  disable frontend <frontend>             : temporarily disable specific frontend
  disable health                          : disable health checks
  disable server (DEPRECATED)             : disable a server for maintenance (use 'set server' instead)
  enable agent                            : enable agent checks
  enable dynamic-cookie backend <bk>      : enable dynamic cookies on a specific backend
  enable frontend <frontend>              : re-enable specific frontend
  enable health                           : enable health checks
  enable server  (DEPRECATED)             : enable a disabled server (use 'set server' instead)
  get acl <acl> <value>                   : report the patterns matching a sample for an ACL
  get map <acl> <value>                   : report the keys and values matching a sample for a map
  get var <name>                          : retrieve contents of a process-wide variable
  get weight <bk>/<srv>                   : report a server's current weight
  new ssl cert <certfile>                 : create a new certificate file to be used in a crt-list or a directory
  operator                                : lower the level of the current CLI session to operator
  prepare acl <acl>                       : prepare a new version for atomic ACL replacement
  prepare map <acl>                       : prepare a new version for atomic map replacement
  set dynamic-cookie-key backend <bk> <k> : change a backend secret key for dynamic cookies
  set map <map> [<key>|#<ref>] <value>    : modify a map entry
  set maxconn frontend <frontend> <value> : change a frontend's maxconn setting
  set maxconn global <value>              : change the per-process maxconn setting
  set maxconn server <bk>/<srv>           : change a server's maxconn setting
  set profiling <what> {auto|on|off}      : enable/disable resource profiling (tasks,memory)
  set rate-limit <setting> <value>        : change a rate limiting value
  set server <bk>/<srv> [opts]            : change a server's state, weight, address or ssl
  set severity-output [none|number|string]: set presence of severity level in feedback information
  set ssl cert <certfile> <payload>       : replace a certificate file
  set ssl ocsp-response <resp|payload>    : update a certificate's OCSP Response from a base64-encode DER
  set ssl tls-key [id|file] <key>         : set the next TLS key for the <id> or <file> listener to <key>
  set table <table> key <k> [data.* <v>]* : update or create a table entry's data
  set timeout [cli] <delay>               : change a timeout setting
  set weight <bk>/<srv>  (DEPRECATED)     : change a server's weight (use 'set server' instead)
  show acl [@<ver>] <acl>]                : report available acls or dump an acl's contents
  show activity                           : show per-thread activity stats (for support/developers)
  show backend                            : list backends in the current running config
  show cache                              : show cache status
  show cli level                          : display the level of the current CLI session
  show cli sockets                        : dump list of cli sockets
  show env [var]                          : dump environment variables known to the process
  show errors [<px>] [request|response]   : report last request and/or response errors for each proxy
  show events [<sink>] [-w] [-n]          : show event sink state
  show fd [num]                           : dump list of file descriptors in use or a specific one
  show info [desc|json|typed|float]*      : report information about the running process
  show libs                               : show loaded object files and libraries
  show map [@ver] [map]                   : report available maps or dump a map's contents
  show peers [dict|-] [section]           : dump some information about all the peers or this peers section
  show pools                              : report information about the memory pools usage
  show profiling [<what>|<#lines>|byaddr]*: show profiling state (all,status,tasks,memory)
  show resolvers [id]                     : dumps counters from all resolvers section and associated name servers
  show schema json                        : report schema used for stats
  show servers conn [<backend>]           : dump server connections status (all or for a single backend)
  show servers state [<backend>]          : dump volatile server information (all or for a single backend)
  show sess [id]                          : report the list of current sessions or dump this exact session
  show ssl cert [<certfile>]              : display the SSL certificates used in memory, or the details of a file
  show ssl crt-list [-n] [<list>]         : show the list of crt-lists or the content of a crt-list file <list>
  show startup-logs                       : report logs emitted during HAProxy startup
  show stat [desc|json|no-maint|typed|up]*: report counters for each proxy and server
  show table <table> [<filter>]*          : report table usage stats or dump this table's contents (filter: data/key)
  show tasks                              : show running tasks
  show threads                            : show some threads debugging information
  show tls-keys [id|*]                    : show tls keys references or dump tls ticket keys when id specified
  show trace [<module>]                   : show live tracing state
  show version                            : show version of the current process
  shutdown frontend <frontend>            : stop a specific frontend
  shutdown session [id]                   : kill a specific session
  shutdown sessions server <bk>/<srv>     : kill sessions on a server
  trace [<module>|0] [cmd [args...]]      : manage live tracing (empty to list, 0 to stop all)
  user                                    : lower the level of the current CLI session to user
  help [<command>]                        : list matching or all commands
  prompt                                  : toggle interactive mode with prompt
  quit                                    : disconnect

常用示例:(socat是临时调整的)

示例1

[root@haproxy ~]# echo show info | socat stdio /var/lib/haproxy/stats 
Name: HAProxy
Version: 2.4.22-f8e3218
Release_date: 2023/02/14
Nbthread: 2
Nbproc: 1
Process_num: 1
Pid: 34883
Uptime: 0d 0h15m58s
Uptime_sec: 958
Memmax_MB: 0
PoolAlloc_MB: 0
PoolUsed_MB: 0
PoolFailed: 0
Ulimit-n: 8037
Maxsock: 8037
Maxconn: 4000
Hard_maxconn: 4000
CurrConns: 0
CumConns: 2722
CumReq: 7
MaxSslConns: 0
CurrSslConns: 0
CumSslConns: 0
Maxpipes: 0
PipesUsed: 0
PipesFree: 0
ConnRate: 0
ConnRateLimit: 0
MaxConnRate: 0
SessRate: 0
SessRateLimit: 0
MaxSessRate: 0
SslRate: 0
SslRateLimit: 0
MaxSslRate: 0
SslFrontendKeyRate: 0
SslFrontendMaxKeyRate: 0
SslFrontendSessionReuse_pct: 0
SslBackendKeyRate: 0
SslBackendMaxKeyRate: 0
SslCacheLookups: 0
SslCacheMisses: 0
CompressBpsIn: 0
CompressBpsOut: 0
CompressBpsRateLim: 0
Tasks: 20
Run_queue: 0
Idle_pct: 100
node: haproxy
Stopping: 0
Jobs: 5
Unstoppable Jobs: 1
Listeners: 4
ActivePeers: 0
ConnectedPeers: 0
DroppedLogs: 0
BusyPolling: 0
FailedResolutions: 0
TotalBytesOut: 26114
TotalSplicdedBytesOut: 0
BytesOutRate: 0
DebugCommandsIssued: 0
CumRecvLogs: 0
Build info: 2.4.22-f8e3218
Memmax_bytes: 0
PoolAlloc_bytes: 108672
PoolUsed_bytes: 108672
Start_time_sec: 1723173756
Tainted: 0

示例2

[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
3 webcluster 1 web1 172.25.254.10 0 5 1 1 1062 1 0 0 14 0 0 0 - 80 - 0 0 - - 0
3 webcluster 2 web2 172.25.254.20 2 0 1 1 1062 6 3 7 6 0 0 0 - 80 - 0 0 - - 0
3 webcluster 3 wen_sorry 172.25.254.100 2 0 1 1 1062 1 0 2 0 0 0 0 - 8080 - 0 0 - - 0
4 static 1 static 127.0.0.1 0 0 1 1 1062 8 2 0 6 0 0 0 - 4331 - 0 0 - - 0
5 app 1 app1 127.0.0.1 0 0 1 1 1061 8 2 0 6 0 0 0 - 5001 - 0 0 - - 0
5 app 2 app2 127.0.0.1 0 0 1 1 1061 8 2 0 6 0 0 0 - 5002 - 0 0 - - 0
5 app 3 app3 127.0.0.1 0 0 1 1 1061 8 2 0 6 0 0 0 - 5003 - 0 0 - - 0
5 app 4 app4 127.0.0.1 0 0 1 1 1061 8 2 0 6 0 0 0 - 5004 - 0 0 - - 0

示例3(加权)

#给查看权重
[root@haproxy ~]# echo "get weight webcluster/web1" | socat stdio /var/lib/haproxy/stats 
1 (initial 1)
#添加权重
[root@haproxy ~]# echo "set weight webcluster/web1 2" | socat stdio /var/lib/haproxy/stats

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

示例4(下线和上线)

#下线
[root@haproxy ~]# echo "disable server webcluster/web1" | socat stdio /var/lib/haproxy/stats
[root@haproxy ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@haproxy ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@haproxy ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
#上线
[root@haproxy ~]# echo "enable server webcluster/web1" | socat stdio /var/lib/haproxy/stats
[root@haproxy ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@haproxy ~]# curl 172.25.254.100
webserver1 - 172.25.254.10
[root@haproxy ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@haproxy ~]# curl 172.25.254.100
webserver1 - 172.25.254.10

针对多进程处理方法

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

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

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
 # 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核心绑定防止cpu抖动从而减少系统资源消耗
    cpu-map 2 1 #2 表示第二个进程,1表示第二个cpu核心

[root@haproxy ~]# systemctl restart haproxy.service 
[root@haproxy ~]# ll /var/lib/haproxy
总用量 4
-rw-r--r-- 1 root root 40  8月  9 11:30 haproxy.sock
srw------- 1 root root  0  8月  9 11:56 stats
srw------- 1 root root  0  8月  9 11:57 stats1
srw------- 1 root root  0  8月  9 11:57 stats2

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

四.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 roundrobin
    balance static-rr
#   redirect prefix http://www.baidu.com/
    server web1 172.25.254.10:80 maxconn 2 check inter 3s fall 3 rise 5 
    server web2 172.25.254.20:80 check inter 3s fall 3 rise 5
    server wen_sorry 172.25.254.100:8080 backup
[root@haproxy ~]# systemctl restart haproxy.service


#测试,发现无法修改权重
[root@haproxy ~]# echo "get weight webcluster/web1" | socat stdio /var/lib/haproxy/stats 
1 (initial 1)

[root@haproxy ~]# echo "set weight webcluster/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 webcluster
    bind *:80
    mode http
    #balance roundrobin
    #balance static-rr
    balance first
#   redirect prefix http://www.baidu.com/
    server web1 172.25.254.10:80 maxconn 2 check inter 3s fall 3 rise 5
    server web2 172.25.254.20:80 check inter 3s fall 3 rise 5
    server wen_sorry 172.25.254.100:8080 backup
[root@haproxy ~]# systemctl restart haproxy.service 

测试结果:first会一直使用同一个主机,直到该主机无法运行

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

测试:让主机挂掉

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

#使用两个主机同时循环访问
[root@webserver1 ~]# while true;do curl 172.25.254.100;done
[root@haproxy ~]# while true;do curl 172.25.254.100;done

发现10的主机达到上限后会转到20访问

4.2动态算法

动态算法

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

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

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

4.2.1 roundrobin

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

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

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

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

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

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

roundrobin给负载小的,谁闲给谁,谁权重高给谁,先看负载

示例

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

动态调整权重(可以调整权重)

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

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

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

4.2.2 leastconn

·leastconn加权的最少连接的动态

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

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

leastconn谁的链接少给谁,权重是次考虑的,当链接数相同时谁的权重大给谁

示例:

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
listen webcluster
    bind *:80
    mode http
    #balance roundrobin
    #balance static-rr
    #balance first
    #balance  roundrobin 
    balance  leastconn
#   redirect prefix http://www.baidu.com/
    server web1 172.25.254.10:80 maxconn 2 check inter 3s fall 3 rise 5
    server web2 172.25.254.20:80 check inter 3s fall 3 rise 5
    server wen_sorry 172.25.254.100:8080 backup
[root@haproxy ~]# systemctl restart haproxy.service

4.3其他算法

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

有hash-type consistent则为动态,没有则为静态

4.3.1source(源)

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

source源地址hash使同一个源地址都访问一个网址

示例:

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
listen webcluster
    bind *:80
    mode http
    #balance roundrobin
    #balance static-rr
    #balance first
    #balance  roundrobin 
    #balance  leastconn
    balance  source
#   redirect prefix http://www.baidu.com/
    server web1 172.25.254.10:80 maxconn 2 check inter 3s fall 3 rise 5
    server web2 172.25.254.20:80 check inter 3s fall 3 rise 5
    server wen_sorry 172.25.254.100:8080 backup
[root@haproxy ~]# systemctl restart haproxy.service

测试

[root@haproxy ~]# for i in {1..10};do curl 172.25.254.100;done
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10

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

4.3.1.1 map-base 取模法

map-based:取模法,对source地址进行hash计算,再基于服务器总权重的取模,最终结果决定将此请求转发至对应的后端服务器。

此方法是静态的,即不支持在线调整权重,不支持慢启动,可实现对后端服务器均衡调度

如hash值为111,总权重为3,则111%3

 缺点是当服务器的总权重发生变化时,即有服务器上线或下线,都会因总权重发生变化而导致调度结果整体改变,hash-type指定的默认值为此算法

所谓取模运算,就是计算两个数相除之后的余数,10%7=3,7%4=3

map-based算法:基于权重取模,hash(source_ip)%所有后端服务器相加的总权重

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

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

假设a为0,1113主机会被调度到a上,

如果a的权重变成了2

1111%4=3,1112%4=0,1113%4=1

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

会出现的问题:由于权重的变化会导致哈希偏移,导致会话丢失

示例:

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
listen webcluster
    bind *:80
    mode http
    #balance roundrobin
    #balance static-rr
    #balance first
    #balance  roundrobin 
    #balance  leastconn
    balance  source
#   redirect prefix http://www.baidu.com/
    server web1 172.25.254.10:80 maxconn 2 check inter 3s fall 3 rise 5
    server web2 172.25.254.20:80 check inter 3s fall 3 rise 5
    server wen_sorry 172.25.254.100:8080 backup
[root@haproxy ~]# systemctl restart haproxy.service

4.3.1.2 一致性hash

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

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

算法:

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

哈希环:0到2^32-1的数字落到一个圆上,这个圆就叫哈希环

hash环偏斜问题

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

hash对象

Hash对象到后端服务器的映射关系:

一致性hash示意图

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

客户机会顺时针寻找服务器

在线

离线

一致性hash配置示例

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
listen webcluster
    bind *:80
    mode http
    #balance roundrobin
    #balance static-rr
    #balance first
    #balance  roundrobin 
    #balance  leastconn
    balance  source
    hash-type consistent
#   redirect prefix http://www.baidu.com/
    server web1 172.25.254.10:80 maxconn 2 check inter 3s fall 3 rise 5
    server web2 172.25.254.20:80 check inter 3s fall 3 rise 5
    server wen_sorry 172.25.254.100:8080 backup
[root@haproxy ~]# systemctl restart haproxy.service
[root@haproxy ~]# echo "set weight webcluster/web1 2" | socat stdio /var/lib/haproxy/stats

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

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>

<scheme> : / /<user>:<password>@<host> :<port>/<path> ; <params>?<query>#<frag>

<scheme>:协议

<user>:用户

<password>:密码

<host>:主机

<port>:端口

<path> :文件路径

<params>:向服务器传递的指令

<query>:查询的目标

<frag>:片段

[协议名]://[用户名]:[密码]@[主机名]:[端口号]/[路径]?[查询参数]#[片段ID]

uri:资源的唯一标志符(标志)

url:资源在服务器的真实位置(定位)

urn:统一资源名称

4.3.2.1 uri 取模法配置示例
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
listen webcluster
    bind *:80
    mode http
    #balance roundrobin
    #balance static-rr
    #balance first
    #balance  roundrobin 
    #balance  leastconn
    #balance  source
    balance  uri
    hash-type consistent   #一致性hash
#   redirect prefix http://www.baidu.com/
    server web1 172.25.254.10:80 maxconn 2 check inter 3s fall 3 rise 5
    server web2 172.25.254.20:80 check inter 3s fall 3 rise 5
    server wen_sorry 172.25.254.100:8080 backup
[root@haproxy ~]# systemctl restart haproxy.service

#修改web1和web2的nginx的配置
[root@webserver1 ~]# echo 172.25.254.10 - index1.htel > /usr/share/nginx/html/index1.html 
[root@webserver1 ~]# echo 172.25.254.10 - index2.htel > /usr/share/nginx/html/index2.html 
[root@webserver1 ~]# echo 172.25.254.10 - index3.htel > /usr/share/nginx/html/index3.html 
[root@webserver1 ~]# systemctl restart nginx

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

#测试,发现访问同一个index时候
[root@haproxy ~]# curl 172.25.254.100/index1.html
172.25.254.10 - index1.htel
[root@haproxy ~]# curl 172.25.254.100/index2.html
172.25.254.20 - index2.htel
[root@haproxy ~]# curl 172.25.254.100/index3.html
172.25.254.10 - index3.htel
[root@haproxy ~]# curl 172.25.254.100/index1.html
172.25.254.10 - index1.htel
[root@haproxy ~]# curl 172.25.254.100/index2.html
172.25.254.20 - index2.htel
[root@haproxy ~]# curl 172.25.254.100/index3.html
172.25.254.10 - index3.htel

注意:只要后面的uri(文件路径)不变,那么取到的地址不会发送变化

4.3.2.2 访问测试

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

#测试,发现访问同一个index时候
[root@haproxy ~]# curl 172.25.254.100/index1.html
172.25.254.10 - index1.htel
[root@haproxy ~]# curl 172.25.254.100/index2.html
172.25.254.20 - index2.htel
[root@haproxy ~]# curl 172.25.254.100/index3.html
172.25.254.10 - index3.htel
[root@haproxy ~]# curl 172.25.254.100/index1.html
172.25.254.10 - index1.htel
[root@haproxy ~]# curl 172.25.254.100/index2.html
172.25.254.20 - index2.htel
[root@haproxy ~]# curl 172.25.254.100/index3.html
172.25.254.10 - index3.htel

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"

4.3.3.1 url_param取模法配置示例
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
listen webcluster
    bind *:80
    mode http
    #balance roundrobin
    #balance static-rr
    #balance first
    #balance  roundrobin 
    #balance  leastconn
    #balance  source
    #balance  uri
    balance  url_param name,userid
    hash-type consistent
#   redirect prefix http://www.baidu.com/
    server web1 172.25.254.10:80 maxconn 2 check inter 3s fall 3 rise 5
    server web2 172.25.254.20:80 check inter 3s fall 3 rise 5
    server wen_sorry 172.25.254.100:8080 backup
[root@haproxy ~]# systemctl restart haproxy.service

#访问测试
[root@haproxy ~]# curl 172.25.254.100/index3.html?name=lee
172.25.254.10 - index3.htel
[root@haproxy ~]# curl 172.25.254.100/index3.html?name=lee
172.25.254.10 - index3.htel
[root@haproxy ~]# curl 172.25.254.100/index3.html?name=lee
172.25.254.10 - index3.htel
[root@haproxy ~]# curl 172.25.254.100/index3.html?name=test
172.25.254.20 - index3.htel
[root@haproxy ~]# curl 172.25.254.100/index3.html?name=test
172.25.254.20 - index3.htel

4.3.3.2 测试访问
[root@haproxy ~]# curl 172.25.254.100/index3.html?name=lee
172.25.254.10 - index3.htel
[root@haproxy ~]# curl 172.25.254.100/index3.html?name=lee
172.25.254.10 - index3.htel
[root@haproxy ~]# curl 172.25.254.100/index3.html?name=lee
172.25.254.10 - index3.htel
[root@haproxy ~]# curl 172.25.254.100/index3.html?name=test
172.25.254.20 - index3.htel
[root@haproxy ~]# curl 172.25.254.100/index3.html?name=test
172.25.254.20 - index3.htel

访问时链接不能断开

4.3.4 hdr

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

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

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

用hdr的话浏览器看的是报头无法更改,浏览器不同访问的网站不同

4.3.4.1 hdr取模法配置示例
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
listen webcluster
    bind *:80
    mode http
    #balance roundrobin
    #balance static-rr
    #balance first
    #balance  roundrobin 
    #balance  leastconn
    #balance  source
    #balance  uri
    #balance  url_param name,userid
    balance hdr(User-Agent)
    hash-type consistent
#   redirect prefix http://www.baidu.com/
    server web1 172.25.254.10:80 maxconn 2 check inter 3s fall 3 rise 5
    server web2 172.25.254.20:80 check inter 3s fall 3 rise 5
    server wen_sorry 172.25.254.100:8080 backup
[root@haproxy ~]# systemctl restart haproxy.service

4.3.4.2 测试访问
#-v查看报文
[root@haproxy ~]# curl -v 172.25.254.100
*   Trying 172.25.254.100:80...
* Connected to 172.25.254.100 (172.25.254.100) port 80 (#0)
> GET / HTTP/1.1
> Host: 172.25.254.100
> User-Agent: curl/7.76.1
> Accept: */*
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< server: nginx/1.20.1
< date: Fri, 09 Aug 2024 08:12:58 GMT
< content-type: text/html
< content-length: 27
< last-modified: Wed, 07 Aug 2024 15:47:45 GMT
< etag: "66b39721-1b"
< accept-ranges: bytes
< 
webserver1 - 172.25.254.10
* Connection #0 to host 172.25.254.100 left intact


#-A 指定什么浏览器
[root@haproxy ~]# curl -vA "firefox" 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: firefox
> Accept: */*
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< server: nginx/1.20.1
< date: Fri, 09 Aug 2024 08:13:11 GMT
< content-type: text/html
< content-length: 27
< last-modified: Wed, 07 Aug 2024 15:47:45 GMT
< etag: "66b39721-1b"
< accept-ranges: bytes
< 
webserver1 - 172.25.254.10
* Connection #0 to host 172.25.254.100 left intact


#-A 指定什么浏览器
[root@haproxy ~]# curl -vA "sougou" 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: sougou
> Accept: */*
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< server: nginx/1.20.1
< date: Fri, 09 Aug 2024 08:13:33 GMT
< content-type: text/html
< content-length: 27
< last-modified: Wed, 07 Aug 2024 15:48:35 GMT
< etag: "66b39753-1b"
< accept-ranges: bytes
< 
webserver2 - 172.25.254.20
* Connection #0 to host 172.25.254.100 left intact

4.3.5 算法总结

#静态

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 对http的报文头进行哈希

4.3.6 各算法使用场景

first #使用较少

static-rr #做了session共享的web集群

roundrobin

random

leastconn #数据库

source

#基于客户端公网IP的会话保持

uri--------------->http #缓存服务器,CDN服务商,蓝汛、百度、阿里云、腾讯

ur1_param--------->http #可以实现session保持

hdr #基于客户端请求报文头部做下一步处理

五.高级功能及配置

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

5.1基于cookie的会话保持

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

注意:cookie保存在浏览器上,session保存在服务器上

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

使用cookie的话,浏览器看的是cookie,cookie是可以更改的(与hdr的区别)

5.1.1配置选项

cookie name [ rewrite / insert / prefix ][ indirect ] [ nocache ][ postonly ][preserve ][ httponly ] [ secure ][ domain ]1[ maxidle <idle> ][ 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 webcluster
    bind *:80
    mode http
    balance roundrobin
    #balance static-rr
    #balance first
#   redirect prefix http://www.baidu.com/
    cookie WEBCOOKIE insert nocache indirect
    server web1 172.25.254.10:80 cookie haha1 check inter 3s fall 3 rise 5
    server web2 172.25.254.20:80 cookie haha2 check inter 3s fall 3 rise 5
    server wen_sorry 172.25.254.100:8080 backup

[root@haproxy ~]# systemctl restart haproxy.service
#用两个不同的浏览器访问172.25.254.100,发现访问的不同而且不断刷新但是内容不变

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

用两个不同的浏览器访问172.25.254.100,发现访问的不同而且不断刷新但是内容不变

5.1.3 验证cookie信息

浏览器访问后按F12

通过命令行验证:

[root@haproxy ~]# curl -b WEBCOOKIE=haha1 172.25.254.100
webserver1 - 172.25.254.10
[root@haproxy ~]# curl -b WEBCOOKIE=haha2 172.25.254.100
webserver2 - 172.25.254.20
[root@haproxy ~]# curl -b WEBCOOKIE=haha1 172.25.254.100
webserver1 - 172.25.254.10
[root@haproxy ~]# curl -b WEBCOOKIE=haha2 172.25.254.100
webserver2 - 172.25.254.20

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启用状态页

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
#添加即可
listen stats
    mode http
    bind *:9999
    stats enable  #打开状态页功能
    log global
    stats uri /status    #自定义uri,访问的目录(可以改)
    stats auth haha:haha  #认证,haha用户,密码haha
[root@haproxy ~]# systemctl restart haproxy.service

#浏览器访问:http://172.25.254.100:9999/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 = o

#当前连接数/当前管道数/当前连接速率

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改成O)

active or backup sOFT STOPPED for maintenance

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:活动链接数量

ln:网络的字节输入总量 Bck:备份的服务器数量

Out:网络的字节输出总量 chk:心跳检测时间

Dwn:后端服务器连接后都是DOWN的数量 Denied(拒绝统计信息):

Dwntme:总的downtime时间 Req:拒绝请求量

Thrtle:server状态 Resp:拒绝回复量

5.3IP透传

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

#先将web1的nginx换成http好方便看效果
[root@webserver1 ~]# systemctl stop nginx.service 
[root@webserver1 ~]# yum install httpd -y
[root@webserver1 ~]# systemctl start httpd
[root@webserver1 ~]# echo webserver1 - 172.25.254.10 > /var/www/html/index.html

此选项是是否打开透传

5.3.1 layer 4 与 layer 7

四层:IP+PORT转发

七层:协议+内容交换

5.3.1.1四层负载

在四层负载设备中,把client发送的报文目标地址(原来是负载均衡设备的IP地址),根据均衡设备设置的选择web服务器的规则选择对应的web服务器IP地址,这样client就可以直接跟此服务器建立TCP连接并发送数据,而四层负载自身不参与建立连接,而和LVS不同,haproxy是伪四层负载均衡,因为haproxy需要分别和前端客户端及后端服务器建立连接

5.3.1.2七层代理

七层负载均衡服务器起了一个反向代理服务器的作用,服务器建立一次TCP连接要三次握手,而client要访问Web Server要先与七层负载设备进行三次握手后建立TCP连接,把要访问的报文信息发送给七层负载均衡;然后七层负载均衡再根据设置的均衡规则选择特定的Web Server,然后通过三次握手与此台Web Server建立TCP连接,然后Web Server把需要的数据发送给七层负载均衡设备,负载均衡设备再把数据发送给client;所以,七层负载均衡设备起到了代理服务器的作用,七层代理需要和Client和后端服务器分别建立连接

5.3.2四层IP透传

#未开启透传的四层代理
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    #option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000
....
listen webcluster
    bind *:80
    mode tcp
    balance roundrobin
    #balance static-rr
    #balance first
#   redirect prefix http://www.baidu.com/
    #cookie WEBCOOKIE insert nocache indirect
    server web1 172.25.254.10:80 check inter 3s fall 3 rise 5
    server web2 172.25.254.20:80 check inter 3s fall 3 rise 5
    server wen_sorry 172.25.254.100:8080 backup

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

#查看nginx配置,为开启时不做修改
[root@webserver2 ~]# vim /etc/nginx/nginx.conf

#在访问haproxy后查看nginx日志
[root@haproxy ~]# curl 172.25.254.100
webserver1 - 172.25.254.10
[root@haproxy ~]# curl 172.25.254.100
webserver2 - 172.25.254.20

[root@webserver2 ~]# tail -n 3 /var/log/nginx/access.log
172.25.254.100 - - [10/Aug/2024:10:56:20 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1" "-"
172.25.254.100 - - [10/Aug/2024:10:56:57 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1" "-"
172.25.254.100 - - [10/Aug/2024:10:57:01 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1" "-"
#在此日志中是无法看到真实访问源地址的

开始四层透传

nginx中

nginx的配置文件需要修改两个地方

haproxy需要开启透传,并且添加send-proxy

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000
.....
listen webcluster
    bind *:80
    mode tcp
    balance roundrobin
    #balance static-rr
    #balance first
#   redirect prefix http://www.baidu.com/
    #cookie WEBCOOKIE insert nocache indirect
    server web1 172.25.254.10:80 check inter 3s fall 3 rise 5
    server web2 172.25.254.20:80 check inter 3s fall 3 rise 5
    server wen_sorry 172.25.254.100:8080 backup

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

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

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        error_page 404 /404.html;
        location = /404.html {
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }

 [root@webserver2 ~]# systemctl restart nginx
 #此时任然无法访问   
[root@haproxy ~]# curl 172.25.254.100
webserver1 - 172.25.254.10
[root@haproxy ~]# curl 172.25.254.100
curl: (52) Empty reply from server
[root@haproxy ~]# curl 172.25.254.100
webserver1 - 172.25.254.10
[root@haproxy ~]# curl 172.25.254.100
curl: (52) Empty reply from server



#配置nginx
[root@webserver2 ~]# vim /etc/nginx/nginx.conf
http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      ' "$proxy_protocol_addr"'    #添加
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
[root@webserver2 ~]# systemctl restart nginx


#修改haproxy
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
listen webcluster
    bind *:80
    mode tcp
    balance roundrobin
    #balance static-rr
    #balance first
#   redirect prefix http://www.baidu.com/
    #cookie WEBCOOKIE insert nocache indirect
    server web1 172.25.254.10:80 check inter 3s fall 3 rise 5
    server web2 172.25.254.20:80 send-proxy check inter 3s fall 3 rise 5  #添加send-proxy
    server wen_sorry 172.25.254.100:8080 backup
[root@haproxy ~]# systemctl restart haproxy.service
      
[root@haproxy ~]# curl 172.25.254.100
webserver1 - 172.25.254.10
[root@haproxy ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
  
[root@webserver2 ~]#  tail -n 3 /var/log/nginx/access.log
172.25.254.100 - - [10/Aug/2024:10:56:57 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1" "-"
172.25.254.100 - - [10/Aug/2024:10:57:01 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1" "-"
172.25.254.100 - - [10/Aug/2024:11:20:30 +0800] "GET / HTTP/1.1"  "172.25.254.100"200 27 "-" "curl/7.76.1" "-"

nginx

5.3.3七层IP透传

当haproxy工作在七层的时候,也可以透传客户端真实IP至后端服务器

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

option forwardfor [ except <network> ] [ header <name> ] [ if-none ]

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

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

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

示例:

#先关闭透传
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    #option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000
.....
listen webcluster
    bind *:80
    mode http
    balance roundrobin
    #balance static-rr
    #balance first
#   redirect prefix http://www.baidu.com/
    #cookie WEBCOOKIE insert nocache indirect
    server web1 172.25.254.10:80 check inter 3s fall 3 rise 5
    server web2 172.25.254.20:80 check inter 3s fall 3 rise 5
    server wen_sorry 172.25.254.100:8080 backup

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

#nginx访问
[root@haproxy ~]# systemctl restart haproxy.service 
[root@webserver2 ~]# tail -n 3 /var/log/nginx/access.log
172.25.254.100 - - [10/Aug/2024:10:29:18 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1" "172.25.254.100"
172.25.254.100 - - [10/Aug/2024:10:36:02 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1" "172.25.254.100"
172.25.254.100 - - [10/Aug/2024:10:36:40 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1" "-"

开启透传

nginx透传:

七层中nginx不需要做修改,只需要haproxy打开透传即可


[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000
[root@haproxy ~]# systemctl restart haproxy.service 

#nginx访问
[root@haproxy ~]# curl 172.25.254.100
webserver1 - 172.25.254.10
[root@haproxy ~]# curl 172.25.254.100
webserver2 - 172.25.254.20

[root@webserver2 ~]# tail -n 3 /var/log/nginx/access.log
172.25.254.100 - - [10/Aug/2024:10:41:26 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1" "-"
172.25.254.100 - - [10/Aug/2024:10:41:30 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1" "-"
172.25.254.100 - - [10/Aug/2024:10:41:49 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1" "172.25.254.100"

httpd透传:

七层中需要在/etc/httpd/conf/httpd.conf中添加LogFormat "%{X-Forwarded-For}i %a %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

[root@webserver1 ~]# vim /etc/httpd/conf/httpd.conf
#修改
LogFormat "%{X-Forwarded-For}i %a %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
[root@webserver1 ~]# systemctl restart httpd
[root@webserver1 ~]# tail -n 3 /etc/httpd/logs/access_log
172.25.254.100 - - [10/Aug/2024:10:41:48 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1"
172.25.254.100 - - [10/Aug/2024:10:47:51 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/8.7.1"
172.25.254.100 172.25.254.100 - - [10/Aug/2024:10:50:11 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1"

小贴士:

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

#apache配置:
LogFormat "%{X-Forwarded-For}i %a %7 %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 '"Sproxy_add_x_forwarded_for" - $remote_user [$time_loca1]" $request" '
' $status $body_bytes_sent "$http_referer" ''"$http_user_agent" $http_x_forwarded_For ';

#tomcat配置:conf目录下的server.xm7
<valve className="org.apache.catalina.valves.AccessLogvalve" directory="1ogs"
prefix="locaThost_access_log" suffix=".txt"
pattern="%{X-Forwarded-For}i %h %7 %u %t &quot;%r&quot;%s %b”/>

#查看日志如下:
[root@rs1 ~]# tail -n 3 /var / log/nginx/access .1og
"172.25.254.10,192.168.0.10"192.168.0.10 - - [10/u1/2024:16:15:00 +0800]"GET/HTTP/1.1"200 18 "-" "cur1/7.29.0" "172.25.254.10"
[root@rs2~]# tail -n 3 /etc/httpd/1ogs/access_log
172.25.254.10 192.168.0.10 - -[11/Ju1/2024:00:15:00 +0800]"GET / HTTP/1.1”20027 "-" "cur1 /7.29.0"

5.4 ACL

访问控制列表ACL,Access Control Lists)

是一种基于包过滤的访问控制技术

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

#示例
frontend test_acl
    bind *:80
    mode http
    acl test hdr_dom(host) -i www.timinglee.org  #完全匹配www.timinglee.org
    #acl test hdr_end(host) -i .org   #以.org结尾
    #acl bad_browers hdr_beg(User-Agent) -i curl
    #http-request deny if bad_browers
    #acl test hdr_dom(host) -i www.timinglee.org
    #acl test base_sub -m sub org   #匹配模式-m,指定正则表达式,-m sub 在提取的字符串中查找模式,如果其中任何一个被发现,ACL将匹配
    #acl test path_sub -m sub /a
    #acl test path_end -m sub /a
    #acl test path_reg -i ^/t
    #acl test url_sub -m sub lee
    #acl test path_dir -m sub a

    use_backend test_web if test
    default_backend default_webserver

backend test_web
    mode http
    server web2 172.25.254.10:80 check inter 3 fall 3 rise 5

backend default_webserver
    mode http
    server web1 172.25.254.20:80 check inter 3 fall 3 rise 5

5.4.1 ACL配置选项

#用ac1来定义或声明一个ac1

ac1<ac1name> <criterion>[f1ags] [operator] [<value>]

ac7 名称 匹配规范 匹配模式 具体操作符 操作对象类型

5.4.1.1 ACL-Name名称

acl image_service hdr_dom(host)-i img.magedu. com #-i忽略大小写

acl test path_end -m sub /a

#ACL名称,可以使用大字母A-Z、小写字母a-z、数字O-9、冒号:、点.、中横线和下划线,并且严格区分大小写,比如:my_ac1和My_Ac1就是两个完全不同的ac15.8.1.2 ACL-criterion

5.4.1.2 ACL-criterion匹配规范

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

hdr string,提取在一个HTTP请求报文的首部
hdr([<name> [,<occ>]]):完全匹配字符串,header的指定信息,<occ> 表示在多值中使用的值的出现次数
hdr_beg([<name> [,<occ>]]):前缀匹配,header中指定匹配内容的begin,(以什么开头)
hdr_end([<name> [,<occ>]]):后缀匹配,header中指定匹配内容end,(以什么结尾)
hdr_dom([<name> [,<occ>]]):域匹配,header中的dom(host)(是什么)

hdr_dir([<name> [,<occ>]]):路径匹配,header的uri路径
hdr_len([<name> [,<occ>]]):长度匹配,header的长度匹配
hdr_reg([<name> [,<occ>]]):正则表达式匹配,自定义表达式(regex)模糊匹配
hdr_sub([<name> [,<occ>]]):子串匹配,header中的uri模糊匹配 模糊匹配c 报文中a/b/c也会匹
配

#示例:
hdr(<string>) 用于测试请求头部首部指定内容

hdr_dom(host) 请求的host名称,如 www.timinglee.org
hdr_beg(host) 请求的host开头,如 www. img. video. download. ftp.
hdr_end(host) 请求的host结尾,如 .com .net .cn

#示例:
acl bad_agent hdr_sub(User-Agent) -i curl wget
http-request deny if bad_agent

#有些功能是类似的,比如以下几个都是匹配用户请求报文中host的开头是不是www
acl short_form hdr_beg(host) www.
acl alternate1 hdr_beg(host) -m beg www.
acl alternate2 hdr_dom(host) -m beg www.
acl alternate3 hdr(host) -m beg www.

base : string
#返回第一个主机头和请求的路径部分的连接,该请求从主机名开始,并在问号之前结束,对虚拟主机有用
<scheme>://<user>:<password>@#<host>:<port>/<path>;<params>#?<query>#<frag>
base : exact string match
base_beg : prefix match  (匹配开头)
base_dir : subdir match   (匹配子目录)
base_dom : domain match    (域匹配)
base_end : suffix match  (匹配结尾)
base_len : length match   (长度匹配)
base_reg : regex match   (正则匹配)
base_sub : substring match   (字符串匹配)

path : string
#提取请求的URL路径,该路径从第一个斜杠开始,并在问号之前结束(无主机部分)(<path>;<params>#)
<scheme>://<user>:<password>@<host>:<port>#/<path>;<params>#?<query>#<frag>
path : exact string match
path_beg : prefix match #请求的URL开头,如/static、/images、/img、/css
path_end : suffix match #请求的URL中资源的结尾,如 .gif .png .css .js .jpg .jpeg
path_dom : domain match    
path_dir : subdir match
path_len : length match
path_reg : regex match
path_sub : substring match

#示例:
path_beg -i /haproxy-status/
path_end .jpg .jpeg .png .gif
path_reg ^/images.*\.jpeg$
path_sub image
path_dir jpegs
path_dom timinglee

url : string
#提取请求中的整个URL。
url :exact string match
url_beg : prefix match
url_dir : subdir match
url_dom : domain match
url_end : suffix match
url_len : length match
url_reg : regex match
url_sub : substring match

dst #目标IP
dst_port #目标PORT

src #源IP
src_port #源PORT

#示例:
acl invalid_src src 10.0.0.7 192.168.1.0/24
acl invalid_src src 172.16.0.0/24
acl invalid_port src_port 0:1023

status : integer #返回在响应报文中的状态码

#七层协议
acl valid_method method GET HEAD
http-request deny if ! valid_method

path是从斜线开始匹配,base会包含前面的

示例:

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
frontend webcluster
    bind *:80
    mode http
    acl test hdr_dom(host) -i www.timinglee.org
    use_backend webcluster-host if test
    default_backend default-host

backend webcluster-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 ~]# systemctl restart haproxy.service

5.4.1.3 ACL-flags 匹配模式

ACL匹配模式

-i不区分大小写

-m使用指定的正则表达式匹配方法

-n不做DNS解析

-u禁止ac1重名,否则多个同名ACL匹配或关系

5.4.1.4 ACL-operator具体操作符

ACL操作符

整数比较: eq、ge、gt、 le、1t字符比较:

- exact match( -m str):字符串必须完全匹配模式

- substring match (-m sub) :在提取的字符串中查找模式,如果其中任何一个被发现,ACL将匹配

- prefix match (-m beg):在提取的字符串首部中查找模式,如果其中任何一个被发现,ACL将匹配

- suffix match (-m end) :将模式与提取字符串的尾部进行比较,如果其中任何一个匹配,则ACL进行匹配

- subdir match (-m dir) :查看提取出来的用斜线分隔(“/")的字符串,如其中任一个匹配,则ACL进行匹配

- domain match (-m dom):查找提取的用点(“.")分隔字符串,如果其中任何一个匹配,则ACL进行匹配

5.4.1.5 ACL-value操作对象

value的类型

The AcL engine can match these types against patterns of the following types :

- Boolean #布尔值

- integer or integer range #整数或整数范围,比如用于匹配端口范围

- IP address / network #工P地址或IP范围,192.168.0.1 ,192.168.0.1/24

- string--> www .timinglee.org

exact #精确比较

substring #子串

suffix #后缀比较

prefix #前缀比较

subdir #路径,/wp-includes/js/jquery/jquery.js

domain #域名,www .timinglee.org

- regular expression #正则表达式

- hex block #16进制

5.4.2多个ACL的组合调用方式

多个ACL的逻辑处理

与:隐式(默认)使用

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

否定:使用"!"表示

多个ACL调用方式:

#示例:

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

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

if ! invalid_src #非,取反,不满足ACL才为true

5.4.3 ACL示例-域名匹配

#域名匹配
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
frontend webcluster
    bind *:80
    mode http
    acl test hdr_dom(host) -i www.timinglee.org
    use_backend webcluster-host if test
    default_backend default-host

backend webcluster-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 ~]# systemctl restart haproxy.service

#做本地解析
[root@haproxy ~]# vim /etc/hosts
172.25.254.100  www.timinglee.org www.timelee.cmo bbs.timinglee.org

#访问
[root@haproxy ~]#  curl www.timinglee.org
webserver1 - 172.25.254.10
[root@haproxy ~]#  curl 172.25.254.100
webserver2 - 172.25.254.20

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

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

#指定IP调度
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
frontend webcluster
    bind *:80
    mode http
    acl ctrl_ip src 172.25.254.1 172.25.254.20 192.168.0.0/24
    use_backend webcluster-host if ctrl_ip
    default_backend default-host

backend webcluster-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 ~]# systemctl restart haproxy.service

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

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

[root@webserver2 ~]# curl 172.25.254.100
webserver1 - 172.25.254.10

测试结果:

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

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

[root@webserver2 ~]# curl 172.25.254.100
webserver1 - 172.25.254.10

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

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

#拒绝指定的IP访问
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg

frontend webcluster
    bind *:80
    mode http
    acl ctrl_ip src  172.25.254.1 172.25.254.20 192.168.0.0/24
    #use_backend webcluster-host if ctrl_ip
    http-request deny if ctrl_ip   #这一条会让本地的ip在上面条件的无法访问
    default_backend default-host

backend webcluster-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 ~]# systemctl restart haproxy.service

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

#172.25.254.20的无法访问
[root@webserver2 ~]# curl 172.25.254.100
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>

172.25.254.20的无法访问

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

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

示例:

#拒绝curl访问
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
frontend webcluster
    bind *:80
    mode http
    acl badwebrowers hdr_sub(User-Agent) -i curl wget
    #use_backend webcluster-host if ctrl_ip
    http-request deny if badwebrowers    #拒绝匹配到的条件
    default_backend default-host

backend webcluster-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 ~]# systemctl restart haproxy.service

#curl访问,发现无法访问
[root@haproxy ~]# curl 172.25.254.100
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>

#浏览器访问172.25.254.100

curl无法访问,但是浏览器可以

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

#动静分离
[root@webserver1 ~]# yum install php -y
[root@webserver1 ~]# systemctl restart httpd
[root@webserver1 ~]# vim /var/www/html/index.php
<?php
        phpinfo();
?> 


[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
frontend webcluster
    bind *:80
    mode http
    acl static path_end -i .html .jpg .png .css .js
    acl php path_end -i .php
    
    use_backend webcluster-host if php
    default_backend default-host

backend webcluster-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 ~]# systemctl restart haproxy.service

#浏览器访问172.25.254.100/index.php和172.25.254.100

先查看php

配置完后浏览器访问

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

#动静分离
[root@webserver1 ~]# yum install php -y
[root@webserver1 ~]# systemctl restart httpd
[root@webserver1 ~]# vim /var/www/html/index.php
<?php
        phpinfo();
?> 

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

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



[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
frontend webcluster
    bind *:80
    mode http
    acl static path_sub -m sub static
    acl php    path_sub -m sub php

    use_backend webcluster-host if php
    default_backend default-host

backend webcluster-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 ~]# systemctl restart haproxy.service

#浏览器访问:172.25.254.100/php/和172.25.254.100

5.5自定义HAProxy错误界面

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

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

#haproxy默认使用的错误错误页面
[root@haproxy ~]# rpm -ql haproxy | 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 <code> <file>
<code> #HTTP status code.支持200, 400, 403, 405, 408, 425, 429, 500, 502,503,504
<file> #包含完整HTTP响应头的错误页文件的绝对路径。 建议后缀".http",以和一般的html文件相区分
#示例:
errorfile 503 /haproxy/errorpages/503page.http

示例

#haproxy默认使用的错误错误页面
[root@haproxy ~]# rpm -ql haproxy | 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

#修改错误页面
[root@haproxy ~]# cp  /usr/share/haproxy/503.http  /etc/haproxy/errorpages/503.http
[root@haproxy ~]# vim /etc/haproxy/errorpages/503.http
HTTP/1.0 503 Service Unavailable
Cache-Control: no-cache
Connection: close
Content-Type: text/html;charset=UTF-8

<html><body><h1>什么动物生气最安静</h1>
大猩猩!!
</body></html>


[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000
    errorfile 503  /etc/haproxy/errorpages/503.http     #自定义错误页面的路径

[root@haproxy ~]# curl 172.25.254.100
<html><body><h1>什么动物生气最安静</h1>
大猩猩!!
</body></html>

#浏览器访问172.25.254.100

浏览器访问

5.5.2基于http重定向错误页面

#错误页面重定向
errorloc <code> <ur1>
#相当于errorloc302 <code> <ur1>,利用302重定向至指URL
#示例:
errorloc 503 https : / /www. baidu . com

示例

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000
    #errorfile 503  /etc/haproxy/errorpages/503bad.http
    errorloc 503 https://www.baidu.com    #如果遇见503报错会自动进入百度页面

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

#浏览器访问172.25.254.100

5.6 HAProxy四层负载

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

MySQL
Redis
Memcache
RabbitMQ

#下载mariadb-server
[root@webserver1 ~]# yum install mariadb-server -y
[root@webserver2 ~]# yum install mariadb-server -y

#修改两个mariadb-server的id便于区分
[root@webserver1 ~]# vim /etc/my.cnf.d/mariadb-server.cnf 
[mysqld]
server-id=1
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-error=/var/log/mariadb/mariadb.log
pid-file=/run/mariadb/mariadb.pid


[root@webserver2 ~]# vim /etc/my.cnf.d/mariadb-server.cnf 
[mysqld]
server-id=2
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-error=/var/log/mariadb/mariadb.log
pid-file=/run/mariadb/mariadb.pid

#启动mariadb
[root@webserver1 ~]# systemctl start mariadb
[root@webserver2 ~]# systemctl start mariadb

#进入mysql,创建一个用户并且可以远程访问
[root@webserver1 ~]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 10.5.22-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)]> CREATE USER haha@'%' identified by 'haha';
Query OK, 0 rows affected (0.001 sec)

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

MariaDB [(none)]> quit
Bye
[root@webserver1 ~]# 




[root@webserver2 ~]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 10.5.22-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)]> CREATE USER haha@'%' identified by 'haha';
Query OK, 0 rows affected (0.001 sec)

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

MariaDB [(none)]> quit
Bye
[root@webserver2 ~]# 



#测试机下载mariadb,注意:不是mariadb-server
[root@haproxy ~]# yum install mariadb -y
#设置四层负载
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
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 -uhaha -phaha -h 172.25.254.100
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 5
Server version: 10.5.22-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)

#另一个主机测试,发现实现了轮询
[root@webserver2 ~]# mysql -uhaha -phaha -h 172.25.254.100
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 6
Server version: 10.5.22-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.003 sec)

MariaDB [(none)]> 

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

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
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

5.7 HAProxy https 实现

首先要将上文关闭的web服务开启

[root@webserver1 ~]# systemctl start httpd
[root@webserver2 ~]# systemctl start nginx

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

#配置HAProxy支持https协议,支持ss1会话;
bind *:443 ss1 crt /PATH/TO/SOME_PEM_FILE

#指令crt后证书文件为PEM格式,需要同时包含证书和所有私钥
cat demo.key demo.crt > demo.pem

#把80端口的请求重向定443
bind * :80
redirect scheme https if !i ss1_fc }

配置https

#创建证书
[root@haproxy ~]# mkdir -p /etc/haproxy/certs
[root@haproxy ~]# openssl req -newkey rsa:2048 -nodes -sha256 -keyout /etc/haproxy/certs/haha.org.key -x509 -days 365 -out /etc/haproxy/certs/haha.org.crterts/haha.org.key -x509 -days 365 -out /etc/haproxy/certs/haha.org
...+...+.+...........+.........+.+...+..+......+..........+...+...........+...+......+.+......+..+.+...........+.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.+.....+......+.......+..+.+.........+..+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*...........+.....+.+........+...+....+........+.+......+...........+....+...............+.....+.+...+..+...+......+.............+........+.............+............+...+..............+...............+................+..............+...+.........+.............+......+..........................+...+...+...+.+......+........+............+...+......+....+......+.....+....+..............+......+.......+..............+.+..............+...+......+.+.........+..+..........+..+...............+...+..........+..+.+..+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
............+...+..+......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*....+...+.......+...+..+....+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*...+...+.+...........+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:shannxi 
Locality Name (eg, city) [Default City]:Xi`An    
Organization Name (eg, company) [Default Company Ltd]:haha
Organizational Unit Name (eg, section) []:webserver
Common Name (eg, your name or your server's hostname) []:www.haha.org
Email Address []:haha@qq.com


#指令crt后证书文件为PEM格式,需要同时包含证书和所有私钥
[root@haproxy ~]# ls /etc/haproxy/certs/
haha.org.crt  haha.org.key
[root@haproxy ~]# cat /etc/haproxy/certs/haha.org.key /etc/haproxy/certs/haha.org.crt>/etc/haproxy/certs/haha.pem

#修改配置文件,把80端口的请求重向定443
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen web-https
    bind *:443 ssl crt /etc/haproxy/certs/haha.pem
    mode http
    balance roundrobin
    server db1 172.25.254.10:80 check inter 2 fall 2 rise 5
    server db2 172.25.254.20:80 check inter 2 fall 2 rise 5

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

#查看443端口是否启用
[root@haproxy ~]# netstat -antlupe | grep haproxy
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      0          5749091    2935/haproxy        
tcp        0      0 0.0.0.0:9999            0.0.0.0:*               LISTEN      0          5749092    2935/haproxy        
tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      0          5749090    2935/haproxy        
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      0          5749089    2935/haproxy        
tcp        0      0 0.0.0.0:5000            0.0.0.0:*               LISTEN      0          5749088    2935/haproxy        
udp        0      0 0.0.0.0:44146           0.0.0.0:*                           980        5749130    2935/haproxy        
udp        0      0 0.0.0.0:38187           0.0.0.0:*                           980        5751550    2935/haproxy        
udp        0      0 0.0.0.0:59791           0.0.0.0:*                           980        5750749    2935/haproxy        
udp        0      0 0.0.0.0:51959           0.0.0.0:*                           980        5747082    2935/haproxy      

#浏览器访问:https://172.25.254.100/

浏览器访问

此方法会发生的问题:如果不访问https会自动访问http

解决方法:

全站加密

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
#注意修改
frontend webcluster
    bind *:80
    mode http
    redirect scheme https if !{ ssl_fc }  #如果不是ssl,会自动跳转到下方的https

backend webcluster-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

listen web-https
    bind *:443 ssl crt /etc/haproxy/certs/haha.pem
    mode http
    balance roundrobin
    server db1 172.25.254.10:80 check inter 2 fall 2 rise 5
    server db2 172.25.254.20:80 check inter 2 fall 2 rise 5
[root@haproxy ~]# systemctl restart haproxy.service
#浏览器访问172.25.254.100,发现会自动跳转到https

5.8 子配置文件

在编写/lib/systemd/system/haproxy.service中如果编写的过多看起来会非常的臃肿,这时我们就可以把配置写到子配置文件中,以此来达到同样的效果。

#查看服务目录
[root@haproxy ~]# vim /lib/systemd/system/haproxy.service
[Unit]
Description=HAProxy Load Balancer
After=network-online.target
Wants=network-online.target

[Service]
EnvironmentFile=-/etc/sysconfig/haproxy
Environment="CONFIG=/etc/haproxy/haproxy.cfg" "PIDFILE=/run/haproxy.pid" "CFGDIR=/etc/haproxy/conf.d" #子配置文件目录:/etc/haproxy/conf.d
ExecStartPre=/usr/sbin/haproxy -f $CONFIG -f $CFGDIR -c -q $OPTIONS
ExecStart=/usr/sbin/haproxy -Ws -f $CONFIG -f $CFGDIR -p $PIDFILE $OPTIONS
ExecReload=/usr/sbin/haproxy -f $CONFIG -f $CFGDIR -c -q $OPTIONS
ExecReload=/bin/kill -USR2 $MAINPID
KillMode=mixed
SuccessExitStatus=143
Type=notify

[Install]
WantedBy=multi-user.target

#编写子配置文件
[root@haproxy ~]# cd /etc/haproxy/conf.d
[root@haproxy conf.d]# vim webcluster.cfg
listen stats
    mode http
    bind *:9999
    stats enable
    log global
    stats uri /status
    stats auth haha:haha 

[root@haproxy conf.d]# systemctl restart haproxy.service 
Warning: The unit file, source configuration file or drop-ins of haproxy.service changed on disk. Run 'systemctl daemon-reload' to reload units.
#查看了/lib/systemd/system/haproxy.service文件之后重启需要输入systemctl daemon-reload,才可以生效
[root@haproxy conf.d]# systemctl daemon-reload
#浏览器访问:                                                                                                                                                                                                 172.25.254.100:9999/status

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值