Haproxy

发布时间 2023-04-07 16:32:00作者: ——浮生——

HAPROXY

支持功能:

TCP 和 HTTP反向代理
SSL/TSL服务器
可以针对HTTP请求添加cookie,进行路由后端服务器
可平衡负载至后端服务器,并支持持久连接
支持所有主服务器故障切换至备用服务器
支持专用端口实现监控服务
支持停止接受新连接请求,而不影响现有连接
可以在双向添加,修改或删除HTTP报文首部
响应报文压缩
支持基于pattern实现连接请求的访问控制
通过特定的URI为授权用户提供详细的状态信息

支持http反向代理
支持动态程序的反向代理
支持基于数据库的反向代理

不具备的功能:

正向代理--squid,nginx
缓存代理--varnish
web服务--nginx、tengine、apache、php、tomcat
UDP--目前不支持UDP协议
单机性能--相比LVS性能较差

Haproxy安装

1.apt yum安装

使用ubuntu使用apt,centos使用yum安装,不同的系统版本不同,也可以到官网https://haproxy.debian.net ubuntu使用源安装新版。

2.编译安装

centos 7编译安装

1.准备lua环境
[root@centos7 ~]# tar -xvf lua-5.4.4.tar.gz -C /usr/local/src/
[root@centos7 ~]# yum -y install gcc openssl-devel pcre-devel systemd-devel
[root@centos7 ~]# cd /usr/local/src/lua-5.4.4
[root@centos7 ~]# make linux test
[root@centos7 lua-5.4.4]# src/lua -v
Lua 5.4.4  Copyright (C) 1994-2022 Lua.org, PUC-Rio

2.编译haproxy
[root@centos7 ~]# tar -xvf haproxy-2.6.4.tar.gz -C /usr/local/src/
[root@centos7 lua-5.4.4]# cd /usr/local/src/haproxy-2.6.4/
[root@centos7 haproxy-2.6.4]# make ARCH=x86_64 TARGET=linux-glibc USE_PCRE=1 USE_OPENSSL=1 USE_ZLIB=1 USE_SYSTEMD=1 USE_LUA=1 LUA_INC=/usr/local/src/lua-5.4.4/src/ LUA_LIB=/usr/local/src/lua-5.4.4/src/
[root@centos7 haproxy-2.6.4]# make install PREFIX=/apps/haproxy
[root@centos7 haproxy-2.6.4]# ln -s /apps/haproxy/sbin/haproxy /usr/sbin/
[root@centos7 haproxy-2.6.4]# haproxy -v
HAProxy version 2.6.4-2a2078c 2022/08/22 - https://haproxy.org/
Status: long-term supported branch - will stop receiving fixes around Q2 2027.
Known bugs: http://www.haproxy.org/bugs/bugs-2.6.4.html
Running on: Linux 3.10.0-1160.el7.x86_64 #1 SMP Mon Oct 19 16:18:59 UTC 2020 x86_64
3.准备service和配置文件
[root@centos7 haproxy-2.6.4]# cat /usr/lib/systemd/system/haproxy.service 
[Unit]
Description=HAProxy Load Balancer
After=network-online.target rsyslog.service
Wants=network-online.target

[Service]
ExecStartPre=/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -c -q
ExecStart=/usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/lib/haproxy/haproxy.pid
ExecReload=/bin/kill -USR2 $MAINPID
LimitNOFILE=100000

[Install]
WantedBy=multi-user.target


[root@centos7 haproxy-2.6.4]# cat /etc/haproxy/haproxy.cfg 
global
  maxconn 100000
  stats socket /var/lib/haproxy/haproxy.sock mode 600 level admin
  user haproxy
  group haproxy
  daemon
  pidfile /var/lib/haproxy/haproxy.pid
  log 127.0.0.1 local2 info
defaults
  maxconn 100000
  option http-keep-alive
  option forwardfor
  mode http
  timeout connect 300000ms
  timeout client 300000ms
  timeout server 300000s
listen stats
  bind 0.0.0.0:9999
  mode http
  stats enable
  log global
  stats uri /haproxy-status
  stats auth admin:123456
listen web
  bind 10.0.0.17:80
  mode http
  option forwardfor
  server web1 10.0.0.18:80 check inter 3000 fall 2 rise 5
  
[root@centos7 haproxy-2.6.4]# tree /apps/haproxy/
/apps/haproxy/
├── doc
│   └── haproxy
│       ├── 51Degrees-device-detection.txt
│       ├── architecture.txt
│       ├── close-options.txt
│       ├── configuration.txt
│       ├── cookie-options.txt
│       ├── DeviceAtlas-device-detection.txt
│       ├── intro.txt
│       ├── linux-syn-cookies.txt
│       ├── lua.txt
│       ├── management.txt
│       ├── netscaler-client-ip-insertion-protocol.txt
│       ├── network-namespaces.txt
│       ├── peers.txt
│       ├── peers-v2.0.txt
│       ├── proxy-protocol.txt
│       ├── regression-testing.txt
│       ├── seamless_reload.txt
│       ├── SOCKS4.protocol.txt
│       ├── SPOE.txt
│       └── WURFL-device-detection.txt
├── sbin
│   └── haproxy
└── share
    └── man
        └── man1
            └── haproxy.1

6 directories, 22 files
ubuntu编译安装类似
1.依赖
apt install gcc iproute2 ntpdate tcpdump telnet traceroute nfs-kernel-server nfs-common lrzsz tree openssl libssl-dev libpcre3 libpcre3-dev zlib1g-dev openssh-server libreadline-dev libsystemd-dev

