haproxy

1、haproxy介绍

HAProxy是法国开发者威利塔罗(Willy Tarreau)在2000年使用C语言开发的一个开源软件,是一款具备高并发(一万以上)、高性能的TCP和HTTP负载均衡器,支持基于cookie的持久性,自动故障切换,支持正则表达式及web状态统计。

No Load Balancing

Layer 4 Load Balancing

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

Layer 7 Load Balancing

根据应用层信息(例如URI、Cookie、 HTTP header等信息)进行解析,决定是否需要进行负载均衡

从2013年HAProxy 分为社区版和企业版,企业版将提供更多的特性和功能以及全天24小时的技术支持等服务。

企业版网站:HAProxy Technologies | Powering the World's Busiest Applications

社区版网站:HAProxy - The Reliable, High Perf. TCP/HTTP Load Balancer

github:https://github.com/haproxy

2、haproxy安装及配置

复制代码
[root@haproxy ~]# yum install haproxy -y
[root@haproxy ~]# haproxy -v
HAProxy version 2.4.22-f8e3218 2023/02/14 - https://haproxy.org/
# haproxy的主配置文件:/etc/haproxy/haproxy.cfg

2.1 配置文件说明

官方文档: HAProxy version 2.4.36 - Configuration Manual

HAProxy 的配置文件/etc/haproxy/haproxy.cfg由两大部分组成,分别是: global:全局配置段

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

proxies:代理配置段

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

2.1.1 全局配置段global配置

复制代码
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
global
    log         127.0.0.1 local2  #定义日志输出设置,local2是日志输出设置
    chroot      /var/lib/haproxy  #修改haproxy的工作目录至指定的目录
    pidfile     /var/run/haproxy.pid  #指定pid文件
    maxconn     4000    #默认最大连接数
    user        haproxy  #指定haproxy的运行用户
    group       haproxy  #指定haproxy的运行组
    daemon   #让haproxy以守护进程的方式工作于后台
    stats socket /var/lib/haproxy/stats  #指定haproxy的套接字文件
    nbproc 2 #指定haproxy的worker进程数量, 默认是1个
	cpu-map 1 0 #指定第一个work绑定第一个cpu核心
	cpu-map 2 1 #指定第二个work绑定第二个cpu核心
	nbthread 2 #指定haproxy的线程数量, 默认每个进程一个线程, 此参数与nbproc互斥
	maxsslconn 100000 #每个haproxy进程ssl最大连接数,用于haproxy配置了证书的场景下
	maxconnrate 100 #指定每个客户端每秒建立连接的最大数量

haproxy.cfg文件中定义了chroot、pidfile、user、group等参数,如果系统没有相应的资源会导致haproxy无法启动,具体参考日志文件 /var/log/messages。

复制代码
#yum安装的haproxy提供了service文件
[root@haproxy ~]# cat /usr/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"
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 ~]# systemctl restart haproxy.service
[root@haproxy ~]# pstree -p | grep haproxy
           |-haproxy(27783)---haproxy(27785)-+-{haproxy}(27786)
           |                                 |-{haproxy}(27787)
           |                                 `-{haproxy}(27788)

(1)启用多进程

复制代码
#在global中添加如下配置
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg   
global
    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(28090)-+-haproxy(28092)
           |                `-haproxy(28093)
[root@haproxy ~]# ps -axo pid,psr,cmd  | grep haproxy | grep -v grep
  28090   3 /usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -f /etc/haproxy/conf.d -p /run/haproxy.pid
  28092   0 /usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -f /etc/haproxy/conf.d -p /run/haproxy.pid
  28093   1 /usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -f /etc/haproxy/conf.d -p /run/haproxy.pid

(2)启用多线程

复制代码
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg   
global
    #nbproc  2
    #cpu-map 1 0
    #cpu-map 2 1
    nbthread 4
