haproxy七层代理

一.负载均衡

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

二.haproxy简介

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

三.haproxy的安装和服务信息

3.1实验环境

haproxy实验环境设置
主机名主机IP
harpoxy172.25.254.100
webserver1172.25.254.10
webserver2172.25.254.20

3.2.haproxy的基本配置信息

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

global:全局配置段

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

proxies:代理配置段

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

3.3global配置参数说明

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

其中使用的最多的是对于多进程和多线程参数的使用

3.3.1多进程与多线程

3.3.1.1启动多进程

haproxy配置文件配置

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




global
   
    log         127.0.0.1 local2

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

    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats1 mode 600 level admin process 1
    stats socket /var/lib/haproxy/stats2 mode 600 level admin process 2

    # utilize system-wide crypto-policies
    ssl-default-bind-ciphers PROFILE=SYSTEM
    ssl-default-server-ciphers PROFILE=SYSTEM

        nbproc 2
        cpu-map 1 0
        cpu-map 2 1

重启haproxy服务

[root@haproxy ~]# systemctl restart haproxy.service 
[root@haproxy ~]# systemctl status haproxy.service 
● haproxy.service - HAProxy Load Balancer
     Loaded: loaded (/usr/lib/systemd/system/haproxy.service; disabled; preset: disabled)
     Active: active (running) since Sat 2024-08-10 22:53:01 CST; 7s ago
    Process: 2082 ExecStartPre=/usr/sbin/haproxy -f $CONFIG -f $CFGDIR -c -q $OPTIONS (code=exited, s>
   Main PID: 2085 (haproxy)
      Tasks: 3 (limit: 10887)
     Memory: 5.1M
        CPU: 28ms
     CGroup: /system.slice/haproxy.service

查看进程数量

[root@haproxy ~]# pstree -p |grep haproxy
           |-haproxy(2085)-+-haproxy(2087)
           |               `-haproxy(2088)
[root@haproxy ~]# 
3.3.1.2启动多线程

haproxy配置文件配置

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


stats socket /var/lib/haproxy/stats1 mode 600 level admin process 1
    stats socket /var/lib/haproxy/stats2 mode 600 level admin process 2

    # utilize system-wide crypto-policies
    ssl-default-bind-ciphers PROFILE=SYSTEM
    ssl-default-server-ciphers PROFILE=SYSTEM

        #nbproc 2
        #cpu-map 1 0
        #cpu-map 2 1
        nbthread 2

重启haproxy服务

[root@haproxy ~]# systemctl restart haproxy.service 
[root@haproxy ~]# systemctl status haproxy.service 
● haproxy.service - HAProxy Load Balancer
     Loaded: loaded (/usr/lib/systemd/system/haproxy.service; disabled; preset: disabled)
     Active: active (running) since Sat 2024-08-10 22:56:07 CST; 6s ago
    Process: 2125 ExecStartPre=/usr/sbin/haproxy -f $CONFIG -f $CFGDIR -c -q $OPTIONS (code=exited, s>
   Main PID: 2128 (haproxy)
      Tasks: 3 (limit: 10887)
     Memory: 4.2M
        CPU: 24ms
     CGroup: /system.slice/haproxy.service

3.4defaults参数信息

参数参数配置表达意思
mode  httpHAProxy实例使用的连接协议
logglobal指定日志地址和记录日志条目的 syslog/rsyslog日志设备
optionhttplog日志记录选项,httplog表示记录与 HTTP 会话相关的各种属性值
option  dontlognulldontlognull表示不记录空会话连接日志
option http-server-close等待客户端完整HTTP请求的时间,此处为等 待10s。
option forwardforexcept 127.0.0.0/8透传客户端真实IP至后端web服务器
optionredispatch当server Id对应的服务器挂掉后,强制定 向到其他健康的服务器,重新派发
optionhttp-keep-alive开启与客户端的会话保持
retries  3连接后端服务器失败次数
timeout http-request1000s等待客户端请求完全被接收和处理的最 长时间
timeout queue  60s设置删除连接和客户端收到503或服务不可 用等提示信息前的等待时间
timeout connect120s设置等待服务器连接成功的时间
timeout client600s设置允许客户端处于非活动状态,即既不发 送数据也不接收数据的时间
timeout server600s设置服务器超时时间,即允许服务器处于既 不接收也不发送数据的非活动时间
timeout http-keep-alive60ssession 会话保持超时时间,此时间段内 会转发到相同的后端服务器
timeout check  10s指定后端服务器健康检查的超时时间
maxconn3000
default-server inter 1000 weight 3

3.4.1server配置测试

[root@haproxy ~]# vim /etc/haproxy/conf.d/serverclient.cfg 
[root@haproxy ~]# cat /etc/haproxy/conf.d/serverclient.cfg 
listen webserver
	bind *:80
	mode http
	balance roundrobin
	server web1 172.25.254.10:80
	server web2 172.25.254.20:80

启动haproxy服务

[root@haproxy ~]# systemctl restart haproxy.service 
[root@haproxy ~]# systemctl status haproxy.service 
● haproxy.service - HAProxy Load Balancer
     Loaded: loaded (/usr/lib/systemd/system/haproxy.service; disabled; preset: disabled)
     Active: active (running) since Sat 2024-08-10 23:14:38 CST; 8s ago
    Process: 2315 ExecStartPre=/usr/sbin/haproxy -f $CONFIG -f $CFGDIR -c -q $OPTIONS (code=exited, status=0/SUCCESS)
   Main PID: 2318 (haproxy)
      Tasks: 5 (limit: 10887)
     Memory: 6.6M
        CPU: 27ms
     CGroup: /system.slice/haproxy.service

测试效果:

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

实现 sorry_server 效果:

安装http服务并进行配置

修改端口:

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

Listen 8080

配置http输出效果:

[root@haproxy ~]# echo sorry 下班了> /var/www/html/index.html
 

修改haproxy配置文件:

[root@haproxy ~]# cat /etc/haproxy/conf.d/serverclient.cfg 
listen webserver
	bind *:80
	mode http
	balance roundrobin
	server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
	server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 2
	server web_sorry 172.25.254.100:8080 backup

将另外两台nginx服务器的服务下线进行测试

[root@client ~]# curl 172.25.254.100:8080
sorry 下班了
 

进行网页重定向实验:

[root@haproxy ~]# cat /etc/haproxy/conf.d/serverclient.cfg 
listen webserver
	bind *:80
	mode http
	balance roundrobin
	redirect prefix http://www.baidu.com
	#server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
	#server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 2
	#server web_sorry 172.25.254.100:8080 backup

进行测试会发向访问172.25.254.100的网页自动跳转到了百度

3.5 socat工具

修改harpoxy配置文件

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
global
    
    log         127.0.0.1 local2
    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     4000
    user        haproxy
    group       haproxy
    daemon

    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats mode 600 level admin
   

重启haproxy服务使配置生效

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

下载socat工具

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

查看帮助目录

[root@haproxy haproxy]# echo "help" | socat stdio /var/lib/haproxy/stats

查看haproxy状态

[root@haproxy haproxy]# echo "show info" | socat stdio /var/lib/haproxy/stats
Name: HAProxy
Version: 2.4.22-f8e3218
Release_date: 2023/02/14
Nbthread: 4
Nbproc: 1
Process_num: 1
Pid: 2371
 

查看集群状态

[root@haproxy haproxy]# echo "show servers state" | socat stdio /var/lib/haproxy/stats
1
# be_id be_name srv_id srv_name srv_addr srv_op_state srv_admin_state srv_uweight srv_iweight srv_time_since_last_change srv_check_status srv_check_result srv_check_health srv_check_state srv_agent_state bk_f_forced_id srv_f_forced_id srv_fqdn srv_port srvrecord srv_use_ssl srv_check_port srv_check_addr srv_agent_addr srv_agent_port
3 static 1 static 127.0.0.1 0 0 1 1 619 8 2 0 6 0 0 0 - 4331 - 0 0 - - 0
4 app 1 app1 127.0.0.1 0 0 1 1 619 8 2 0 6 0 0 0 - 5001 - 0 0 - - 0
4 app 2 app2 127.0.0.1 0 0 1 1 618 8 2 0 6 0 0 0 - 5002 - 0 0 - - 0
4 app 3 app3 127.0.0.1 0 0 1 1 618 8 2 0 6 0 0 0 - 5003 - 0 0 - - 0
4 app 4 app4 127.0.0.1 0 0 1 1 618 8 2 0 6 0 0 0 - 5004 - 0 0 - - 0
5 webserver 1 web1 172.25.254.10 2 0 1 1 619 1 0 2 0 0 0 0 - 80 - 0 0 - - 0
5 webserver 2 web2 172.25.254.20 2 0 1 1 619 1 0 2 0 0 0 0 - 80 - 0 0 - - 0
 

查看集群权重

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

设置权重:实现热处理


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

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

四.haproxy算法

4.1静态算法

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

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

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

示例:

listen webserver
   bind *:80
   mode http
   balance static-rr
   server webserver1 192.168.0.101:80 weight 2 check inter 3s fall 3 rise 5
   server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5

4.1.2 first

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

示例:

listen webserver
   bind *:80
   mode http
   balance first                 
   server webserver1 192.168.0.101:80 maxconn 3 check inter 3s fall 3 rise 5 
   server webserver2 192.168.0.102:80 check inter 3s fall 3 rise 5

测试效果:

#在两台主机上分别执行此循环,可以观察是否102被调度到 while true;do curl 172.25.254.100 ; sleep 0.1;done

4.2动态算法

动态算法

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

4.2.1 roundrobin

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

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

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

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

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

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

4.2.2 leastconn

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

示例:

listen webserver_80
   bind 172.25.254.100:80
   mode http
   balance leastconn
   server webserver1 192.168.0.101:80 weight 1 check inter 3s fall 3 rise 5 
   server webserver2 192.168.0.102:80 weight 1 check inter 3s fall 3 rise 5

4.3 其他算法

4.3.1 source

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

[root@haproxy ~]# cat /etc/haproxy/conf.d/serverclient.cfg 
listen webserver
	bind *:80
	mode http
	#balance roundrobin
	balance source
	server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
	server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 2
	#server web_sorry 172.25.254.100:8080 backup

测试

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

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

4.3.1.1 map-base 取模法

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

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

缺点是当服务器的总权重发生变化时,即有服务器上线或下线,都会因总权重发生变化而导致调度结果 整体改变

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

示例:

[root@haproxy ~]# cat /etc/haproxy/conf.d/serverclient.cfg 
listen webserver
	bind *:80
	mode http
	#balance roundrobin
	balance source
	server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
	server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 2
	#server web_sorry 172.25.254.100:8080 backup

测试:

这时不支持动态调整权重值
[root@haproxy ~]# echo "set weight webserver/web1 1" | socat stdio /var/lib/haproxy/stats
Backend is using a static LB algorithm and only accepts weights '0%' and '100%'.

只能进行动态的下线和上线
[root@haproxy ~]# echo "set weight webserver/web1 0" | socat stdio /var/lib/haproxy/stats

[root@haproxy ~]# echo " set weight webserver/web1 " | socat stdio /var/lib/haproxy/stats
Require <weight> or <weight%>.

[root@haproxy ~]# echo " get weight webserver/web1 " | socat stdio /var/lib/haproxy/stats
0 (initial 2)
4.3.1.2 一致性hash

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

算法:

1、后端服务器哈希环点keyA=hash(后端服务器虚拟ip)%(2^32)

2、客户机哈希环点key1=hash(client_ip)%(2^32) 得到的值在[0---4294967295]之间,

3、将keyA和key1都放在hash环上,将用户请求调度到离key1最近的keyA对应的后端服务器

hash环偏斜问题

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

hash对象

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

一致性hash示意图

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

4.3.2 ur

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

4.3.2.1 uri 取模法配置示例
[root@haproxy ~]# cat /etc/haproxy/conf.d/serverclient.cfg 
listen webserver
	bind *:80
	mode http
	#balance roundrobin
	#balance source
	balance uri
	server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
	server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 2
	#server web_sorry 172.25.254.100:8080 backup
4.3.2.2 uri 一致性hash配置示例
[root@haproxy ~]# cat /etc/haproxy/conf.d/serverclient.cfg 
listen webserver
	bind *:80
	mode http
	#balance roundrobin
	#balance source
	balance uri
	hash-type consistent
	server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
	server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 2
	#server web_sorry 172.25.254.100:8080 backup
[root@haproxy ~]# 

webserver1配置

[root@webserver1 ~]# echo webserver1 - 172.25.254.10 > /usr/share/nginx/html/index1.html
[root@webserver1 ~]# echo webserver1 - 172.25.254.10 > /usr/share/nginx/html/index2.html
[root@webserver1 ~]# echo webserver1 - 172.25.254.10 > /usr/share/nginx/html/index3.html

webserver2配置

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

测试:

[root@client ~]# curl 172.25.254.100/index.html
webserver1 - 172.25.254.10
[root@client ~]# curl 172.25.254.100/index1.html
webserver1 - 172.25.254.10
[root@client ~]# curl 172.25.254.100/index2.html
webserver2 - 172.25.254.20
[root@client ~]# curl 172.25.254.100/index3.html
webserver1 - 172.25.254.10

4.3.3 url_param

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

4.3.3.1 url_param取模法配置示例:
[root@haproxy ~]# cat /etc/haproxy/conf.d/serverclient.cfg 
listen webserver
	bind *:80
	mode http
	#balance roundrobin
	#balance source
	#balance uri
	balance url_param name,userid
#	hash-type consistent
	server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
	server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 2
	#server web_sorry 172.25.254.100:8080 backup
4.3.3.2 url_param一致性hash配置示例
[root@haproxy ~]# cat /etc/haproxy/conf.d/serverclient.cfg 
listen webserver
	bind *:80
	mode http
	#balance roundrobin
	#balance source
	#balance uri
	balance url_param name,userid
	hash-type consistent
	server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
	server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 2
	#server web_sorry 172.25.254.100:8080 backup

测试

[root@client ~]# curl 172.25.254.100/index3.html?name=lee
webserver1 - 172.25.254.10
[root@client ~]# curl 172.25.254.100/index3.html?name=lee
webserver1 - 172.25.254.10
[root@client ~]# curl 172.25.254.100/index3.html?name=lee
webserver1 - 172.25.254.10
[root@client ~]# curl 172.25.254.100/index3.html?name=lee
webserver1 - 172.25.254.10
[root@client ~]# curl 172.25.254.100/index3.html?name=sss
webserver1 - 172.25.254.10

4.3.4 hdr

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

4.3.4.1 hdr取模法配置示例
[root@haproxy ~]# cat /etc/haproxy/conf.d/serverclient.cfg 
listen webserver
	bind *:80
	mode http
	#balance roundrobin
	#balance source
	#balance uri
#	balance url_param name,userid
	balance hdr(User-Agent)
#	hash-type consistent
	server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
	server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 2
	#server web_sorry 172.25.254.100:8080 backup
4.3.4.2 一致性hash配置示例
[root@haproxy ~]# cat /etc/haproxy/conf.d/serverclient.cfg 
listen webserver
	bind *:80
	mode http
	#balance roundrobin
	#balance source
	#balance uri
#	balance url_param name,userid
	balance hdr(User-Agent)
	hash-type consistent
	server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
	server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 2
	#server web_sorry 172.25.254.100:8080 backup

测试访问:

[root@client ~]# curl -v 172.25.254.100
*   Trying 172.25.254.100:80...
* Connected to 172.25.254.100 (172.25.254.100) port 80 (#0)
> GET / HTTP/1.1
> Host: 172.25.254.100
> User-Agent: curl/7.76.1
> Accept: */*

webserver1 - 172.25.254.10
* Connection #0 to host 172.25.254.100 left intact

[root@client ~]# curl -vA "sougou" 172.25.254.100
*   Trying 172.25.254.100:80...
* Connected to 172.25.254.100 (172.25.254.100) port 80 (#0)
> GET / HTTP/1.1
> Host: 172.25.254.100
> User-Agent: sougou
> Accept: */*

webserver2 - 172.25.254.20
* Connection #0 to host 172.25.254.100 left intact

[root@client ~]# curl -vA "firefox" 172.25.254.100
*   Trying 172.25.254.100:80...
* Connected to 172.25.254.100 (172.25.254.100) port 80 (#0)
> GET / HTTP/1.1
> Host: 172.25.254.100
> User-Agent: firefox
> Accept: */*

webserver1 - 172.25.254.10
* Connection #0 to host 172.25.254.100 left intact

4.3.5算法总结

#静态

static-rr--------->tcp/http  

first------------->tcp/http  

#动态

roundrobin-------->tcp/http

leastconn--------->tcp/http

#以下静态和动态取决于hash_type是否consistent

source------------>tcp/http

Uri--------------->http

url_param--------->http

hdr--------------->http

五.高级功能及配置

5.1 基于cookie的会话保持

配置示例:

[root@haproxy ~]# vim /etc/haproxy/conf.d/serverclient.cfg 
[root@haproxy ~]# systemctl restart haproxy.service 
[root@haproxy ~]# cat /etc/haproxy/conf.d/serverclient.cfg 
listen webserver
	bind *:80
	mode http
	balance roundrobin
	#balance source
	#balance uri
#	balance url_param name,userid
#	balance hdr(User-Agent)
#	hash-type consistent
	cookie WEBCOOKIE insert nocache indirect
	server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 2
	server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 2
	#server web_sorry 172.25.254.100:8080 backup

测试效果:

[root@client ~]# 
[root@client ~]# curl -i 172.25.254.100
HTTP/1.1 200 OK
server: nginx/1.20.1
date: Sat, 10 Aug 2024 17:41:54 GMT
content-type: text/html
content-length: 27
last-modified: Sat, 10 Aug 2024 15:19:20 GMT
etag: "66b784f8-1b"
accept-ranges: bytes
set-cookie: WEBCOOKIE=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/
cache-control: private

webserver2 - 172.25.254.20
[root@client ~]# curl -b WEBCOOKIE=web1 172.25.254.100
webserver1 - 172.25.254.10

5.2 HAProxy状态页

配置:

[root@haproxy ~]# cat /etc/haproxy/conf.d/status.cfg 
listen stats:
	mode http
	bind *:9999
	stats enable
	log global
	stats uri /status
	stats auth lk:lk

测试:

5.3 IP透传

5.3.2 四层IP透传

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

http {
   log_format main '$remote_addr - $remote_user [$time_local] "$request"' 
                       ' "$proxy_protocol_addr"'
                     '$status $body_bytes_sent "$http_referer" '
                     '"$http_user_agent" "$http_x_forwarded_for"';
server {
       listen       80 proxy_protocol; 
       listen       [::]:80;
       server_name _;
       root         /usr/share/nginx/html;

修改haproxy配置

vim /etc/haproxy/serverclient.cfg

listen webserver_80
   bind 172.25.254.100:80
   mode tcp
   balance roundrobin                 
   server webserver1 192.168.0.101:80 send-proxy weight 1 check inter 3s fall 3 
rise 5 

测试:

tail -n 3 /var/log/nginx/access.log
172.254.254.10 - - [10/Jul/2024:15:21:00 +0800] "GET / HTTP/1.1"200 18 "-" 
"curl/7.29.0" "-"
172.25.254.10 - - [10/Jul/2024:15:26:11 +0800] "GET / HTTP/1.1"200 18 "-" 
"curl/7.29.0" "-"
172.25.254.10 - - [10/Jul/2024:15:41:56 +0800] "GET / HTTP/1.1" "172.25.254.10"200 
18 "-" "curl/7.29.0"

5.3.3 七层IP透传

5.3.3.1 HAProxy配置
 vim /etc/haproxy/haproxy.cfg

listen webserver_80
 option forwardfor
   bind 172.25.254.100:80
   mode http
   balance roundrobin                 
   server webserver1 172.25.254.10:80 send-proxy weight 1 check inter 3s fall 3 
rise 5
   server webserver1 172.25.254.100:80 weight 1 check inter 3s fall 3 rise 5

#apache 配置:

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

5.4 ACL

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

[root@haproxy ~]# vim /etc/haproxy/conf.d/acl.cfg
[root@haproxy ~]# cat /etc/haproxy/conf.d/acl.cfg
frontend test_acl
   bind *:80
   mode http
   #acl bad_browers hdr_beg(User-Agent) -i curl
   #http-request deny if bad_browers
   #acl test hdr_dom(host) -i www.timinglee.org
   #acl test hdr_end(host) -i .org
   #acl test base_sub -m sub org
   #acl test path_sub -m sub /a
   #acl test path_end -m sub /a
   #acl test path_reg -i ^/t
   acl test url_sub -m sub lee
   acl test path_dir -m sub a
   use_backend test_web if test
   default_backend default_webserver
backend default_webserver
   mode http
   server web1 172.25.254.20:80 check inter 3 fall 3 rise 5
backend test_web
   mode http
   server web2 172.25.254.30:80 check inter 3 fall 3 rise 5

5.4.1 ACL配置选项

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

acl         <aclname>         <ceiterion>         [flags]             [operator]        [<value>]

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

5.4.2 ACL示例-域名匹配


[root@haproxy ~]# vim /etc/haproxy/conf.d/acl.cfg
[root@haproxy ~]# cat /etc/haproxy/conf.d/acl.cfg
frontend testacl
   bind :80
   mode http
   ###########     ACL settings   #######################
   acl web_host hdr_dom(host) www.timinglee.org
   ###########     host       ###########################
   use_backend timinglee_host if web_host
   ###########     default server     ###################
   default_backend default_webserver
backend timinglee_host
   mode http
   server web1 192.168.0.101:80 check weight 1 inter 3s fall 3 rise 5
   server web2 192.168.0.102:80 check weight 1 inter 3s fall 3 rise 5
backend default_webserver
   mode http
   server web1 172.25.254.10:80 check weight 1 inter 3s fall 3 rise 5

测试:

vim /etc/hosts

172.25.254.100   www.timinglee.org

 curl www.timinglee.org
RS1 192.168.0.101
 curl www.timinglee.org
RS2 server - 192.168.0.102

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


[root@haproxy ~]# vim /etc/haproxy/conf.d/acl.cfg
[root@haproxy ~]# cat /etc/haproxy/conf.d/acl.cfg
frontend testacl
   bind :80
   mode http
   ###########     ACL settings   #######################
   acl ip_test src 172.25.254.1 192.168.0.0/24
   ###########     host       ###########################
   use_backend ip_test-host if ip_test
   ###########     default server     ###################
   default_backend default_webserver
backend ip_test-host
   mode http
   server web1 192.168.0.101:80 check weight 1 inter 3s fall 3 rise 5
backend default_webserver
   mode http
   server web1 172.25.254.10:80 check weight 1 inter 3s fall 3 rise 5

测试:

curl 172.25.254.100
default web server webserver1

curl 172.25.254.100
webserver1 - 172.25.254.10

 curl 172.25.254.10
webserver1 - 172.25.254.10

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

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

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

[root@haproxy ~]# cat /etc/haproxy/conf.d/acl.cfg
frontend testacl
   	bind :80
   	mode http
   	acl user_agent_block hdr_sub(User-Agent) -i curl wget
   	acl user_agent_redirect hdr_sub(User-Agent) -i Mozilla/5.0
  	 http-request deny if user_agent_block
  	 redirect prefix https://www.baidu.com if user_agent_redirect
   	default_backend default_webserver
backend ip_test-host
	mode http
   	server web1 192.168.0.101:80 check weight 1 inter 3s fall 3 rise 5
backend default_webserver
  	 mode http
   	server web1 172.25.254.10:80 check weight 1 inter 3s fall 3 rise 5

5.5 自定义HAProxy 错误界面

haproxy默认使用的错误错误页

[root@haproxy ~]# rpm -ql haproxy24z-2.4.27-1.el7.zenetys.x86_64 | grep -E http$ /usr/share/haproxy/400.http

/usr/share/haproxy/403.http

/usr/share/haproxy/408.http

/usr/share/haproxy/500.http

/usr/share/haproxy/502.http

/usr/share/haproxy/503.http

/usr/share/haproxy/504.http

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

defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000

        errorfile 503 /haproxy/errorpage/503page.http

配置错误报告文件

[root@haproxy ~]# mkdir /haproxy/errorpage/ -p
[root@haproxy ~]# cd /usr/share/haproxy/503.http /haproxy/errorpage/503page.http
-bash: cd: 参数太多
[root@haproxy ~]# cp /usr/share/haproxy/503.http /haproxy/errorpage/503page.http
[root@haproxy ~]# vim /haproxy/errorpage/503page.http 
[root@haproxy ~]# cat /haproxy/errorpage/503page.http 
HTTP/1.0 503 Service Unavailable
Cache-Control: no-cache
Connection: close
Content-Type: text/html

<html><body><h1>hahahahaha</h1>
lalalalalalalalalalalaal
</body></html>

测试:

5.6 HAProxy 四层负载

对MySQL服务实现四层负载

在两台服务器上安装mariadb服务

yum install mariadb-server -y

配置MySQL服务器名字

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

另一台主机同理

配置数据库认证远程登陆

mysql -e "grant all on *.* to lee@'%' identified by 'lee';"

测试:

mysql -ulee -plee   -h172.25.254.100 -e "select @@server_id"
+-------------+
| @@server_id |
+-------------+
|           1 |

mysql -ulee -plee   -h172.25.254.100 -e "select @@server_id"
+-------------+
| @@server_id |
+-------------+
|           2 |

5.7 HAProxy https 实现

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

haproxy配置

[root@haproxy ~]# cat /etc/haproxy/conf.d/https.cfg 
frontend webserver
   bind *:80
   redirect scheme https if !{ ssl_fc }
   mode http
   use_backend webcluster
frontend webserver-https
   bind *:443 ssl crt /etc/haproxy/timinglee.org.pem
   mode http
   use_backend webcluster
backend webcluster
   mode http
   balance roundrobin
   server web1 172.25.254.10:80 check inter 3s fall 3 rise 5
   server web2 172.25.254.20:80 check inter 3s fall 3 rise 5

证书制作:

[root@haproxy ~]# mkdir /etc/haproxy/certs/
[root@haproxy ~]# openssl req -newkey rsa:2048 \
> -node -sha256 -keyout /etc/haproxy/certs/lk.org.key \
> -x509 -days 365 -out /etc/haproxy/certs/lk.org.crt
.+.....+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*............+..+...............+..........+.........+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*.....+....+.....+......+..........+..+.+...........+.........+....+...+........+.+.....+........................+....+.....+............+.+...+.....+............+....+..............+..........+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
............+........+...+.......+...+.....+......+.........+.+....................+.+.....+...+.+...+...+..............+.+..+...+.........+....+.........+.....+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*..+......+............+..+...............+......+.......+........+.......+...+..+.........+.............+........+.........+.+...+......+......+...+..+...+.+.....+......+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*...+..+....+...+..+..........+........+......+......+.+..+...+...+.......+............+...............+..+....+..+.......+........+.......+.....+.+...........+...+......+.+..................+..+.+.....+.............+..+............+.+..+...+.+...+........+.......+...+.........+......+...+.....+......+......+....+...+........+.........+.+..............+...+...+...+.......+..+...+....+......+........+...............+.+...+..+.+.....+....+......+........+..........+..+....+...........+.......+......+......+......+..+......+................+...+..+...+......+.......+.....+.......+..+...+..........+..+...+......+.+......+............+...+..+......+..........+.....+.......+........+.+......+...+............+.....+............+.............+..+.+.....................+.....+...+..........+..+.........+....+..+.+...+.....+....+............+..............+....+...+.....+....+...+...+.........+......+...+.....+.......+..+.......+.....+....+...........+......+............+.+....................+...............+......+......+....+...+...+........+......+.+.....+...........................+...+...+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:ch
State or Province Name (full name) []:shanxi
Locality Name (eg, city) [Default City]:xi`an
Organization Name (eg, company) [Default Company Ltd]:haproxy
Organizational Unit Name (eg, section) []:haproxy
Common Name (eg, your name or your server's hostname) []:haproxy
Email Address []:admin@163.com

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值