配置文件

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

global:全局配置段

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

chroot #锁定运行目录
deamon #以守护进程运行
stats socket /var/lib/haproxy/haproxy.sock mode 600 level admin process 1
#socket文件
user, group, uid, gid  #运行haproxy的用户身份 
nbproc   n #开启的haproxy worker 进程数,默认进程数是一个 2.5之后已废弃
#nbthread 1 #和多进程 nbproc配置互斥(版本有关,CentOS8的haproxy1.8无此问题),指定每个haproxy进程开启的线程数,默认为每个进程一个线程
#如果同时启用nbproc和nbthread 会出现以下日志的错误,无法启动服务
Apr  7 14:46:23 haproxy haproxy: [ALERT] 097/144623 (1454) : config : cannot enable multiple processes if multiple threads are configured. Please use either nbproc or nbthread but not both.
cpu-map 1 0   #绑定haproxy worker 进程至指定CPU,将第1个work进程绑定至0号CPU
cpu-map 2 1     #绑定haproxy worker 进程至指定CPU,将第2个work进程绑定至1号CPU
maxconn n   #每个haproxy进程的最大并发连接数
maxsslconn n   #每个haproxy进程ssl最大连接数,用于haproxy配置了证书的场景下
maxconnrate n   #每个进程每秒创建的最大连接数量
spread-checks n #后端server状态check随机提前或延迟百分比时间,建议2-5(20%-50%)之间,默认值0
pidfile #指定pid文件路径
log 127.0.0.1 local2 info #定义全局的syslog服务器;日志服务器需要开启UDP协议,最多可以定义两个

proxies:代理配置段

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配置更简洁,生产常用

defaults 配置参数:
option redispatch     #当server Id对应的服务器挂掉后,强制定向到其他健康的服务器,重新派发
option abortonclose   #当服务器负载很高时,自动结束掉当前队列处理比较久的连接,针对业务情况选择开启
option http-keep-alive #开启与客户端的会话保持
option forwardfor     #透传客户端真实IP至后端web服务器
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   #指定后端服务器的默认设置

listen配置参数:
listen   <name> 
  bind    #指定HAProxy的监听地址,可以是IPV4或IPV6,可以同时监听多个IP或端口,可同时用于listen字段中 bind [<address>]:<port_range> [, ...] [param*] #注意:如果需要绑定在非本机的IP,需要开启内核参数:net.ipv4.ip_nonlocal_bind=1
  mode http|tcp     #指定负载协议类型
  option #配置选项
  server   #定义后端real server,必须指定IP和端口
  
frontend <name> 
  bind    #指定HAProxy的监听地址,可以是IPV4或IPV6,可以同时监听多个IP或端口,可同时用于listen字段中 bind [<address>]:<port_range> [, ...] [param*] #注意:如果需要绑定在非本机的IP,需要开启内核参数:net.ipv4.ip_nonlocal_bind=1
  backlog <backlog> #针对所有server配置,当前端服务器的连接数达到上限后的后援队列长度,注意:不支持backend
  mode http|tcp     #指定负载协议类型
  use_backend <backend_name>  #调用的后端服务器组名称
backend <name>
  mode http|tcp     #指定负载协议类型,和对应的frontend必须一致
  option #配置选项
  server   #定义后端real server,必须指定IP和端口
  注意:option后面加 httpchk,smtpchk,mysql-check,pgsql-check,ssl-hello-chk方法,可用于实现更
多应用层检测功能。

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

子配置

[Service]
#修改下面两行
ExecStartPre=/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -f /etc/haproxy/conf.d/ -c -q
ExecStart=/usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -f /etc/haproxy/conf.d/  -p /var/lib/haproxy/haproxy.pid

代理实现

listen frontend和backend实现代理

1.listen

global
  maxconn 100000
  stats socket /var/lib/haproxy/haproxy.sock mode 600 level admin
  user haproxy
  group haproxy
  daemon
    #cpu-map 1 0
    #cpu-map 2 1
  pidfile /var/lib/haproxy/haproxy.pid
  log 127.0.0.1 local2 info
defaults
  maxconn 100000
  option http-keep-alive
  option forwardfor
  mode http
  timeout connect 300000ms
  timeout client 300000ms
  timeout server 300000s
listen stats
  bind 0.0.0.0:9999
  mode http
  stats enable
  log global
  stats uri /haproxy-status
  stats auth admin:123456
listen web
  bind 10.0.0.17:80
  mode http
  option forwardfor
  server web1 10.0.0.18:80 check inter 3000 fall 2 rise 5
  server web2 10.0.0.28:80 check inter 1000 fall 2 rise 5

测试:
root@ubuntu:~# while true;do curl 10.0.0.17;sleep 1;done
10.0.0.28 
10.0.0.18 
10.0.0.28 
10.0.0.18 
10.0.0.28 
10.0.0.18 

frontend和backend

[root@centos7 haproxy-2.6.4]# cat /etc/haproxy/haproxy.cfg 
global
  maxconn 100000
  stats socket /var/lib/haproxy/haproxy.sock mode 600 level admin
  user haproxy
  group haproxy
  daemon
  pidfile /var/lib/haproxy/haproxy.pid
  log 127.0.0.1 local2 info