[root@haproxy ~]# systemctl restart haproxy
[root@haproxy ~]# pstree -p | grep haproxy | grep -v grep
           |-haproxy(28223)---haproxy(28225)-+-{haproxy}(28226)
           |                                 |-{haproxy}(28227)
           |                                 `-{haproxy}(28228)

#查看指定进程下的线程
[root@haproxy ~]# ps -T -p 28355
    PID    SPID TTY          TIME CMD
  28355   28355 ?        00:00:00 haproxy
  28355   28356 ?        00:00:00 haproxy
  28355   28357 ?        00:00:00 haproxy
  28355   28358 ?        00:00:00 haproxy
[root@haproxy ~]# cat /proc/28355/status | grep Thr
Threads:        4

2.1.2 代理配置段proxies

官方文档:HAProxy version 2.4.36 - Configuration Manual

复制代码
defaults [<name>] #默认配置项,针对以下的frontend、backend和listen生效,可以多个name也可以没有name
frontend <name>   #前端servername,类似于Nginx的一个虚拟主机 server和LVS服务集群
backend  <name>   #后端服务器组,等于nginx的upstream和LVS中的RS服务器
listen   <name>   #将frontend和backend合并在一起配置,相对于frontend和backend配置更简洁,生产常用

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

Proxies配置-defaults

defaults 配置参数:

复制代码
defaults
    mode                    http  #使用协议,http是七层,tcp是四层
    log                     global   #全局日志记录
    option                  httplog  #日志记录选项, httplog表示记录与 HTTP会话相关的各种属性值
    option                  dontlognull  #表示不记录空会话连接日志
    option http-server-close  #等待客户端完整HTTP请求的时间, 此处为等待10s。
    option forwardfor       except 127.0.0.0/8 #透传客户端真实IP至后端web服务器
    option                  redispatch  #当server Id对应的服务器挂掉后,强制定向到其他健康的服务器,重新派发
    retries                 3  #连接后端服务器失败次数
    timeout http-request    10s #等待客户端完整HTTP请求的最大允许时间 
    timeout queue           1m  #如果请求在队列中等待时间超过 1m,haproxy会返回503错误
    timeout connect         10s  #客户端请求从haproxy到后端server的连接最长等待时间(TCP连接之前),默认单位ms
    timeout client          1m  #设置haproxy与客户端的最长非活动时间,默认单位ms,建议和timeout server相同
    timeout server          1m  #客户端请求从haproxy到后端服务端的请求处理超时时长(TCP连接之后),默认单位ms,如果超时,会出现502错误,此值建议设置较大些,访止502错误
    timeout http-keep-alive 10s  #session 会话保持超时时间,此时间段内会转发到相同的后端服务器
    timeout check           10s  #对后端服务器的默认检测超时时间
    maxconn                 3000

Proxies配置-frontend

frontend 配置参数:

复制代码
#指定HAProxy的监听地址,可以是IPV4或IPV6,可以同时监听多个IP或端口,可同时用于listen字段中,格式如下:
bind [<address>]:<port_range> [, ...] [param*]

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

示例:

复制代码
frontend  jungle-web               #可以采用:业务-服务-端口号 形式命名
    bind :80,:8080
    bind 10.0.0.7:10080,:8801-8810,10.0.0.17:9001-9010
    mode  http|tcp              #指定负载协议类型
    use_backend <backend_name>  #调用的后端服务器组名称

Proxies配置-backend

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

复制代码
backend
	mode  http|tcp      #指定负载协议类型,和对应的frontend必须一致
	server              #定义后端real server

server配置如下:

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

2.2 frontend+backend配置实例

示例

复制代码
frontend jungle-web
    bind :80,:8080
    mode tcp
    use_backend jungle-web-nodes

backend jungle-web-nodes
    mode tcp
    server web1 192.168.150.14:80 check weight 2 addr 192.168.150.114 port 8080  #设定后端业务服务器ip为192.168.150.14:80,健康状态监测为192.168.150.114:8080
    server web2 192.168.150.15:80 check
主机名 ip地址 说明
haproxy 192.168.168.30 代理服务器
web1 192.168.168.62 web服务器(nginx提供)
web2 192.168.168.63 web服务器(nginx提供)
client 192.168.168.198 客户端
复制代码
#haproxy的配置
[root@haproxy ~]# tail -10 /etc/haproxy/haproxy.cfg
frontend  jungle-web
    bind 192.168.168.30:80
    mode http
    use_backend  jungle-web-nodes

backend jungle-web-nodes
    mode  http
    option forwardfor
    server web1 192.168.168.62:80   check inter 3000 fall 3 rise 5
    server web2 192.168.168.63:80   check inter 3000 fall 3 rise 5
[root@haproxy ~]# systemctl restart haproxy
#客户端测试
[root@client ~]# for i in {1..10};do curl 192.168.168.30;done
web1 192.168.168.62
web2 192.168.168.63
web1 192.168.168.62
web2 192.168.168.63
web1 192.168.168.62
web2 192.168.168.63
web1 192.168.168.62
web2 192.168.168.63
web1 192.168.168.62
web2 192.168.168.63

2.3 listen配置实例

使用listen替换上面的frontend和backend的配置方式,可以简化设置

复制代码
[root@haproxy ~]# tail -7 /etc/haproxy/haproxy.cfg
listen jungle-web-all
    bind 192.168.168.30:80
    mode http
    option  forwardfor
    server web1 192.168.168.62:80   check inter 3000 fall 3 rise 5 weight 2
    server web2 192.168.168.63:80   check inter 3000 fall 3 rise 5

#客户端访问
[root@client ~]# for i in {1..10};do curl 192.168.168.30;done
web1 192.168.168.62
web2 192.168.168.63
web1 192.168.168.62
web1 192.168.168.62
web2 192.168.168.63
web1 192.168.168.62
web1 192.168.168.62
web2 192.168.168.63
web1 192.168.168.62
web1 192.168.168.62

当业务众多时,将所有配置都放在一个配置文件中,会造成维护困难。可以考虑按业务分类,将配置信息拆分,放在子配置目录下的不同的.cfg子配置文件中。

2.4 haproxy日志文件配置

默认情况下haproxy的日志在/var/log/messages,可以使用rsyslog来让HAProxy单独输出日志到指定文件。

复制代码
[root@haproxy ~]# vim log /etc/haproxy/haproxy.cfg
global
    log         127.0.0.1 local2  #所有haproxy的日志推送到rsyslog的local2接口
    log 127.0.0.1 local1 warning  #将warn级(及以上)的日志推送到rsyslog的local1接口
defaults
    mode                    http
    log                     global  #所有frontend都默认使用global中的日志配置

注:在生产环境中,建议将日志级别调整为notice。

复制代码
[root@haproxy ~]# vim  /etc/rsyslog.d/haproxy.conf
$ModLoad imudp  #加载rsyslog的udp模块
$UDPServerRun 514  #监听514端口
local2.*     /var/log/haproxy.log  #local2接口对应的日志输出文件
local1.*     /var/log/haproxy_warn.log  #local1接口对应的日志输出文件
复制代码
#重启rsyslog和HAProxy
[root@haproxy ~]# systemctl restart haproxy rsyslog
[root@haproxy ~]# ll  /var/log/haproxy*
-rw------- 1 root root 1039  9月 23 17:46 /var/log/haproxy.log
-rw------- 1 root root 1039  9月 23 17:46 /var/log/haproxy_warn.log

3、 haproxy调度算法

HAProxy通过固定参数balance指明对后端服务器的调度算法,该参数可以配置在listen或backend选项中。

HAProxy的调度算法分为静态和动态调度算法,但是有些算法可以根据参数在静态和动态算法中相互转换。

官方文档:HAProxy version 2.4.36 - Configuration Manual

3.1 静态算法

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

3.1.1 static-rr

static-rr:基于权重的轮询调度,不支持运行时动态调整权重及后端服务器慢启动,其后端主机数量没有限制,相当于LVS中的 wrr。

复制代码
listen  web_host
  bind 10.0.0.7:80,:8801-8810,10.0.0.7:9001-9010
  mode http
  log global
  balance static-rr
  server web1  10.0.0.17:80 weight 1 check inter 3000 fall 2 rise 5
  server web2  10.0.0.27:80 weight 2 check inter 3000 fall 2 rise 5
复制代码
[root@haproxy ~]# cd /etc/haproxy/conf.d
[root@haproxy conf.d]# cat haproxy-rr.cfg
listen jungle-web-rr
    bind 192.168.168.30:81
    mode http
    balance static-rr  #设置算法
    option  forwardfor
    server web1 192.168.168.62:80   check inter 3000 fall 3 rise 5 weight 2
    server web2 192.168.168.63:80   check inter 3000 fall 3 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service

测试:

复制代码
[root@client ~]# for i in {1..10};do curl 192.168.168.30:81;done
web1 192.168.168.62
web1 192.168.168.62
web2 192.168.168.63
web1 192.168.168.62
web1 192.168.168.62
web2 192.168.168.63
web1 192.168.168.62
web1 192.168.168.62
web2 192.168.168.63
web1 192.168.168.62

3.1.2 first

first:根据服务器在列表中的位置,自上而下进行调度,只有当第一台服务器的连接数达到上限,新请求才会分配给下一台服务器,因此会忽略服务器的权重设置,此方式使用较少

复制代码
[root@haproxy conf.d]# cat haproxy-first.cfg
listen  jungle-web-first
  bind 192.168.168.30:82
  mode http
  log global
  balance first
  server web1  192.168.168.62:80 maxconn 2 weight 1 check inter 3000 fall 2 rise 5
  server web2  192.168.168.63:80 weight 1 check inter 3000 fall 2 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service

测试

复制代码
[root@client ~]# for i in {1..10};do curl 192.168.168.30:82;done
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
#在web服务器上配置limit_rate 1k;限速
#开启两个客户端下载文件
[root@client ~]# wget 192.168.168.30:82/test.html
[root@client ~]# wget 192.168.168.30:82/test1.html
#查看web服务
[root@web1 html]# ss -tnpe | grep 80
ESTAB 0      0      192.168.168.62:80   192.168.168.197:48372 users:(("nginx",pid=1717,fd=16)) uid:985 ino:26909 sk:1 cgroup:/system.slice/nginx.service <->            
ESTAB 0      0      192.168.168.62:80   192.168.168.197:35446 users:(("nginx",pid=1717,fd=14)) uid:985 ino:26904 sk:2 cgroup:/system.slice/nginx.service <-> 
[root@client ~]# for i in {1..10};do curl 192.168.168.30:82;done
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63

3.2 动态算法

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

3.2.1 roundrobin

roundrobin:基于权重的轮询动态调度算法,支持权重的运行时调整,不同于lvs中的rr轮询模式,HAProxy中的roundrobin支持慢启动(新加的服务器会逐渐增加转发数),其每个后端backend中最多支持4095个real server,支持对real server权重动态调整,roundrobin为默认调度算法

复制代码
[root@haproxy conf.d]# cat haproxy-roundrobin.cfg
listen  jungle-web-roundrobin
  bind 192.168.168.30:83
  mode http
  log global
  balance roundrobin
  server web1  192.168.168.62:80  weight 1 check inter 3000 fall 2 rise 5
  server web2  192.168.168.63:80 weight 1 check inter 3000 fall 2 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service

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

复制代码
#修改配置文件
[root@haproxy conf.d]# vim /etc/haproxy/haproxy.cfg
global
    stats socket /var/lib/haproxy/stats mode 600 level admin

[root@haproxy conf.d]# systemctl restart haproxy
复制代码
#使用socat对服务器动态权重调整
[root@haproxy conf.d]# yum install -y socat
#查看帮助
[root@haproxy conf.d]# echo help | socat stdio /var/lib/haproxy/stats

#查看当前进程信息
[root@haproxy conf.d]# 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

#查看后端服务器
[root@haproxy conf.d]# echo "show backend" | socat stdio /var/lib/haproxy/stats
# name
jungle-web-all
jungle-web-first
jungle-web-roundrobin
jungle-web-rr

#查看当前代理的主机状态信息
[root@haproxy conf.d]# echo "show servers state" | socat stdio /var/lib/haproxy/stats
1
# be_id be_name srv_id srv_name srv_addr srv_op_state srv_admin_state srv_uweight srv_iweight srv_time_since_last_change srv_check_status srv_check_result srv_check_health srv_check_state srv_agent_state bk_f_forced_id srv_f_forced_id srv_fqdn srv_port srvrecord srv_use_ssl srv_check_port srv_check_addr srv_agent_addr srv_agent_port
2 jungle-web-all 1 web1 192.168.168.62 2 0 2 2 256 6 3 7 6 0 0 0 - 80 - 0 0 - - 0
2 jungle-web-all 2 web2 192.168.168.63 2 0 1 1 256 6 3 7 6 0 0 0 - 80 - 0 0 - - 0
3 jungle-web-first 1 web1 192.168.168.62 2 0 1 1 256 6 3 6 6 0 0 0 - 80 - 0 0 - - 0
3 jungle-web-first 2 web2 192.168.168.63 2 0 1 1 256 6 3 6 6 0 0 0 - 80 - 0 0 - - 0
4 jungle-web-roundrobin 1 web1 192.168.168.62 2 0 1 1 256 6 3 6 6 0 0 0 - 80 - 0 0 - - 0
4 jungle-web-roundrobin 2 web2 192.168.168.63 2 0 1 1 256 6 3 6 6 0 0 0 - 80 - 0 0 - - 0
5 jungle-web-rr 1 web1 192.168.168.62 2 0 2 2 256 6 3 7 6 0 0 0 - 80 - 0 0 - - 0
5 jungle-web-rr 2 web2 192.168.168.63 2 0 1 1 256 6 3 7 6 0 0 0 - 80 - 0 0 - - 0

#查看权重
[root@haproxy conf.d]# echo "get weight jungle-web-roundrobin/web1 " | socat stdio /var/lib/haproxy/stats
1 (initial 1)
#修改权重
[root@haproxy conf.d]# echo "set weight jungle-web-roundrobin/web1 3 " | socat stdio /var/lib/haproxy/stats
[root@haproxy conf.d]# echo "get weight jungle-web-roundrobin/web1 " | socat stdio /var/lib/haproxy/stats
3 (initial 1)
#客户端测试
[root@client ~]# for i in {1..10};do curl 192.168.168.30:83;done
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web2 192.168.168.63
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web2 192.168.168.63
web1 192.168.168.62
web1 192.168.168.62

#将后端服务器禁用
[root@haproxy conf.d]# echo "disable server jungle-web-roundrobin/web1 " | socat stdio /var/lib/haproxy/stats
#测试
[root@client ~]# for i in {1..10};do curl 192.168.168.30:83;done
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63


#将后端服务软下线
[root@haproxy conf.d]# echo "set weight jungle-web-roundrobin/web1 0 " | socat stdio /var/lib/haproxy/stats
[root@haproxy conf.d]# echo "get weight jungle-web-roundrobin/web1 " | socat stdio /var/lib/haproxy/stats
0 (initial 1)
#客户端测试
[root@client ~]# for i in {1..3};do curl 192.168.168.30:83;done
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63

在 HAProxy 启用多进程(nbproc)时,修改一个进程的权重不会自动同步到其他进程。因为默认情况下,所有进程共享同一个 stats socket(会导致命令仅作用于随机一个进程)。

可以在 global段配置多个 Socket,绑定到不同路径:

复制代码
global    
	nbproc 2     # 启动 2 个进程    
	stats socket /var/lib/haproxy/stats1 level admin process 1    
	stats socket /var/lib/haproxy/stats2 level admin process 2    

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

3.2.2 leastconn

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

复制代码
[root@haproxy conf.d]# cat haproxy-leastconn.cfg
listen  jungle-web-leastconn
  bind 192.168.168.30:84
  mode http
  log global
  balance leastconn
  #web1上有3个连接的情况等于web2上有一个连接
  server web1  192.168.168.62:80  weight 3 check inter 3000 fall 2 rise 5  
  server web2  192.168.168.63:80 weight 1 check inter 3000 fall 2 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service

测试

复制代码
[root@client ~]# wget 192.168.168.30:84/test.html
#可以在web上查看连接被调度至哪个后端
[root@web2 html]#  ss -tnpe | grep 80
[root@client ~]# for i in {1..3};do curl 192.168.168.30:84;done
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63

3.2.3 random

在1.9版本开始增加一个叫做random的负载平衡算法,其基于随机数作为一致性hash的key,随机负载均衡对于大型服务器场景或经常添加或删除服务器非常有用,支持weight的动态调整,weight较大的主机有更大概率获取新请求。

复制代码
[root@haproxy conf.d]# cat haproxy-random.cfg
listen  jungle-web-random
  bind 192.168.168.30:85
  mode http
  log global
  balance random
  server web1  192.168.168.62:80  weight 1 check inter 3000 fall 2 rise 5
  server web2  192.168.168.63:80 weight 1 check inter 3000 fall 2 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service
复制代码
[root@client ~]# for i in {1..10};do curl 192.168.168.30:85;done
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
web1 192.168.168.62
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63

3.3 其他算法

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

3.3.1 source

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

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

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

  • map-base取模法

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

复制代码
map-based算法:基于权重取模,hash(客户端IP) % sum(所有服务器的权重)
  • 一致性hash

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

复制代码
1、key1=hash(source_ip)%(2^32)  [0---4294967295]
2、keyA=hash(后端服务器虚拟ip)%(2^32)
3、将key1和keyA都放在hash环上,按顺时针将用户请求调度到离key1最近的keyA对应的后端服务器
复制代码
#map-base取模法
[root@haproxy conf.d]# cat haproxy-source-map-based.cfg
listen  jungle-web-source-map-based
  bind 192.168.168.30:86
  mode http
  log global
  balance source
  hash-type map-based
  server web1  192.168.168.62:80  weight 1 check inter 3000 fall 2 rise 5
  server web2  192.168.168.63:80 weight 1 check inter 3000 fall 2 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service
[root@client ~]# for i in {1..10};do curl 192.168.168.30:86;done
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
#修改权重,只支持调整为0或者100%
[root@haproxy conf.d]# echo "set weight jungle-web-source-map-based/web1 0 " | socat stdio /var/lib/haproxy/stats

[root@haproxy conf.d]# echo "set weight jungle-web-source-map-based/web1 2 " | socat stdio /var/lib/haproxy/stats
Backend is using a static LB algorithm and only accepts weights '0%' and '100%'.
复制代码
#一致性hash配置示例
[root@haproxy conf.d]# cat haproxy-source-consistent.cfg
listen  jungle-web-source-consistent
  bind 192.168.168.30:87
  mode http
  log global
  balance source
  hash-type consistent
  server web1  192.168.168.62:80  weight 1 check inter 3000 fall 2 rise 5
  server web2  192.168.168.63:80 weight 1 check inter 3000 fall 2 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service
[root@client ~]# for i in {1..10};do curl 192.168.168.30:87;done
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
#调整权重
[root@haproxy conf.d]# echo "set weight jungle-web-source-consistent/web1 2 " | socat stdio /var/lib/haproxy/stats
[root@haproxy conf.d]# echo "get weight jungle-web-source-consistent/web1  " | socat stdio /var/lib/haproxy/stats
2 (initial 1)

3.3.2 uri

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

注意:此算法是应用层,只支持 mode http ,不支持 mode tcp

复制代码
<scheme>://<user>:<password>@<host>:<port>/<path>?<query>#<frag>
左半部分:/<path>
整个uri:/<path>?<query>#<frag>  #对应算法写法 balance uri whole
复制代码
#uri 取模法配置示例
[root@haproxy conf.d]# cat haproxy-uri-map-based.cfg
listen  jungle-web-uri-map-based
  bind 192.168.168.30:88
  mode http
  log global
  balance uri
  hash-type map-based
  server web1  192.168.168.62:80  weight 1 check inter 3000 fall 2 rise 5
  server web2  192.168.168.63:80 weight 1 check inter 3000 fall 2 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service
#配置web
[root@web1 html]# echo web1 index1 > index1.html
[root@web2 html]# echo web2 index1 > index1.html
#访问不同uri,请求会被转发到相同的后端
[root@client ~]# curl 192.168.168.30:88
web2 192.168.168.63
[root@client ~]# curl 192.168.168.30:88/index1.html
web2 index1
[root@client ~]# curl 192.168.168.30:88/index2.html
web1 index2
复制代码
[root@haproxy conf.d]# cat haproxy-uri-consistent.cfg
listen  jungle-web-uri-consistent
  bind 192.168.168.30:89
  mode http
  log global
  balance uri
  hash-type consistent
  server web1  192.168.168.62:80  weight 1 check inter 3000 fall 2 rise 5
  server web2  192.168.168.63:80 weight 1 check inter 3000 fall 2 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service
#测试
[root@client ~]# curl 192.168.168.30:89/index2.html
web2 index2
[root@client ~]# curl 192.168.168.30:89/index2.html
web2 index2

3.3.3 url_param

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

复制代码
#url_param取模法配置示例
[root@haproxy conf.d]# cat haproxy-url-map-based.cfg
listen  jungle-web-url-map-based
  bind 192.168.168.30:90
  mode http
  log global
  balance url_param userid
  hash-type map-based
  server web1  192.168.168.62:80  weight 1 check inter 3000 fall 2 rise 5
  server web2  192.168.168.63:80 weight 1 check inter 3000 fall 2 rise 5
[root@haproxy conf.d]# systemctl restart haproxy
#测试
[root@client ~]# for i in {1..4};do curl 192.168.168.30:90;done
web1 192.168.168.62
web2 192.168.168.63
web1 192.168.168.62
web2 192.168.168.63
[root@client ~]# for i in {1..4};do curl 192.168.168.30:90/?userid=zhao;done
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
复制代码
#url_param一致性hash配置示例
[root@haproxy conf.d]# cat haproxy-url-consistent.cfg
listen  jungle-web-url-consistent
  bind 192.168.168.30:91
  mode http
  log global
  balance url_param userid
  hash-type consistent
  server web1  192.168.168.62:80  weight 1 check inter 3000 fall 2 rise 5
  server web2  192.168.168.63:80 weight 1 check inter 3000 fall 2 rise 5
[root@haproxy conf.d]# systemctl restart haproxy
#测试
[root@client ~]#  for i in {1..4};do curl 192.168.168.30:91/?userid=zhao;done
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63

3.3.4 hdr

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

复制代码
#hdr取模法配置示例
[root@haproxy conf.d]# cat haproxy-hdr-map-based.cfg
listen  jungle-web-hdr-map-based
  bind 192.168.168.30:92
  mode http
  log global
  balance hdr(User-Agent)
  hash-type map-based
  server web1  192.168.168.62:80  weight 1 check inter 3000 fall 2 rise 5
  server web2  192.168.168.63:80 weight 1 check inter 3000 fall 2 rise 5
[root@haproxy conf.d]# systemctl restart haproxy
[root@client ~]#  for i in {1..4};do curl 192.168.168.30:92;done
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
web2 192.168.168.63
[root@client ~]# curl -A "testagent"   192.168.168.30:92
web2 192.168.168.63
[root@client ~]# curl -A "testagent"   192.168.168.30:92
web2 192.168.168.63
复制代码
#hdr取模法配置示例
[root@haproxy conf.d]# cat haproxy-hdr-consistent.cfg
listen  jungle-web-hdr-consistent
  bind 192.168.168.30:93
  mode http
  log global
  balance hdr(User-Agent)
  hash-type consistent
  server web1  192.168.168.62:80  weight 1 check inter 3000 fall 2 rise 5
  server web2  192.168.168.63:80 weight 1 check inter 3000 fall 2 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service
#测试
[root@client ~]# curl -A "testagent"   192.168.168.30:93
web2 192.168.168.63
[root@client ~]# curl 192.168.168.30:93
web1 192.168.168.62
[root@client ~]# curl 192.168.168.30:93
web1 192.168.168.62

3.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

各算法使用场景

复制代码
first       #使用较少

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

leastconn   #数据库
source      #基于客户端公网IP的会话保持

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

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

4、haproxy高级功能

4.1 haproxy的状态页

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

官方帮助:HAProxy version 2.4.36 - Configuration Manual

状态页配置项

复制代码
stats enable          #基于默认的参数启用stats page
stats hide-version    #将状态页中haproxy版本隐藏
stats refresh <delay> #设定自动刷新时间间隔,默认不自动刷新
stats uri <prefix>   #自定义stats page uri,默认值:/haproxy?stats 
stats realm <realm>  #账户认证时的提示信息,示例:stats realm   HAProxy\ Statistics
stats auth <user>:<passwd>  #认证时的账号和密码,可使用多次,默认:no authentication,可有多行用户
stats admin { if | unless } <cond> #启用stats page中的管理功能
复制代码
[root@haproxy conf.d]# cat  stats.cfg
listen stats
  bind :9999
  stats enable
  #stats hide-version
  stats uri  /haproxy-stats
  stats realm HAPorxy\ Stats\ Page
  stats auth haadmin:123456  #两个用户
  stats auth admin:123456
  #stats refresh 30s
  stats admin if TRUE  #安全原因,不建议打开
[root@haproxy conf.d]# systemctl restart haproxy.service
复制代码
pid = 13340 (process #1, nbproc = 1, nbthread = 1) #pid为当前pid号,process为当前进程号,nbproc和nbthread为一共多少进程和每个进程多少个线程
uptime = 0d 0h01m03s; warnings = 1  #启动了多长时间
system limits: memmax = unlimited; ulimit-n = 200038  #系统资源限制:内存;最大打开文件数
maxsock = 200038; maxconn = 100000; reached = 0; maxpipes = 0 #最大socket连接数;单进程最大连接数;最大管道数maxpipes
current conns = 4; current pipes = 0/0; conn rate = 0/sec; bit rate = 0.000 kbps   #当前连接数;当前管道数;当前连接速率
Running tasks: 0/25 (0 niced); 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 or backup DOWN for maintenance (MAINT) #active或者backup服务器人为下线的
active or backup SOFT STOPPED for maintenance #active或者backup被人为软下线(人为将weight改成0)

backend server信息

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

4.2 基于cookie的会话保持

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

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

配置选项

复制代码
cookie name  [ rewrite | insert | prefix ][ indirect ] [ nocache ][ postonly ] [ preserve ][ httponly ] [ secure ][ domain ]* [ maxidle <idle> ][ maxlife ]

name:       #cookie 的key名称,用于实现持久连接
insert:     #插入新的cookie,默认不插入cookie
indirect:   #如果客户端已经有cookie,则不会再发送cookie信息
nocache:    #当client和haproxy之间有缓存服务器(如:CDN)时,不允许中间缓存器缓存cookie,因为这会导致很多经过同一个CDN的请求都发送到同一台后端服务器
复制代码
[root@haproxy conf.d]# cat cookie.cfg
listen jungle-web-cookie
  bind 192.168.168.30:8001
  mode http
  balance roundrobin
  cookie websrv insert nocache indirect  #insert表示如果客户端请求没有 websrvCookie,HAProxy 自动插入一个 Cookie
  server web1 192.168.168.62:80  check inter 3000 fall 3 rise 5 cookie web1
  server web2 192.168.168.63:80 check cookie web2
[root@haproxy conf.d]# systemctl restart haproxy.service
复制代码
#测试
[root@client ~]# curl -I 192.168.168.30:8001
HTTP/1.1 200 OK
server: nginx/1.20.1
date: Tue, 23 Sep 2025 14:54:28 GMT
content-type: text/html
content-length: 20
last-modified: Tue, 23 Sep 2025 02:54:55 GMT
etag: "68d20bff-14"
accept-ranges: bytes
set-cookie: websrv=web1; path=/
cache-control: private

[root@client ~]# curl -I 192.168.168.30:8001
HTTP/1.1 200 OK
server: nginx/1.20.1
date: Tue, 23 Sep 2025 14:54:30 GMT
content-type: text/html
content-length: 20
last-modified: Tue, 23 Sep 2025 02:55:47 GMT
etag: "68d20c33-14"
accept-ranges: bytes
set-cookie: websrv=web2; path=/
cache-control: private

#携带cookie再次访问
[root@client ~]# curl -b  websrv=web1 192.168.168.30:8001
web1 192.168.168.62
[root@client ~]# curl -b  websrv=web2 192.168.168.30:8001
web2 192.168.168.63

4.3 IP透传

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

四层负载

在四层负载设备中,把client发送的报文目标地址(原来是负载均衡设备的IP地址),根据均衡设备设置选择对应的web服务器IP地址,这样client就可以直接跟此服务器建立TCP连接并发送数据,而四层负载自身不参与建立连接。

七层代理

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

4.3.1 四层ip透传

复制代码
[root@haproxy conf.d]# cat tcp.cfg
listen jungle-web-tcp
    bind 192.168.168.30:8002
    mode tcp
    balance roundrobin
    server web1 192.168.168.62:80 send-proxy check inter 3000 fall 3 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service
[root@client ~]# curl  192.168.168.30:8002
<html>
<head><title>400 Bad Request</title></head>
<body>
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
[root@web1 html]# tail -1 /var/log/nginx/access.log
192.168.168.197 - - [23/Sep/2025:23:14:32 +0800] "PROXY TCP4 192.168.168.197 192.168.168.62 50292 80" 400 0 "-" "-" 
#在nginx服务器上开启日志格式和proxy_protocol;变量proxy_protocol_addr 记录透传过来的客户端IP
http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent"  "$proxy_protocol_addr"';
    server {
        listen       80 proxy_protocol; #启用此项,将无法直接访问此网站,只能通过四层代理访问                      
}
[root@web1 html]# systemctl restart nginx

测试

复制代码
[root@client ~]# curl  192.168.168.30:8002
web1 192.168.168.62
[root@web1 html]# tail -1 /var/log/nginx/access.log
192.168.168.197 - - [23/Sep/2025:23:18:50 +0800] "GET / HTTP/1.1" 200 20 "-" "curl/7.29.0" "192.168.168.198"
复制代码
[root@haproxy conf.d]# mv tcp.cfg{,.bak}

4.3.2 七层IP透传

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

复制代码
option forwardfor [ except <network> ] [ header <name> ] [ if-none ]
	#[ except <network> ]:请求来自此处指定的网络时不予添加此首部,如haproxy自身所在网络
	#[ header <name> ]:使用自定义的首部名称,而非“X-Forwarded-For”,示例:X-client
	#[ if-none ]  如果没有首部才添加首部,如果有使用默认值
复制代码
[root@haproxy conf.d]# cat http.cfg
listen jungle-web-http
    option forwardfor #首部字段默认为:X-Forwarded-For
    bind 192.168.168.30:8003
    mode http
    balance roundrobin
    server web1 192.168.168.62:80  check inter 3000 fall 3 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service

配置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  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" "$proxy_add_x_forwarded_for"';


#tomcat 配置:conf目录下的server.xml
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
   prefix="localhost_access_log" suffix=".txt"
   pattern="%{X-Forwarded-For}i %h %l %u %t "%r" %s %b" />  

此处使用的nginx的后端

复制代码
http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" "$proxy_add_x_forwarded_for"';

    server {
        listen       80;
	}
}
[root@web1 html]# systemctl restart nginx

测试

复制代码
[root@client ~]# curl  192.168.168.30:8003
web1 192.168.168.62
[root@web1 html]# tail -1 /var/log/nginx/access.log
192.168.168.197 - - [23/Sep/2025:23:46:42 +0800] "GET / HTTP/1.1" 200 20 "-" "curl/7.29.0" "192.168.168.198" "192.168.168.198, 192.168.168.197"

4.4 报文修改

在http模式下,基于实际需求修改客户端的请求报文与响应报文,通过reqadd和reqdel在请求报文添加删除字段,通过rspadd与rspidel在响应报文中添加与删除字段。

官方文档:

复制代码
https://docs.haproxy.org/2.4/configuration.html#4.2-http-request
https://docs.haproxy.org/2.4/configuration.html#4.2-http-response

配置说明:

复制代码
http-request add-header <name> <fmt> [ { if | unless } <condition> ]
示例:http-request add-header X-Haproxy-Current-Date %T
http-request del-header <name> [ { if | unless } <condition> ]

http-response add-header <name> <fmt> [ { if | unless } <condition> ]
http-response del-header <name>
#示例:
http-response del-header Server 

4.4.1 修改请求报文

复制代码
[root@haproxy conf.d]# cat request.cfg
listen jungle-request
  bind 192.168.168.30:8004
  mode http
  balance roundrobin
  http-request add-header testheader haproxyserver
  http-request add-header haproxydate %T
  server web1 192.168.168.62:80  check inter 3000 fall 3 rise 5
[root@haproxy conf.d]# systemctl restart haproxy

后端web配置日志

复制代码
[root@web1 html]# vim /etc/nginx/nginx.conf
http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" "$proxy_add_x_forwarded_for" "$http_testheader" "$http_haproxydate"';
}
[root@web1 html]# systemctl restart nginx

后端服务时apache的httpd时日志配置

复制代码
[root@server2 ~]# vim /etc/httpd/conf/httpd.conf
LogFormat "%{testheader}i  %{haproxydate}i %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

测试

复制代码
[root@client ~]# curl  192.168.168.30:8004
web1 192.168.168.62

[root@web1 html]# tail -f /var/log/nginx/access.log
192.168.168.197 - - [24/Sep/2025:00:00:46 +0800] "GET / HTTP/1.1" 200 20 "-" "curl/7.29.0" "192.168.168.198" "192.168.168.198, 192.168.168.197" "haproxyserver" "23/Sep/2025:16:00:46 +0000"

4.4.2 修改响应报文

复制代码
[root@haproxy conf.d]# cat response.cfg
listen jungle-web-response
  bind 192.168.168.30:8005
  mode http
  balance roundrobin
  http-response del-header server
  http-response add-header server testnginx
  http-response add-header x-via haproxy
  server web1 192.168.168.62:80  check inter 3000 fall 3 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service

测试

复制代码
[root@client ~]# curl -I  192.168.168.30:8005
HTTP/1.1 200 OK
date: Tue, 23 Sep 2025 16:06:22 GMT
content-type: text/html
content-length: 20
last-modified: Tue, 23 Sep 2025 02:54:55 GMT
etag: "68d20bff-14"
accept-ranges: bytes
server: testnginx  #显示haproxy中设置的值
x-via: haproxy  #显示haproxy中设置的值

4.5 web服务状态监测

三种状态监测方式HAProxy version 2.4.36 - Configuration Manual

复制代码
基于四层的传输端口做状态监测,此为默认方式
基于指定 URI 做状态监测
基于指定 URI 的request请求头部内容做状态监测,建议使用此方式

基于应用层http协议进行健康性检测

基于应用层http协议,采用不同的监测方式,对后端real server进行状态监测

复制代码
option httpchk          #启用七层健康性检测,对tcp 和 http 模式都支持,默认请求为:“OPTIONS / HTTP/1.0”;默认2xx和3xx是有效码
option httpchk <uri>   #指定uri
option httpchk <method> <uri>  #指定请求方法和uri
option httpchk <method> <uri> <version>  #指定请求方法和uri以及HTTP协议版本

#不想使用默认有效码,可以指定期望以上检查得到的响应码
http-check expect [!] <match> <pattern>
#示例:
http-check expect status 200,201  #当检测状态码为200,201时为有效
http-check expect ! rstatus ^5  #当检测状态码为5xx时为错误

配置示例

复制代码
#后端web配置
[root@web1 html]# mkdir monitor/
[root@web1 html]# echo check1 > monitor/check.html

[root@haproxy conf.d]# cat mon.cfg
listen jungle-web-monitor
  bind 192.168.168.30:8006
  mode http
  balance  roundrobin
  #option httpchk GET /monitor/check.html
  #option httpchk GET /monitor/check.html HTTP/1.0
  #option httpchk GET /monitor/check.html HTTP/1.1  #注意:HTTP/1.1强制要求必须有Host字段 #使用HEAD减少网络流量
  option httpchk HEAD  /monitor/check.html HTTP/1.1 #使用HEAD减少网络流量
  http-check send hdr host www.realserver.com  #向后端传递host头,主要用在后端配置了虚拟主机的情况下
  server web1 192.168.168.62:80  check inter 3000 fall 3 rise 5
  server web2 192.168.168.63:80  check
  
#由于web2上没有健康检查的文件,所以认为web2离线
[root@client ~]#  for i in {1..4};do curl 192.168.168.30:8006;done
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62
web1 192.168.168.62

#web2上创建文件
[root@web2 html]# mkdir monitor/
[root@web2 html]# echo check2 > monitor/check.html
#再次测试
[root@client ~]#  for i in {1..4};do curl 192.168.168.30:8006;done
web1 192.168.168.62
web2 192.168.168.63
web1 192.168.168.62
web2 192.168.168.63

验证http监测:查看状态页,可以看到开启了七层检测功能:LastChk字段:L7

4.6 ACL

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

官方帮助:HAProxy version 2.4.36 - Configuration Manual

4.6.1 ACL配置选项

ACL配置选项

复制代码
acl   <aclname>  <criterion>  [flags]  [operator] <value>
acl    名称       匹配规范       匹配模式  具体操作符   操作对象类型

(1)ACL-Name:ACL名称

复制代码
#可以使用大字母A-Z、小写字母a-z、数字0-9、冒号、点、中横线和下划线,并且严格区分大小写,比如Image_site和image_site就是两个完全不同的acl

(2)ACL-criterion:定义ACL匹配规范,即:匹配条件

常用的匹配条件

条件 说明 示例
path 精确匹配 URL 路径 acl is_login path /login
path_beg 匹配 URL 路径开头 acl is_api path_beg /api
path_end 匹配 URL 路径结尾 acl is_jpg path_end .jpg
hdr(<Header>) 匹配 HTTP 请求头 acl is_json hdr(Content-Type) application/json
src 匹配客户端 IP acl is_local src 127.0.0.1
method 匹配 HTTP 方法 acl is_post method POST
ssl_fc 检查是否 HTTPS acl is_https ssl_fc
复制代码
hdr([<name> [,<occ>]]) #完全匹配字符串,如果未指定<occ>,默认匹配第一次出现的字段值
hdr_beg([<name> [,<occ>]]) #前缀匹配,header中指定匹配内容的begin
hdr_end([<name> [,<occ>]]) #后缀匹配,header中指定匹配内容end
hdr_dom([<name> [,<occ>]]) #域匹配,header中的domain name
hdr_dir([<name> [,<occ>]]) #路径匹配,header的uri路径
hdr_len([<name> [,<occ>]]) #长度匹配,header的长度匹配
hdr_reg([<name> [,<occ>]]) #正则表达式匹配,自定义表达式(regex)模糊匹配
hdr_sub([<name> [,<occ>]]) #子串匹配,header中的uri模糊匹配
复制代码
#示例:
hdr(<string>)   #用于测试请求头部首部指定内容
hdr_dom(host)   #请求的host名称,如 www.jungle.com
hdr_beg(host)   #请求的host开头,如 www.   img.   video. 
hdr_end(host)   #请求的host结尾,如 .com   .net   .cn 

#有些功能是类似的,比如以下几个都是匹配用户请求报文中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.

(3)ACL-flags:ACL匹配模式

复制代码
-i #不区分大小写
-m #使用指定的pattern匹配方法
-n #不做DNS解析
-u #禁止acl重名,否则多个同名ACL匹配或关系

(4)ACL-operator:ACL 操作符

复制代码
#整数比较:eq、ge、gt、le、lt
#字符比较:
- 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)ACL-value:value的类型

复制代码
The ACL engine can match these types against patterns of the following types :
- Boolean                    #布尔值
- integer or integer range   #整数或整数范围,比如用于匹配端口范围
- IP address / network       #IP地址或IP范围, 192.168.0.1,192.168.0.1/24
- string--> www.jungle.com
  exact –精确比较
  substring—子串
  suffix-后缀比较
  prefix-前缀比较
  subdir-路径, /wp-includes/js/jquery/jquery.js
  domain-域名,www.jungle.com
- regular expression      #正则表达式
- hex block               #16进制

4.6.2 ACL调用方式

复制代码
与:隐式(默认)使用
或:使用“or” 或 “||”表示
否定:使用 "!" 表示  

#示例:
if valid_src valid_port         #与关系,A和B都要满足为true,默认为与
if invalid_src || invalid_port  #或,A或者B满足一个为true
if ! invalid_src                #非,取反,不满足为true

4.6.3 ACL示例-域名匹配

复制代码
[root@haproxy ~]# cd /etc/haproxy/conf.d/
[root@haproxy conf.d]# cat acl.cfg
frontend jungle-acl
  bind 192.168.168.30:8100
  mode http
  balance roundrobin
  log global
  ###################### acl setting ###############################
  acl pc_domain hdr_dom(host) -i www.jungle.org
  acl mobile_domain hdr_dom(host) -i mobile.jungle.org

  ###################### acl hosts #################################
  use_backend pc_hosts if pc_domain
  use_backend mobile_hosts if mobile_domain
  default_backend pc_hosts

###################### backend hosts #############################
backend mobile_hosts
  mode http
  server web1 192.168.168.62:80 check inter 2000 fall 3 rise 5

backend pc_hosts
  mode http
  server web2 192.168.168.63:80 check inter 2000 fall 3 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service

测试

复制代码
[root@client ~]# echo "192.168.168.30 www.jungle.org mobile.jungle.org" >> /etc/hosts
[root@client ~]# curl mobile.jungle.org:8100
web1 192.168.168.62
[root@client ~]# curl www.jungle.org:8100
web2 192.168.168.63
[root@client ~]# echo "192.168.168.30 test.jungle.org" >> /etc/hosts
[root@client ~]# curl test.jungle.org:8100
web2 192.168.168.63

4.6.4 ACL示例---基于源ip或子网调度访问

复制代码
[root@haproxy conf.d]# cat acl.cfg
frontend jungle-acl
  bind 192.168.168.30:8100
  mode http
  balance roundrobin
  log global
  ###################### acl setting ###############################
  acl pc_domain hdr_dom(host) -i www.jungle.org
  acl mobile_domain hdr_dom(host) -i mobile.jungle.org
  acl ip_range_test src 172.18.0.0/16 192.168.168.30
  ###################### acl hosts #################################
  use_backend pc_hosts if ip_range_test
  use_backend pc_hosts if pc_domain
  use_backend mobile_hosts if mobile_domain
  default_backend pc_hosts

###################### backend hosts #############################
backend mobile_hosts
  mode http
  server web1 192.168.168.62:80 check inter 2000 fall 3 rise 5

backend pc_hosts
  mode http
  server web2 192.168.168.63:80 check inter 2000 fall 3 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service

测试

复制代码
[root@haproxy conf.d]# echo "192.168.168.30 test.jungle.org" >> /etc/hosts
[root@haproxy conf.d]# curl mobile.jungle.org:8100
web2 192.168.168.63

[root@client ~]# curl mobile.jungle.org:8100
web1 192.168.168.62

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

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

复制代码
[root@haproxy conf.d]# cat acl.cfg
frontend jungle-acl
  bind 192.168.168.30:8100
  mode http
  balance roundrobin
  log global
  ###################### acl setting ###############################
  acl pc_domain hdr_dom(host) -i www.jungle.org
  acl mobile_domain hdr_dom(host) -i mobile.jungle.org
  acl ip_range_test src 172.18.0.0/16 192.168.168.30
  acl acl_deny_src src 192.168.168.198 192.168.0.0/24
  ###################### acl hosts #################################
  http-request deny if acl_deny_src
  use_backend pc_hosts if ip_range_test
  use_backend pc_hosts if pc_domain
  use_backend mobile_hosts if mobile_domain
  default_backend pc_hosts

###################### backend hosts #############################
backend mobile_hosts
  mode http
  server web1 192.168.168.62:80 check inter 2000 fall 3 rise 5

backend pc_hosts
  mode http
  server web2 192.168.168.63:80 check inter 2000 fall 3 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service

测试

复制代码
[root@client ~]# curl mobile.jungle.org:8100
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>
[root@client ~]# curl www.jungle.org:8100
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>
[root@haproxy conf.d]# curl mobile.jungle.org:8100
web2 192.168.168.63
[root@haproxy conf.d]# curl www.jungle.org:8100
web2 192.168.168.63

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

复制代码
[root@haproxy conf.d]# cat acl.cfg
frontend jungle-acl
  bind 192.168.168.30:8100
  mode http
  balance roundrobin
  log global
  ###################### acl setting ###############################
  #acl pc_domain hdr_dom(host) -i www.jungle.org
  #acl mobile_domain hdr_dom(host) -i mobile.jungle.org
  #acl ip_range_test src 172.18.0.0/16 192.168.168.30
  acl acl_user_agent hdr_sub(User-Agent) -i curl wget
  acl acl_user_agent_ab hdr_sub(User-Agent)  -i ApacheBench
  #acl acl_deny_src src 192.168.168.198 192.168.0.0/24
  ###################### acl hosts #################################
  redirect prefix http://192.168.168.62:81 if acl_user_agent
  http-request deny if acl_user_agent_ab
  #http-request deny if acl_deny_src
  #use_backend pc_hosts if ip_range_test
  #use_backend pc_hosts if pc_domain
  #use_backend mobile_hosts if mobile_domain
  default_backend pc_hosts

###################### backend hosts #############################
backend mobile_hosts
  mode http
  server web1 192.168.168.62:80 check inter 2000 fall 3 rise 5

backend pc_hosts
  mode http
  server web2 192.168.168.63:80 check inter 2000 fall 3 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service

测试

复制代码
[root@client ~]# curl  -I  192.168.168.30:8100
HTTP/1.1 302 Found
content-length: 0
location: http://192.168.168.62:81/
cache-control: no-cache

[root@client ~]# curl  -L  192.168.168.30:8100
port81
[root@client ~]# wget -O - -q 192.168.168.30:8100
port81

[root@client ~]# curl -A chrome 192.168.168.30:8100
web2 192.168.168.63

[root@client ~]#  curl -A ApacheBench 192.168.168.30:8100
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>

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

复制代码
[root@haproxy conf.d]# cat acl.cfg
frontend jungle-acl
  bind 192.168.168.30:8100
  mode http
  balance roundrobin
  log global
  acl acl_static path_end -i .jpg .jpeg .png .gif .css .js
  acl acl_php path_end -i .php
  use_backend mobile_hosts if acl_static
  use_backend pc_hosts if acl_php
  default_backend pc_hosts

###################### backend hosts #############################
backend mobile_hosts
  mode http
  server web1 192.168.168.62:80 check inter 2000 fall 3 rise 5

backend pc_hosts
  mode http
  server web2 192.168.168.63:80 check inter 2000 fall 3 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service

分别在两台后端web主机上准备文件,然后浏览器测试

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

复制代码
[root@haproxy conf.d]# cat acl.cfg
frontend jungle-acl
  bind 192.168.168.30:8100
  mode http
  balance roundrobin
  log global
  acl acl_static path_end -i .jpg .jpeg .png .gif .css .js
  acl acl_static path_beg -i /static /images /javascript  #两条名字一样的acl会被自动合并,逻辑关系为或
  acl acl_php path_end -i .php
  use_backend mobile_hosts if acl_static
  use_backend pc_hosts if acl_php
  default_backend pc_hosts

###################### backend hosts #############################
backend mobile_hosts
  mode http
  server web1 192.168.168.62:80 check inter 2000 fall 3 rise 5

backend pc_hosts
  mode http
  server web2 192.168.168.63:80 check inter 2000 fall 3 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service

准备好web文件

复制代码
[root@web1 html]# mkdir static
[root@web1 html]# echo static > static/index.html

测试

复制代码
[root@client ~]# curl 192.168.168.30:8100/static/
static

4.6.9 ACL示例-预定义ACL使用

官方帮助文档:HAProxy version 2.4.36 - Configuration Manual

预定义ACL

ACL name Equivalent to Usage
FALSE always_false never match
HTTP req_proto_http match if protocol is valid HTTP
HTTP_1.0 req_ver 1.0 match HTTP version 1.0
HTTP_1.1 req_ver 1.1 match HTTP version 1.1
HTTP_CONTENT hdr_val(content-length) gt 0 match an existing content-length
HTTP_URL_ABS url_reg ^/:*:// match absolute URL with scheme
HTTP_URL_SLASH url_beg / match URL beginning with "/"
HTTP_URL_STAR url * match URL equal to "*"
LOCALHOST src 127.0.0.1/8 match connection from local host
METH_CONNECT method CONNECT match HTTP CONNECT method
METH_DELETE method DELETE match HTTP DELETE method
METH_GET method GET HEAD match HTTP GET or HEAD method
METH_HEAD method HEAD match HTTP HEAD method
METH_OPTIONS method OPTIONS match HTTP OPTIONS method
METH_POST method POST match HTTP POST method
METH_PUT method PUT match HTTP PUT method
METH_TRACE method TRACE match HTTP TRACE method
RDP_COOKIE req_rdp_cookie_cnt gt 0 match presence of an RDP cookie
REQ_CONTENT req_len gt 0 match data in the request buffer
TRUE always_true always match
WAIT_END wait_end wait for end of content analysis

示例

复制代码
[root@haproxy conf.d]# cat acl.cfg
frontend jungle-acl
  bind 192.168.168.30:8100
  mode http
  balance roundrobin
  log global
  http-request deny if METH_HEAD HTTP_1.1  #如果HTTP请求方法为 HEAD并且HTTP协议版本为 HTTP/1.1则拒绝
  default_backend pc_hosts

###################### backend hosts #############################
backend mobile_hosts
  mode http
  server web1 192.168.168.62:80 check inter 2000 fall 3 rise 5

backend pc_hosts
  mode http
  server web2 192.168.168.63:80 check inter 2000 fall 3 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service

测试

复制代码
[root@client ~]# curl -I 192.168.168.30:8100
HTTP/1.1 403 Forbidden
content-length: 93
cache-control: no-cache
content-type: text/html

[root@client ~]# curl -I -XHEAD 192.168.168.30:8100
HTTP/1.1 403 Forbidden
content-length: 93
cache-control: no-cache
content-type: text/html
[root@client ~]# curl  192.168.168.30:8100
web2 192.168.168.63
#-0表示强制使用HTTP/1.0协议请求头
[root@client ~]# curl -I -0 -XHEAD  192.168.168.30:8100
#查看web服务器日志
[root@web2 ~]# tail -1 /var/log/nginx/access.log
192.168.168.30 - - [24/Sep/2025:22:03:08 +0800] "GET / HTTP/1.0" 200 20 "-" "curl/7.29.0" "192.168.168.198"

4.7 自定义HAProxy错误界面

默认情况下,所有后端服务器都down机后,会显示下面页面

复制代码
[root@client ~]# curl  192.168.168.30
<html><body><h1>503 Service Unavailable</h1>
No server is available to handle this request.
</body></html>

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

使用errorfile和errorloc指令,可以自定义各种错误页面

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

#示例:
    errorfile 400 /etc/haproxy/errorfiles/400badreq.http
    errorfile 403 /etc/haproxy/errorfiles/403forbid.http
    errorfile 503 /etc/haproxy/errorfiles/503sorry.http 

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

#示例:
errorloc 503 http://www.jungle.org/error_pages/503.html
复制代码
#errorfile示例
[root@haproxy conf.d]# vim /etc/haproxy/haproxy.cfg
defaults
    errorfile 503  /usr/local/haproxy/html/503.http
#配置错误信息
[root@haproxy conf.d]# mkdir -p  /usr/local/haproxy/html
[root@haproxy conf.d]# vim /usr/local/haproxy/html/503.http
HTTP/1.1 503 Service Unavailable
Content-Type:text/html;charset=utf-8

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>报错页面</title>
</head>
<body>
<center><h1>网站维护中......请稍侯再试</h1></center>
<center><h2>联系电话:400-123-4567</h2></center>
<center><h3>503 Service Unavailable</h3></center>
</body>
[root@haproxy conf.d]# systemctl restart haproxy.service

后端服务器都down了后,访问haproxy可以观察到以下页面

复制代码
#errorloc示例
[root@haproxy conf.d]# vim /etc/haproxy/haproxy.cfg
defaults
    #errorfile 503  /usr/local/haproxy/html/503.http
    errorloc 503 http://192.168.168.198:80/error_page/503.html
[root@haproxy conf.d]# systemctl restart haproxy

在192.168.168.198上配置页面error_page/503.html

复制代码
[root@client html]# cat  /var/www/html/error_page/503.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>报错页面</title>
</head>
<body>
<center><h1>网站维护中......请稍侯再试</h1></center>
<center><h2>联系电话:400-888-8888</h2></center>
<center><h3>503 Service Unavailable</h3></center>
</body>

由于后端服务器都宕机了,访问192.168.168.30页面会跳转至http://192.168.168.198:80/error_page/503.html页面

4.8 haproxy实现四层负载

针对有特殊访问写的应用场景

复制代码
MySQL
Redis
Memcache
RabbitMQ

4.8.1 四层负载示例

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

复制代码
listen redis-port
    bind 192.168.168.30:6379
    mode tcp
    balance leastconn
    server server1 192.168.168.62:6379 check
    server server1 192.168.168.63:6379 check backup
复制代码
#对 MySQL 服务实现四层负载
[root@haproxy conf.d]# cat mysql.cfg
listen mysql
  bind 192.168.168.30:3306
  mode tcp
  balance leastconn
  server mysql1 192.168.168.62:3306
  server mysql2 192.168.168.63:3306

[root@haproxy conf.d]# systemctl restart haproxy.service

在mysql服务器上创建账号

复制代码
create user test@'%' identified by '123';
grant all on *.* to test@'%';

测试

复制代码
[root@haproxy conf.d]# mysql -utest -p123 -h 192.168.168.30 -e "show variables like 'hostname'"
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| hostname      | web1  |
+---------------+-------+
[root@haproxy conf.d]# mysql -utest -p123 -h 192.168.168.30 -e "show variables like 'hostname'"
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| hostname      | web2  |
+---------------+-------+

4.8.2 ACL示例-四层访问控制

复制代码
[root@haproxy conf.d]# cat mysql.cfg
listen mysql
  bind 192.168.168.30:3306
  mode tcp
  balance leastconn
  acl invalid_src src 192.168.168.30 192.168.0.0/24
  tcp-request connection reject if invalid_src
  server mysql1 192.168.168.62:3306
  server mysql2 192.168.168.63:3306

[root@haproxy conf.d]# systemctl restart haproxy.service     

测试

复制代码
#测试连接提示连接中断,换个客户端测试即可
[root@haproxy conf.d]# mysql -utest -p123 -h 192.168.168.30 -e "show variables like 'hostname'"
ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 104

4.9 HAProxy- https实现

HAProxy https实现

复制代码
#配置HAProxy支持https协议,支持ssl会话;
    bind *:443 ssl crt /PATH/TO/SOME_PEM_FILE  #crt 后证书文件为PEM格式,且同时包含证书和所有私钥cat  demo.crt demo.key > demo.pem 

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

#向后端传递用户请求的协议和端口
    http_request set-header X-Forwarded-Port %[dst_port]
    http_request add-header X-Forwared-Proto https if { ssl_fc }

制作证书

复制代码
[root@haproxy conf.d]# mkdir /etc/haproxy/certs
[root@haproxy conf.d]# cd /etc/haproxy/certs
[root@haproxy certs]# openssl  genrsa -out haproxy.key 2048
[root@haproxy certs]# openssl req  -x509 -newkey rsa:2048 -subj "/CN=www.jungle.org" -keyout haproxy.key -nodes -days 365 -out haproxy.crt
[root@haproxy certs]# cat haproxy.key  haproxy.crt > haproxy.pem
#查看证书内容
[root@haproxy certs]# openssl  x509 -in  haproxy.pem -noout -text

haproxy配置https

复制代码
[root@haproxy conf.d]# cat https.cfg
frontend jungle-https
  bind 192.168.168.30:80
  bind 192.168.168.30:443 ssl crt /etc/haproxy/certs/haproxy.pem
  redirect scheme https if !{ ssl_fc }
  http-request set-header forwardPort %[dst_port]
  http-request add-header forwardProto https if { ssl_fc }
  use_backend static_hosts
  mode http
  balance roundrobin
  log global


backend static_hosts
  mode http
  server web1 192.168.168.62:80 check inter 2000 fall 3 rise 5
  server web2 192.168.168.63:80 check inter 2000 fall 3 rise 5
[root@haproxy conf.d]# systemctl restart haproxy.service
[root@haproxy conf.d]# ss -lntup | grep 443
tcp   LISTEN 0      3000   192.168.168.30:443       0.0.0.0:*    users:(("haproxy",pid=2938,fd=24))

修改后端服务器日志

复制代码
[root@web1 html]# vim /etc/nginx/nginx.conf
http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" "$proxy_add_x_forwarded_for" "$http_testheader" "$http_haproxydate" "$http_forwardPort" "$http_forwardProto"';
}
[root@web1 html]# systemctl restart nginx.service

验证并测试

复制代码
[root@client html]# curl -I 192.168.168.30
HTTP/1.1 302 Found
content-length: 0
location: https://192.168.168.30/
cache-control: no-cache
​
[root@client html]# curl -IL 192.168.168.30
HTTP/1.1 302 Found
content-length: 0
location: https://192.168.168.30/
cache-control: no-cache
​
curl: (60) Peer's certificate issuer has been marked as not trusted by the user.
More details here: http://curl.haxx.se/docs/sslcerts.html
[root@client html]# curl -kL 192.168.168.30
web2 192.168.168.63
[root@client html]# curl -kL 192.168.168.30
web1 192.168.168.62
[root@client html]# curl -kL 192.168.168.30
web2 192.168.168.63

查看后端web日志,可看到端口和协议

复制代码
[root@web1 html]# tail -1 /var/log/nginx/access.log
192.168.168.30 - - [24/Sep/2025:22:54:53 +0800] "GET / HTTP/1.1" 200 20 "-" "curl/7.29.0" "192.168.168.198" "192.168.168.198, 192.168.168.30" "-" "-" "443" "https"
相关推荐
发量惊人的中年网工1 小时前
如何验证DDoS高防真的生效?从源站隐藏到正常访问的完整验收方法
运维·网络·数据库·ddos
艾伦_耶格宇1 小时前
【ELK】-8 logstash的filter模块详解
运维·elk·filter
躺不平的理查德1 小时前
OpenSSL 的异步 TLS 1.3 加密
linux·运维·服务器
容器魔方1 小时前
云容器引擎 CCE 2026-Q2 优化升级:AI 推理负载、备份中心、Gateway API能力全新上线!
人工智能·云原生·容器·开源
无望__wsk1 小时前
k8s的pod管理
云原生·容器·kubernetes
楷哥爱开发1 小时前
IPFoxy爬虫代理配置指南:从0搭建Crawl4AI网页爬虫教程
大数据·运维·人工智能·爬虫
菜鸟界的菜鸟2 小时前
k8s-Service详解(七)
云原生·容器·kubernetes
Dear~yxy2 小时前
k8s的pod
云原生·容器·kubernetes
Dear~yxy2 小时前
k8s中的控制器管理
云原生·容器·kubernetes