defaults
  maxconn 100000
  option http-keep-alive
  option forwardfor
  mode http
  timeout connect 300000ms
  timeout client 300000ms
  timeout server 300000s
listen stats
  bind 0.0.0.0:9999
  mode http
  stats enable
  log global
  stats uri /haproxy-status
  stats auth admin:123456
#listen web
#  bind 10.0.0.17:80
#  mode http
#  option forwardfor
#  server web1 10.0.0.18:80 check inter 3000 fall 2 rise 5
#  server web2 10.0.0.28:80 check inter 1000 fall 2 rise 5
frontend web
  bind 10.0.0.17:80
  mode http
  use_backend web-server

backend web-server
  mode http
  option forwardfor
  server web1 10.0.0.18:80 check inter 3000 fall 3 rise 5
  server web2 10.0.0.28:80 check inter 1000 fall 3 rise 5



测试:
root@ubuntu:~# while true;do curl 10.0.0.17;sleep 1;done
10.0.0.18 
10.0.0.28 
10.0.0.18 
10.0.0.28 

调度算法

socat工具

使用socat工具可以实现动态调整动态算法的权重

[root@centos7 ~]#socat -h
[root@centos7 ~]#echo "help" | socat stdio /var/lib/haproxy/haproxy.sock

[root@centos7 ~]#echo "get weight web/web1" | socat stdio /var/lib/haproxy/haproxy.sock
3 (initial 3) #修改weight,注意只针对单进程有效
[root@centos7 ~]#echo "set weight web/web1 2" | socat stdio /var/lib/haproxy/haproxy.sock
[root@centos7 ~]#echo "get weight web/web1" | socat stdio /var/lib/haproxy/haproxy.sock

#针对haproxy的多进程,将后端服务器禁用
[root@centos7 ~]#vim /etc/haproxy/haproxy.cfg
......
stats socket /var/lib/haproxy/haproxy1.sock mode 600 level admin process 1 #绑定第1个进程和socket文件
stats socket /var/lib/haproxy/haproxy2.sock mode 600 level admin process 2 #绑定第2个进程和socket文件

#将后端服务器禁用,注意只针对单进程有效
[root@centos7 ~]#echo "disable server web/web1" | socat stdio /var/lib/haproxy/haproxy.sock
#启用后端服务器
[root@centos7 ~]#echo "enable server web/web1" | socat stdio /var/lib/haproxy/haproxy.sock
#将后端服务器软下线,即weight设为0
[root@centos7 ~]#echo "set weight web/web1 0" | socat stdio /var/lib/haproxy/haproxy.sock

静态算法

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

listen web
  bind 10.0.0.17:80
  mode http
  option forwardfor
  balance static-rr
  server web1 10.0.0.18:80 weight 1 check inter 3000 fall 2 rise 5
  server web2 10.0.0.28:80 weight 2 check inter 1000 fall 2 rise 5

root@ubuntu:~# while true;do curl 10.0.0.17;sleep 0.5;done
10.0.0.18 
10.0.0.18 
10.0.0.28 
10.0.0.28 
10.0.0.18 
10.0.0.28 
10.0.0.28 
10.0.0.18 
10.0.0.28 
10.0.0.18 
10.0.0.18 
10.0.0.28 
10.0.0.28

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

listen web
  bind 10.0.0.17:80
  mode http
  option forwardfor
  #balance static-rr
  balance first
  server web1 10.0.0.18:80 weight 1 check inter 3000 fall 2 rise 5
  server web2 10.0.0.28:80 weight 1 check inter 1000 fall 2 rise 5

root@ubuntu:~# while true;do curl 10.0.0.17;sleep 0.5;done
10.0.0.28 
10.0.0.28 
10.0.0.18 
10.0.0.28 
10.0.0.18 
10.0.0.28 
10.0.0.18 
10.0.0.28 
10.0.0.28 
10.0.0.28 
10.0.0.18 

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

动态算法

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

listen web
  bind 10.0.0.17:80
  mode http
  option forwardfor
  balance roundrobin
  server web1 10.0.0.18:80 weight 1 check inter 3000 fall 3 rise 3
  server web2 10.0.0.28:80 weight 1 check inter 2000 fall 3 rise 3
  
socat动态调整权重
[root@centos7 haproxy-2.6.4]# echo "get weight web/web1" |socat stdio /var/lib/haproxy/haproxy.sock 
1 (initial 1)

[root@centos7 haproxy-2.6.4]# echo "set weight web/web1 3" |socat stdio /var/lib/haproxy/haproxy.sock 

[root@centos7 haproxy-2.6.4]# echo "get weight web/web1" |socat stdio /var/lib/haproxy/haproxy.sock 
3 (initial 1)

root@ubuntu:~# while  true ;do curl 10.0.0.17 ; sleep 1 ;done
10.0.0.18 
10.0.0.28 
10.0.0.18 
10.0.0.28 
10.0.0.18 
10.0.0.18 
10.0.0.28 
10.0.0.18 
10.0.0.18 
10.0.0.18 
10.0.0.28 
10.0.0.18

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

listen web
  bind 10.0.0.17:80
  mode http
  option forwardfor
  balance leastconn
  server web1 10.0.0.18:80 weight 1 check inter 3000 fall 3 rise 3
  server web2 10.0.0.28:80 weight 1 check inter 2000 fall 3 rise 3

socat动态调整权重
[root@centos7 haproxy-2.6.4]# echo "get weight web/web1" |socat stdio /var/lib/haproxy/haproxy.sock 
1 (initial 1)

[root@centos7 haproxy-2.6.4]# echo "set weight web/web1 3" |socat stdio /var/lib/haproxy/haproxy.sock 

[root@centos7 haproxy-2.6.4]# echo "get weight web/web1" |socat stdio /var/lib/haproxy/haproxy.sock 
3 (initial 1)

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

listen web
  bind 10.0.0.17:80
  mode http
  option forwardfor
  balance random
  server web1 10.0.0.18:80 weight 1 check inter 3000 fall 3 rise 3
  server web2 10.0.0.28:80 weight 1 check inter 2000 fall 3 rise 3

source :源地址hash

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

1.map-based
map-based:取模法,对source地址进行hash计算,再基于服务器总权重的取模,最终结果决定将此请求转发至对应的后端服务器。此方法是静态的,即不支持在线调整权重,不支持慢启动,可实现对后端服务器均衡调度。缺点是当服务器的总权重发生变化时,即有服务器上线或下线,都会因总权重发生变化而导致调度结果整体改变,hash-type 指定的默认值为此算法
listen web
  bind 10.0.0.17:80
  mode http
  option forwardfor
  balance source
  hash-type map-based
  server web1 10.0.0.18:80 weight 1 check inter 3000 fall 3 rise 3
  server web2 10.0.0.28:80 weight 1 check inter 2000 fall 3 rise 3
2.consistent一致性哈希
  1、key1=hash(source_ip)%(2^32) [0---4294967295]
  2、keyA=hash(后端服务器虚拟ip)%(2^32)
  3、将key1和keyA都放在hash环上,将用户请求调度到离key1最近的keyA对应的后端服务器
listen web
  bind 10.0.0.17:80
  mode http
  option forwardfor
  balance source
  hash-type consistent
  server web1 10.0.0.18:80 weight 1 check inter 3000 fall 3 rise 3
  server web2 10.0.0.28:80 weight 1 check inter 2000 fall 3 rise 3

uri和url_param

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

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

url_param对用户请求的url中的 params 部分中的一个参数key对应的value值作hash计算通常用于追踪用户,以确保来自同一个用户的请求始终发往同

一个real server,如果无没key,将按roundrobin算法

<scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<frag>
左半部分:/<path>;<params>
整个uri:/<path>;<params>?<query>#<frag>
1.uri 
listen web
  bind 10.0.0.17:80
  mode http
  option forwardfor
  balance uri
  hash-type consistent  #默认map-based
  server web1 10.0.0.18:80 weight 1 check inter 3000 fall 3 rise 3
  server web2 10.0.0.28:80 weight 1 check inter 2000 fall 3 rise 3
2.url_param
listen web
  bind 10.0.0.17:80
  mode http
  option forwardfor
  balance url_param key #userid
  hash-type consistent  #默认map-based
  server web1 10.0.0.18:80 weight 1 check inter 3000 fall 3 rise 3
  server web2 10.0.0.28:80 weight 1 check inter 2000 fall 3 rise 3

对比总结

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

基于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和hapoxy之间有缓存服务器(如:CDN)时,不允许中间缓存器缓存cookie,因为这会导致很多经过同一个CDN的请求都发送到同一台后端服务器

listen web
  bind 10.0.0.17:80
  mode http
  option forwardfor
  balance roundrobin
  cookie WEBSRV insert nocache indirect
  server web1 10.0.0.18:80 weight 1 check inter 3000 fall 3 rise 3 cookie web1
  server web2 10.0.0.28:80 weight 1 check inter 2000 fall 3 rise 3 cookie web2

状态页

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中的管理功能

启用状态页
listen stats
  bind 0.0.0.0:9999
  mode http
  stats enable
  log global
  stats uri /haproxy-status
  stats auth admin:123456

ip地址透传

四层IP透传

实现:
haproxy服务端
[root@centos7 ~]# vim /etc/haproxy/haproxy.cfg

listen web
  bind 10.0.0.17:80
  mode tcp
  option forwardfor
  balance roundrobin
  server web3 10.0.0.100:80 weight 1  send-proxy check inter 1000 fall 3 rise 3
  
nginx服务端
root@ubuntu:~# vim /etc/nginx/nginx.conf
log_format main  "$remote_addr  $request $proxy_protocol_addr";

测试:
root@ubuntu:~# curl 10.0.0.17


root@ubuntu:~# tail -f /var/log/nginx/access.log 
10.0.0.1 - - [14/Sep/2022:07:36:16 +0000] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.33"
10.0.0.17 - - [14/Sep/2022:07:45:11 +0000] "PROXY TCP4 10.0.0.110 10.0.0.17 34166 80" 400 166 "-" "-"

七层IP透传

haproxy服务器
defaults
  maxconn 100000
  option forwardfor
  mode http
web服务器
apache
LogFormat "%{X-Forwarded-For}i %a %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

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

测试

root@ubuntu:~# tail -f /var/log/nginx/access.log
 "10.0.0.110, 10.0.0.17--[19/Sep/2022:01:19:43 +0000]GET / HTTP/1.1200612-curl/7.68.0 10.0.0.110"
 "10.0.0.110, 10.0.0.17--[19/Sep/2022:01:19:45 +0000]GET / HTTP/1.1200612-curl/7.68.0 10.0.0.110"

报文修改

2.0以下版本可以使用reqadd和reqdel在请求报文添加删除字段,通过rspadd与rspidel在响应报文中添加与删除字段。

2.1以上使用http-request和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

添加字段

添加向后端服务器发送的请求报文首部
frontend web
  bind *:80
  use_backend web_server
   http-request add-header X-haproxy-Current-Date %T
   
[root@localhost ~]# tail -f /var/log/httpd/access_log
10.0.0.110 10.0.0.17 - - [19/Sep/2022:17:54:41 +0800] "GET / HTTP/1.1" 200 11 "-" "curl/7.68.0" "19/Sep/2022:01:54:42 +0000"
10.0.0.110 10.0.0.17 - - [19/Sep/2022:17:54:43 +0800] "GET / HTTP/1.1" 200 11 "-" "curl/7.68.0" "19/Sep/2022:01:54:44 +0000"

添加向客户端发送的响应报文首部
frontend web
  bind *:80
  use_backend web_server
   http-request add-header X-haproxy-Current-Date %T
  http-response add-header x-via haproxy

root@ubuntu:~# curl -i 10.0.0.17
HTTP/1.1 200 OK
date: Mon, 19 Sep 2022 09:58:12 GMT
server: Apache/2.4.37 (rocky)
last-modified: Tue, 13 Sep 2022 09:47:25 GMT
etag: "b-5e88be64bee48"
accept-ranges: bytes
content-length: 11
content-type: text/html; charset=UTF-8
x-via: haproxy

10.0.0.28 

报文修改

删除原有server字段添加新字段
frontend web
  bind *:80
  use_backend web_server
   http-request add-header X-haproxy-Current-Date %T
  http-response add-header x-via haproxy
  http-response del-header server
  http-response add-header server haproxy-2.6
  
root@ubuntu:~# curl -I 10.0.0.17
HTTP/1.1 200 OK
date: Mon, 19 Sep 2022 02:06:59 GMT
content-type: text/html
content-length: 612
last-modified: Wed, 14 Sep 2022 02:55:32 GMT
etag: "632142a4-264"
accept-ranges: bytes
x-via: haproxy
server: haproxy-2.6

自定义日志

log global开启默认日志

option httplog可以采用 http 格式记录下来,并且可以使用相关指令将特定信息记录在haproxy的日志中

注:开启haproxy日志功能会加重负载,不建议开启

log global #开启记录日志,默认不开启
option httplog                              #开启记录httplog日志格式选项
capture cookie <name> len <length> #捕获请求和响应报文中的 cookie及值的长度,将之记录到日志 
capture request header <name> len <length> #捕获请求报文中指定的首部内容和长度并记录日志
capture response header <name> len <length> #捕获响应报文中指定的内容和长度首部并记录日志
#示例:
log global 
option httplog
capture request header Host len  256
capture request header User-Agent len 512 
capture request header Referer len 15
capture request header X-Forwarded-For len 15

后端服务器状态检测

三种方式

  • 1.基于四层的传输端口检测,默认
  • 2.基于URI做状态检测,占用带宽
  • 3.基于URI的request请求头内容做检测,占用较少带宽,建议方式

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

注:此方式会生成很多haproxy发起的访问日志

option httpchk   #启用七层健康性检测,对tcp 和 http 模式都支持,默认为:OPTIONS / 
HTTP/1.0
option httpchk <uri>
option httpchk <method> <uri>
option httpchk <method> <uri> <version>
#期望以上检查得到的响应码
http-check expect [!] <match> <pattern>
#示例:
http-check expect status 200
http-check expect ! rstatus ^5 #支持正则表达式

基于检测页面检测后端服务器

listen web
  bind 10.0.0.17:80
  mode http
  option httpchk GET /check.html
  option httpchk HEAD /check.html HTTP/1.1\r\nHost:\ 10.0.0.17
  balance roundrobin
  server web1 10.0.0.18:80 weight 1 check inter 3000 fall 3 rise 3
  server web2 10.0.0.28:80 weight 1 check inter 2000 fall 3 rise 3
  server web3 10.0.0.100:80 weight 1  check inter 1000 fall 3 rise 3


[root@localhost ~]# tail -f /var/log/httpd/access_log 
- 10.0.0.17 - - [19/Sep/2022:18:58:00 +0800] "HEAD /check.html HTTP/1.1" 200 - "-" "-" "-"
- 10.0.0.17 - - [19/Sep/2022:18:58:03 +0800] "HEAD /check.html HTTP/1.1" 200 - "-" "-" "-"
- 10.0.0.17 - - [19/Sep/2022:18:58:05 +0800] "HEAD /check.html HTTP/1.1" 200 - "-" "-" "-"
- 10.0.0.17 - - [19/Sep/2022:18:58:08 +0800] "HEAD /check.html HTTP/1.1" 200 - "-" "-" "-"

ACL

访问控制列表,基于包过滤的访问控制技术,通过对经过服务器传输的数据包进行过滤,即对收到的报文进行匹配和过滤,基于源地址,源端口,请求方法,文件后缀等信息进行下一步操作

格式和选项

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

#aclname ACL名称,可以使用大字母A-Z、小写字母a-z、数字0-9、冒号:、点.、中横线和下划线,并且严格区分大小写,比如:my_acl和My_Acl就是两个完全不同的acl
#criterion 定义匹配规则
hdr string,提取在一个HTTP请求报文的首部
hdr([<name> [,<occ>]]):完全匹配字符串,header的指定信息,<occ> 表示在多值中使用的值的出现次数
hdr_beg([<name> [,<occ>]]):前缀匹配,header中指定匹配内容的begin
hdr_end([<name> [,<occ>]]):后缀匹配,header中指定匹配内容end
hdr_dom([<name> [,<occ>]]):域匹配,header中的domain name
hdr_dir([<name> [,<occ>]]):路径匹配,header的uri路径
hdr_len([<name> [,<occ>]]):长度匹配,header的长度匹配
hdr_reg([<name> [,<occ>]]):正则表达式匹配,自定义表达式(regex)模糊匹配
hdr_sub([<name> [,<occ>]]):子串匹配,header中的uri模糊匹配

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

#operator 操作符
整数比较: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进行匹配

# 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.magedu.com
 exact #精确比较
 substring #子串
 suffix #后缀比较
 prefix #前缀比较
 subdir #路径, /wp-includes/js/jquery/jquery.js
 domain #域名,www.magedu.com
- regular expression #正则表达式
- hex block #16进制

组合调用

与:默认
或:使用or或||
非:使用!
调用方式:
#示例:
if valid_src valid_port #与关系,ACL中A和B都要满足为true,默认为与
if invalid_src || invalid_port  #或,ACL中A或者B满足一个为true
if ! invalid_src #非,取反,不满足ACL才为true

基于域名访问

frontend web
  bind *:80
  mode http
################################ acl setting #############################
acl pc hdr_dom(host) -i www.magedu.org
acl mobile hdr_dom(host) -i mobile.magedu,org

############################### acl host ################################

use_backend pc_server if pc
use_backend mobile_server if mobile


######################### backend server #############################
backend pc_server 
  mode http
  server web1 10.0.0.18:80 weight 1 check inter 3000 fall 3 rise 3 
backend mobile_server 
  mode http
  server web2 10.0.0.28:80 weight 1 check inter 2000 fall 3 rise 3 
  
root@ubuntu:~# curl mobile.magedu.org
10.0.0.28 
root@ubuntu:~# curl www.magedu.org
10.0.0.18

基于源地址或子网实现调度

frontend web
  bind *:80
  mode http
################################ acl setting #############################
acl pc hdr_dom(host) -i www.magedu.org
acl mobile hdr_dom(host) -i mobile.magedu.org
acl src_pc src 10.0.0.100 
acl src_mobile src 10.0.0.110 

############################### acl host ################################

use_backend pc_server if pc
use_backend mobile_server if mobile
default_backend pc_server


######################### backend server #############################
backend pc_server 
  mode http
  server web1 10.0.0.18:80 weight 1 check inter 3000 fall 3 rise 3 
backend mobile_server 
  mode http
  server web2 10.0.0.28:80 weight 1 check inter 2000 fall 3 rise 3 
  
  
root@ubuntu:~# hostname -I
10.0.0.100 
root@ubuntu:~# curl 10.0.0.17
10.0.0.18 

root@ubuntu:~# hostname -I
10.0.0.110 
root@ubuntu:~# curl 10.0.0.17
10.0.0.18 

基于ip的访问控制

listen web
  bind 10.0.0.17:80
  mode http
#  #option httpchk GET /check.html
#  option httpchk HEAD /check.html HTTP/1.1\r\nHost:\ 10.0.0.17
  balance roundrobin
#  server web1 10.0.0.18:80 weight 1 check inter 3000 fall 3 rise 3 
#  server web2 10.0.0.28:80 weight 1 check inter 2000 fall 3 rise 3 
#  server web3 10.0.0.100:80 weight 1  check inter 1000 fall 3 rise 3 
################################ acl setting #############################
acl acl_deny_src src 10.0.0.100

############################### acl host ################################
http-request deny if acl_deny_src
default_backend pc_server


######################### backend server #############################
backend pc_server 
  mode http
  server web1 10.0.0.18:80 weight 1 check inter 3000 fall 3 rise 3 
backend mobile_server 
  mode http
  server web2 10.0.0.28:80 weight 1 check inter 2000 fall 3 rise 3 

root@ubuntu:~# curl 10.0.0.17
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>

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

listen web
  bind 10.0.0.17:80
  mode http
#  #option httpchk GET /check.html
#  option httpchk HEAD /check.html HTTP/1.1\r\nHost:\ 10.0.0.17
  balance roundrobin
#  server web1 10.0.0.18:80 weight 1 check inter 3000 fall 3 rise 3 
#  server web2 10.0.0.28:80 weight 1 check inter 2000 fall 3 rise 3 
#  server web3 10.0.0.100:80 weight 1  check inter 1000 fall 3 rise 3 
################################ acl setting #############################
acl static_server path_end -i .html
acl php_server path_end -i .php

############################### acl host ################################
use_backend pc_server if static_server
use_backend mobile_server if php_server
default_backend pc_server


######################### backend server #############################
backend pc_server 
  mode http
  #option httpchk GET check.html
  server web1 10.0.0.18:80 weight 1 check inter 3000 fall 3 rise 3 
backend mobile_server 
  mode http
  #option httpchk GET check.html
  server web2 10.0.0.28:80 weight 1 check inter 2000 fall 3 rise 3 
#  server web3 10.0.0.100:80 weight 1  check inter 1000 fall 3 rise 3

root@ubuntu:~# curl 10.0.0.17/index.html
10.0.0.18 
root@ubuntu:~# curl 10.0.0.17/index.php
10.0.0.28 

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

listen web
  bind 10.0.0.17:80
  mode http
#  #option httpchk GET /check.html
#  option httpchk HEAD /check.html HTTP/1.1\r\nHost:\ 10.0.0.17
  balance roundrobin
#  server web1 10.0.0.18:80 weight 1 check inter 3000 fall 3 rise 3 
#  server web2 10.0.0.28:80 weight 1 check inter 2000 fall 3 rise 3 
#  server web3 10.0.0.100:80 weight 1  check inter 1000 fall 3 rise 3 
################################ acl setting #############################
acl static_path path_beg -i /static

############################### acl host ################################
use_backend pc_server if static_path


######################### backend server #############################
backend pc_server 
  mode http
  server web1 10.0.0.18:80 weight 1 check inter 3000 fall 3 rise 3 
backend mobile_server 
  mode http
  server web2 10.0.0.28:80 weight 1 check inter 2000 fall 3 rise 3 


root@ubuntu:~# curl 10.0.0.17/static/index.html
10.0.0.18 

自定义错误页

使用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  500 /var/www/html/errorfile/500.http
启用 no option http-use-htx #在defaults 块中添加

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

errorloc 500 /var/www/html/errorfile/500.http

tcp四层负载

listen mysql
  bind 10.0.0.17:3306
  mode tcp
  balance leastconn
  server mysql1 10.0.0.18:3306 check inter 3000 fall 3 rise 3 
  server mysql2 10.0.0.28:3306 check inter 2000 fall 3 rise 3 

测试:
[root@centos7 ~]# mysql -utest -p123456 -h10.0.0.17 -e "select @@server_id;"
+-------------+
| @@server_id |
+-------------+
|          28 |
+-------------+
[root@centos7 ~]# mysql -utest -p123456 -h10.0.0.17 -e "select @@server_id;"
+-------------+
| @@server_id |
+-------------+
|          18 |
+-------------+

实现https

haproxy可以实现https的证书安全,从用户到haproxy为https,从haproxy到后端服务器用http通信

但基于性能考虑,生产中证书都是在后端服务器比如nginx上实现

#配置HAProxy支持https协议,支持ssl会话;
 bind *:443 ssl crt /PATH/TO/SOME_PEM_FILE 
#指令 crt 后证书文件为PEM格式,需要同时包含证书和所有私钥 
 cat demo.key demo.crt > demo.pem 
#把80端口的请求重向定443
 bind *:80
 redirect scheme https if !{ ssl_fc } 
#向后端传递用户请求的协议和端口(frontend或backend)
 http_request set-header X-Forwarded-Port %[dst_port]
 http_request add-header X-Forwared-Proto https if { ssl_fc }

配置:

1.准备证书
[root@centos7 ~]# mkdir /etc/haproxy/certs
[root@centos7 ~]# cd /etc/haproxy/certs/
[root@centos7 certs]# openssl req -x509 -newkey rsa:2048 -subj "/CN=www.magedu.org" -keyout haproxy.key -nodes -days 365 -out haproxy.crt
[root@centos7 certs]# cat haproxy.key haproxy.crt > haproxy.pem
[root@centos7 certs]# ll
total 12
-rw-r--r-- 1 root root 1107 Sep 26 16:06 haproxy.crt
-rw-r--r-- 1 root root 1704 Sep 26 16:06 haproxy.key
-rw-r--r-- 1 root root 2811 Sep 26 16:07 haproxy.pem
2.配置haproxy
frontend http_port
  bind 10.0.0.17:80
  bind 10.0.0.17:443 ssl crt /etc/haproxy/certs/haproxy.pem
  redirect scheme https if !{ ssl_fc }
  #添加先后端传输参数也可放在backend中
  http-request set-header X-forwarded-port %[dst_port]  
  http-request add-header Xforwarded-proto https if { ssl_fc } 
 
 mode http
  balance roundrobin
  

  acl pc_server hdr_dom(host) -i www.magedu.org
  

backend pc_server
  mode http
  server web1 10.0.0.18:80 check

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" \"%{X-Forwarded-Port}i\" \"%{X-Forwarded-Proto}i\"" combined  

案例:

编译安装haproxy

ubuntu编译安装haproxy
1.安装依赖
root@ubuntu:~# apt install gcc iproute2 ntpdate tcpdump telnet traceroute nfs-kernel-server nfs-common lrzsz tree openssl libssl-dev libpcre3 libpcre3-dev zlib1g-dev openssh-server libreadline-dev libsystemd-dev
2.准备lua
root@ubuntu:~# tar -xvf lua-5.4.4.tar.gz -C /usr/local/src/
root@ubuntu:~# cd /usr/local/src/lua-5.4.4/
root@ubuntu:/usr/local/src/lua-5.4.4# src/lua -v
Lua 5.4.4  Copyright (C) 1994-2022 Lua.org, PUC-Rio
3.编译安装
root@ubuntu:/usr/local/src/haproxy-2.6.4# tar -xvf haproxy-2.6.4.tar.gz -C /usr/local/src/
root@ubuntu:/usr/local/src/haproxy-2.6.4# cd /usr/local/src/haproxy-2.6.4/
root@ubuntu:/usr/local/src/haproxy-2.6.4# make ARCH=x86_64 TARGET=linux-glibc USE_PCRE=1 USE_OPENSSL=1 USE_ZLIB=1 USE_SYSTEMD=1 USE_LUA=1 LUA_INC=/usr/local/src/lua-5.4.4/src/ LUA_LIB=/usr/local/src/lua-5.4.4/src/
root@ubuntu:/usr/local/src/haproxy-2.6.4# make install PREFIX=/apps/haproxy
root@ubuntu:/usr/local/src/haproxy-2.6.4# ln -s /apps/haproxy/sbin/haproxy /usr/sbin/
root@ubuntu:/usr/local/src/haproxy-2.6.4# haproxy -v
HAProxy version 2.6.4-2a2078c 2022/08/22 - https://haproxy.org/
Status: long-term supported branch - will stop receiving fixes around Q2 2027.
Known bugs: http://www.haproxy.org/bugs/bugs-2.6.4.html
Running on: Linux 5.4.0-96-generic #109-Ubuntu SMP Wed Jan 12 16:49:16 UTC 2022 x86_64
4.准备service和配置文件
root@ubuntu:/usr/local/src/haproxy-2.6.4# vim /usr/lib/systemd/system/haproxy.service
[Unit]
Description=HAProxy Load Balancer
After=network-online.target rsyslog.service
Wants=network-online.target

[Service]
ExecStartPre=/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -c -q
ExecStart=/usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/lib/haproxy/haproxy.pid
ExecReload=/bin/kill -USR2 $MAINPID
LimitNOFILE=100000

[Install]
WantedBy=multi-user.target

root@ubuntu:/usr/local/src/haproxy-2.6.4# vim /etc/haproxy/haproxy.cfg
global
  maxconn 100000
  stats socket /var/lib/haproxy/haproxy.sock mode 600 level admin
  user haproxy
  group haproxy
  daemon
  pidfile /var/lib/haproxy/haproxy.pid
  log 127.0.0.1 local2 info
defaults
  maxconn 100000
  option http-keep-alive
  option forwardfor
  mode http
  timeout connect 300000ms
  timeout client 300000ms
  timeout server 300000s
listen stats
  bind 0.0.0.0:9999
  mode http
  stats enable
  log global
  stats uri /haproxy-status
  stats auth admin:123456
  
root@ubuntu:/usr/local/src/haproxy-2.6.4# mkdir /var/lib/haproxy/
验证启动
root@ubuntu:/usr/local/src/haproxy-2.6.4# systemctl start haproxy.service 
、root@ubuntu:/usr/local/src/haproxy-2.6.4# systemctl status  haproxy.service
● haproxy.service - HAProxy Load Balancer
     Loaded: loaded (/lib/systemd/system/haproxy.service; disabled; vendor preset: enabled)
     Active: active (running) since Mon 2022-09-26 08:52:11 UTC; 2min 45s ago
    Process: 14374 ExecStartPre=/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -c -q (code=exited, status=0/SUCCESS)
   Main PID: 14376 (haproxy)
      Tasks: 2 (limit: 2238)
     Memory: 19.3M
        CPU: 232ms
     CGroup: /system.slice/haproxy.service
             ├─14376 /usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/lib/haproxy/haproxy.pid
             └─14378 /usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/lib/haproxy/haproxy.pid

Sep 26 08:52:11 ubuntu systemd[1]: Starting HAProxy Load Balancer...
Sep 26 08:52:11 ubuntu systemd[1]: Started HAProxy Load Balancer.
Sep 26 08:52:11 ubuntu haproxy[14376]: [NOTICE]   (14376) : haproxy version is 2.6.4-2a2078c
Sep 26 08:52:11 ubuntu haproxy[14376]: [NOTICE]   (14376) : path to executable is /usr/sbin/haproxy
Sep 26 08:52:11 ubuntu haproxy[14376]: [ALERT]    (14376) : config : parsing [/etc/haproxy/haproxy.cfg:7] : 'pidfile' already specified. Continuing.
Sep 26 08:52:11 ubuntu haproxy[14376]: [NOTICE]   (14376) : New worker (14378) forked
Sep 26 08:52:11 ubuntu haproxy[14376]: [NOTICE]   (14376) : Loading success.

总结haproxy各调度算法的实现方式及其应用场景

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

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

实现方式:
firts
static-rr
roundrobin
leastconn
random

配置文件中添加
balance  算法 
例:
listen web
  balance roundrobin
  
source
Uri
url_param
hdr
rdp-cookie

配置文件中添加
balance  算法 
hash-type consistent 一致性哈希
例:
listen web
  balance source
  hash-type consistent

使用haproxy的ACL实现基于文件后缀名的动静分离

listen web  #frontend配置相同
  bind 10.0.0.17:80
  mode http
  balance roundrobin
################################ acl setting #############################
acl static_server path_end -i .html
acl php_server path_end -i .php

############################### acl host ################################
use_backend pc_server if static_server
use_backend mobile_server if php_server
default_backend pc_server


######################### backend server #############################
backend pc_server 
  mode http
  server web1 10.0.0.18:80 weight 1 check inter 3000 fall 3 rise 3 
backend mobile_server 
  mode http
  server web2 10.0.0.28:80 weight 1 check inter 2000 fall 3 rise 3 

haproxy https实现

frontend http_port
  bind 10.0.0.17:80
  bind 10.0.0.17:443 ssl crt /etc/haproxy/certs/haproxy.pem
  redirect scheme https if !{ ssl_fc }
  mode http
  balance roundrobin
  
################################ acl setting #############################
  acl pc_server hdr_dom(host) -i www.magedu.org
  

backend pc_server
  mode http
  server web1 10.0.0.18:80 check