haproxy七层代理

负载均衡

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

阿里云SLB介绍 : https://yq.aliyun.com/articles/1803

为什么用负载均衡

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

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

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

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

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

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

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

负载均衡类型 

硬件:

F5 美国F5网络公司 https://f5.com/zh

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

Array 华耀 https://www.arraynetwaorks.com.cn/

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

四层负载均衡 

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

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

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

4.支持四层的软件

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

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

Haproxy:模拟四层转发。 

七层负载均衡 

 

1.通过虚拟ur|或主机ip进行流量识别,根据应用层信息进行解析,决定是否需要进行负载均衡。

2.代理后台服务器与客户端建立连接,如nginx可代理前后端,与前端客户端tcp连接,与后端服务器建立 tcp连接

3.支持7层代理的软件:

Nginx:基于http协议(nginx七层是通过proxy_pass)

Haproxy:七层代理,会话保持、标记、路径转移等 

四层和七层负载均衡的区别 

所谓的四到七层负载均衡,就是在对后台的服务器进行负载均衡时,依据四层的信息或七层的信息来决 定怎么样转发流量
四层的负载均衡,就是通过发布三层的IP地址(VIP),然后加四层的端口号,来决定哪些流量需要做负载均衡,对需要处理的流量进行NAT处理,转发至后台服务器,并记录下这个TCP或者UDP的流量是由哪台服务器处理的,后续这个连接的所有流量都同样转发到同一台服务器处理。
七层的负载均衡,就是在四层的基础上(没有四层是绝对不可能有七层的),再考虑应用层的特征,比如同一个Web服务器的负载均衡,除了根据VIP加80端口辨别是否需要处理的流量,还可根据七层的URL、浏览器类别、语言来决定是否要进行负载均衡。

分层位置:四层负载均衡在传输层及以下,七层负载均衡在应用层及以下
性能:四层负载均衡架构无需解析报文消息内容,在网络吞吐量与处理能力上较高:七层可支持解析应 用层报文消息内容,识别URL、Cookie、HTTP header等信息。
原理:四层负载均衡是基于ip+port;七层是基于虚拟的URL或主机IP等。
功能类比:四层负载均衡类似于路由器;七层类似于代理服务器。
安全性:四层负载均衡无法识别DDoS攻击;七层可防御SYN Cookie/Flood攻击

 haproxy简介

HAProxy是法国开发者威利塔罗(Willy Tarreau)在2000年使用C语言开发的一个开源软件,是一款具备高并发(万级以上)、高性能的TCP和HTTP负载均衡器。支持基于cookie的持久性,自动故障切换,支持正则表达式及web状态统计。
企业版网站:https://www.haproxy.com
社区版网站:http://www.haproxy.org
github:https://github.com/haprox

proxies配置
参数类型作用
defaultsproxies默认配置项,针对以下的frontend、backend和listen生效,可以多个name也可以没有name
frontendproxies前端servername,类似于Nginx的一个虚拟主机 server和LVS服务集群。
backendproxies后端服务器组,等于nginx的upstream和LVS中的RS服务器
listenproxies将frontend和backend合并在一起配置,相对于frontend和backend配置更简洁,生产常用

proxies配置-defaults

参数功能
mode httpHAProxy实例使用的连接协议
log global指定日志地址和记录日志条目的syslog/rsyslog日志设备
option httplog日志记录选项,httplog表示记录与 HTTP会话相关的各种属性值。包括HTTP请求、会话状态、连接数、源地址以及连接时间等
option dontlognulldontlognull表示不记录空会话连接日志
option http-server-close等待客户端完整HTTP请求的时间,此处为等待10s。
option forwardfor except 127.0.0.0/8透传客户端真实IP至后端web服务器;在apache配置文件中加入:
%{X-Forwarded-For}i;后在webserer中看日志即可看到地址透传信息
option redispatch当server Id对应的服务器挂掉后,强制定向到其他健康的服务器,重新派发
option http-keep-alive开启与客户端的会话保持
retries 3连接后端服务器失败次数
timeout queue 60s设置删除连接和客户端收到503或服务不可用等提示信息前的等待时间
timeout connect 120s设置等待服务器连接成功的时间
timeout client 600s设置允许客户端处于非活动状态,即既不发送数据也不接收数据的时间
timeout server 600s设置服务器超时时间,即允许服务器处于既不接收也不发送数据的非活动时间
timeout http-keep-alive 60ssession 会话保持超时时间,此时间段内会转发到相同的后端服务器
timeout check 10s指定后端服务器健康检查的超时时间
maxconn 3000最大连接数量限制
default-server inter 1000 weight 3每隔 1000 毫秒对服务器的状态进行检查

Proxies配置-frontend

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

#格式:

bind [

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

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

Proxies配置backend

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

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

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

option #配置选项

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

server配置

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

 

haproxy实验环境的部署

注意:所有主机的防火墙均为关闭状态!!!!否则会影响实验

haproxyeth0:172.25.254.100主机名:haproxy
webserver1eth0:172.25.254.10主机名:webserver1
webserver2eth0:172.25.254.20主机名:webserver2

给webserver1、2安装nginx

webserver1

[root@webserver1 ~]# dnf install nginx -y
[root@webserver1 ~]# echo webserver1:172.25.254.10 > /usr/share/nginx/html/index.html
[root@webserver1 ~]# systemctl enable --now nginx.service 

webserver2

[root@webserver2 ~]# dnf install nginx -y
[root@webserver2 ~]# echo webserver1:172.25.254.20 > /usr/share/nginx/html/index.html
[root@webserver2 ~]# systemctl enable --now nginx.service 

测试

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

在haproxy主机上安装haproxy服务

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

编辑配置文件

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

将以下内容添加进去

frontend webcluster
    bind *:80
    mode http
    use_backend webcluster-host

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

重启服务

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

本机访问

[C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    25  100    25    0     0   9211      0 --:--:-- --:--:-- --:--:-- 12500
webserver1:172.25.254.10

[C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    25  100    25    0     0  10660      0 --:--:-- --:--:-- --:--:-- 12500
webserver2:172.25.254.20

注释掉之前的内容,重新写入新的内容进去

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

重启服务

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

本机访问

[C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    25  100    25    0     0  10084      0 --:--:-- --:--:-- --:--:-- 12500
webserver1:172.25.254.10

[C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    25  100    25    0     0  11876      0 --:--:-- --:--:-- --:--:-- 12500
webserver2:172.25.254.20
haproxy的全局配置参数

配置参数

[root@haproxy ~]# pstree -p | grep haproxy
           |-haproxy(32904)---haproxy(32906)---{haproxy}(32907)

将nbproc 2写入到配置文件的global中

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
[root@haproxy ~]# systemctl restart haproxy.service 
[root@haproxy ~]# pstree -p | grep haproxy
           |-haproxy(32924)-+-haproxy(32926)
           |                `-haproxy(32927)

记得重启服务

查看多线程数量

[root@haproxy ~]# cat /proc/32960/status | grep -i thread
Threads:	1
Speculation_Store_Bypass:	thread vulnerable

 编辑配置文件

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

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

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

    # utilize system-wide crypto-policies
    ssl-default-bind-ciphers PROFILE=SYSTEM
    ssl-default-server-ciphers PROFILE=SYSTEM
    #nbproc 2
    #cpu-map 1 0
    #cpu-map 2 1
    nbthread 2
    
    
    ·······

重启服务

[root@haproxy ~]# systemctl restart haproxy.service 
[root@haproxy ~]# pstree -p | grep haproxy
           |-haproxy(33009)---haproxy(33011)---{haproxy}(33012)
[root@haproxy ~]# cat /proc/33011/status | grep -i thread
Threads:	2
Speculation_Store_Bypass:	thread vulnerable
定向haproxy日志

编辑配置文件,进行以下修改

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

#module(load="imudp") # needs to be done just once
#input(type="imudp" port="514")
module(load="imudp") # needs to be done just once
input(type="imudp" port="514")


# Log cron stuff
cron.*                                                  /var/log/cron

# Everybody gets emergency messages
*.emerg                                                 :omusrmsg:*

# Save news errors of level crit and higher in a special file.
uucp,news.crit                                          /var/log/spooler

# Save boot messages also to boot.log
local7.*                                                /var/log/boot.log
local2.*                                                /var/log/haproxy.log


重启服务

[root@haproxy ~]# systemctl restart rsyslog.service
haproxy的热更新方法

socat

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

修改配置文件

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

查看haproxy状态

[root@haproxy ~]# echo "show info" | socat stdio /var/lib/haproxy/stats
Name: HAProxy
Version: 2.4.22-f8e3218
Release_date: 2023/02/14
Nbthread: 1
Nbproc: 1
Process_num: 1
Pid: 33542
Uptime: 0d 0h03m43s
Uptime_sec: 223
Memmax_MB: 0
PoolAlloc_MB: 0

查看集群状态

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

查看集群权重

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

设置权重

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

下线后端服务器

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

上线后端服务器

[root@haproxy ~]# echo "enable server webcluster/web1 " | socat stdio
/var/lib/haproxy/stats

多进程处理方法

编辑配置文件

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

stats socket /var/lib/haproxy/stats1 mode 600 level admin process 1
stats socket /var/lib/haproxy/stats2 mode 600 level admin process 2
nbproc 2
cpu-map 1 0
cpu-map 2 1

haproxy算法

HAProxy通过固定参数 balance 指明对后端服务器的调度算法

balance参数可以配置在listen或backend选项中

HAProxy的调度算法分为静态和动态调度算法

有些算法可以根据参数在静态和动态算法中相互转换

静态算法


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

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

不支持运行时利用socat进行权重的动态调整(只支持0和1,不支持其它值)
不支持端服务器慢启动(慢启动是指在服务器刚刚启动时不会把它所应该承担的访问压力全部给它,而是先给一部分,当没有问题后再给一部分)
其后端主机数量没有限制,相当于LVS中的wrr

示例

编辑配置文件

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

listen webcluster
   bind *:80
   mode http
   #balance first
   balance static-rr
   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 1
   

 重启服务

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

测试

[root@test ~]# for i in {1..10}; do curl 172.25.254.100; done
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
webserver1:172.25.254.10

first

根据服务器在列表中的位置,自上而下进行调度

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

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

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

动态算法

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

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

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

静态算法后端Real Server个数不限

roundrobin

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

示例

编辑配置文件

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

listen webcluster
   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 1
   

重启服务

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

leastconn加权的最少连接的动态

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

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

示例

编辑配置文件

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

listen webcluster
   bind *:80
   mode http
   balance leastconn
   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 1

重启服务

[root@haproxy ~]# systemctl restart haproxy.service
其他算法

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

source

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

示例

编辑配置文件

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

listen webcluster
   bind *:80
   mode http
   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 1
   

重启服务

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

测试

[root@test ~]# for i in {1..10}; do curl 172.25.254.100; done
webserver2:172.25.254.20
webserver2:172.25.254.20
webserver2:172.25.254.20
webserver2:172.25.254.20
webserver2:172.25.254.20
webserver2:172.25.254.20
webserver2:172.25.254.20
webserver2:172.25.254.20
webserver2:172.25.254.20
webserver2:172.25.254.20
map-base 取模法

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

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

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

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

一致性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对象到后端服务器的映射关系

一致性hash示意图

uri

基于对用户请求的URI的左半部分或整个uri做hash,再将hash结果对总权重进行取模后

根据最终结果将请求转发到后端指定服务器

适用于后端是缓存服务器场景

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

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

url_param

url_param对用户请求的url中的 params 部分中的一个参数key对应的value值作hash计算,并由服务器

总权重相除以后派发至某挑出的服务器,后端搜索同一个数据会被调度到同一个服务器,多用与电商

通常用于追踪用户,以确保来自同一个用户的请求始终发往同一个real server 如果无没key,将按roundrobin算法

示例

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

#则: host = "www.timinglee.com" url_param = "key=value"

hdr 

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

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

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

算法总结

#静态

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

 各算法使用场景

first                        #使用较少

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

roundrobin

leastconn             #数据库

source

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

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

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

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

高级功能及配置

haproxy的状态页面监控

编辑配置文件

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


listen stats
    mode http
    bind *:4567
    stats enable
    stats refresh 1
    stats uri /status
    stats auth www:www


重启服务

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

浏览器访问测试

基于cookie的会话保持

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

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

示例

配置文件

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

listen webcluster
   bind *:80
   mode http
   balance roundrobin
   cookie WEBCOOKIE insert nocache indirect
   server  web1 172.25.254.10:80 cookie web1 check inter 2 fall 3 rise 5 weight 1
   server  web2 172.25.254.20:80 cookie web2 check inter 2 fall 3 rise 5 weight 1

重启服务

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

测试

[C:\~]$ curl -b WEBCOOKIE=web2 172.25.254.100
    %Total    %Received    %Xferd    Average  Speed   Time    Time      Time    Current
                                     Dload   Upload   Total   Spent     Left    Speed
100    25  100    25       0      0  12100      0 --:--:--  --:--:--  --:--:--   12500
webserver2:172.25.254.20


[C:\~]$ curl -b WEBCOOKIE=web2 172.25.254.100
    %Total    %Received    %Xferd    Average  Speed   Time    Time      Time    Current
                                     Dload   Upload   Total   Spent     Left    Speed
100    25  100    25       0      0  12025      0 --:--:--  --:--:--  --:--:--   12500
webserver2:172.25.254.10
IP透传

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

四层透传

编辑配置文件

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

listen webcluster
   bind *:80
   mode tcp
   #balance first
   #balance static-rr
   balance roundrobin
   #balance leastconn
   #balance source
   #balance uri
   #balance url_param name,userid
   #balance hdr(User-Agent)
   #hash-type consistent
  # redirect prefix http://www.baidu.com/
   #cookie WEBCOOKIE insert nocache indirect
   server  web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 1
   server  web2 172.25.254.20:80 send-proxy check inter 2 fall 3 rise 5 weight 1
#   server web_sorry 172.25.254.100:8080 backup

重启服务

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

查看日志

[root@webserver1 ~]# tail /etc/httpd/logs/access_log 
 - 172.25.254.100 - - [10/Aug/2024:23:09:56 +0800] "PROXY TCP4 172.25.254.100" 400 226 "-" "-"
 - 172.25.254.100 - - [10/Aug/2024:23:09:56 +0800] "PROXY TCP4 172.25.254.100" 400 226 "-" "-"

编辑文件haproxy文件

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen webcluster
   bind *:80
   mode tcp
   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 send-proxy check inter 2 fall 3 rise 5 weight 1

编辑文件nginx文件

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

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      ' "$proxy_protocol_addr"'
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;



    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80 proxy_protocol;
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/html;

查看日志

[root@webserver2 ~]# tail /var/log/nginx/access.log
172.25.254.100 - - [10/Aug/2024:23:06:34 +0800] "PROXY TCP4 172.25.254.100 172.25.254.20 55510 80" 400 0 "-" "-" "-"
172.25.254.100 - - [10/Aug/2024:23:06:34 +0800] "PROXY TCP4 172.25.254.100 172.25.254.20 55526 80" 400 0 "-" "-" "-"
七层IP透传

编辑配置文件

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

listen webcluster
   bind *:80
   mode http
   #balance first
   #balance static-rr
   balance roundrobin
   #balance leastconn
   #balance source
   #balance uri
   #balance url_param name,userid
   #balance hdr(User-Agent)
   #hash-type consistent
  # redirect prefix http://www.baidu.com/
   #cookie WEBCOOKIE insert nocache indirect
   server  web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 1
   server  web2 172.25.254.20:80 send-proxy check inter 2 fall 3 rise 5 weight 1
#   server web_sorry 172.25.254.100:8080 backup

 重启服务

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

配置web服务器

[root@webserver1 ~]# vi /etc/httpd/conf/httpd.conf 

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

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

重启服务

[root@webserver1 ~]# systemctl restart httpd

 测试

[C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    25  100    25    0     0  10794      0 --:--:-- --:--:-- --:--:-- 12500
webserver2:172.25.254.20

[C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    21  100    21    0     0   6231      0 --:--:-- --:--:-- --:--:--  7000
web1 - 172.25.254.10

[C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    21  100    21    0     0   7996      0 --:--:-- --:--:-- --:--:-- 10500
web1 - 172.25.254.10

查看访问的真实ip

[root@webserver1 ~]# tail /etc/httpd/logs/access_log 
172.25.254.1 172.25.254.100 - - [10/Aug/2024:22:39:31 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/8.7.1"
172.25.254.1 172.25.254.100 - - [10/Aug/2024:22:41:33 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/8.7.1"
172.25.254.1 172.25.254.100 - - [10/Aug/2024:22:41:34 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/8.7.1"

 

ACL访问控制列表

访问控制列表ACL(Access Control Lists) 是一种基于包过滤的访问控制技术

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

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

frontend webcluster
     bind *:80
     mode http
     acl test hdr_dom(host) -i www.abc.org
     use_backend webcluster-host if test
     default_backend default-host

backend webcluster-host
     mode http
     server web1 172.25.254.10:80 check inter 2 fall 2 rise 5

backend default-host
     mode http
     server web2 172.25.254.20:80 check inter 2 fall 2 rise 5

重启服务

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

测试

[C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    25  100    25    0     0  12130      0 --:--:-- --:--:-- --:--:-- 12500
webserver2:172.25.254.20

[C:\~]$ curl www.abc.org
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    21  100    21    0     0   2300      0 --:--:-- --:--:-- --:--:--  3000
web1 - 172.25.254.10
利用ACL做动静分离访问控制

基于域名的访问控制

配置文件

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



frontend webcluster
     bind *:80
     mode http
     acl domain hdr_dom(host) -i www.abc.org

#####################################################

     use_backend webcluster-host if domain
     default_backend default-host

backend webcluster-host
     mode http
     server web1 172.25.254.10:80 check inter 2 fall 2 rise 5

backend default-host
     mode http
     server web2 172.25.254.20:80 check inter 2 fall 2 rise 5

测试

[C:\~]$ curl www.abc.org
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    21  100    21    0     0   3558      0 --:--:-- --:--:-- --:--:--  7000
web1 - 172.25.254.10

[C:\~]$ curl www.abc.com
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    25  100    25    0     0   2763      0 --:--:-- --:--:-- --:--:--  3571
webserver2:172.25.254.20

基于IP的访问控制

编辑配置文件

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

frontend webcluster
     bind *:80
     mode http
     acl ctrl_ip src 172.25.254.1  172.25.254.20  192.168.0.0/24


     use_backend webcluster-host if ctrl_ip
     default_backend default-host

backend webcluster-host
     mode http
     server web1 172.25.254.10:80 check inter 2 fall 2 rise 5

backend default-host
     mode http
     server web2 172.25.254.20:80 check inter 2 fall 2 rise 5

测试

[C:\~]$ curl www.abc.com  #本机的IP为172.25.254.1
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    21  100    21    0     0   2151      0 --:--:-- --:--:-- --:--:--  3000
web1 - 172.25.254.10
[root@webserver2 ~]# curl 172.25.254.100
web1 - 172.25.254.10
[root@test ~]# curl 172.25.254.100   
webserver2:172.25.254.20

 拒绝IP访问

编辑配置文件

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


frontend webcluster
     bind *:80
     mode http
     acl ctrl_ip src 172.25.254.1  172.25.254.20  192.168.0.0/24



     http-request deny if ctrl_ip
     default_backend default-host

backend webcluster-host
     mode http
     server web1 172.25.254.10:80 check inter 2 fall 2 rise 5

backend default-host
     mode http
     server web2 172.25.254.20:80 check inter 2 fall 2 rise 5

测试

[C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    93  100    93    0     0  64898      0 --:--:-- --:--:-- --:--:-- 93000
<html><body><h1>403 Forbidden</h1>
                                  Request forbidden by administrative rules.
                                                                            </body></html>
[root@test ~]# curl 172.25.254.100
webserver2:172.25.254.20

基于浏览器类型的访问控制

配置文件

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

frontend webcluster
     bind *:80
     mode http
     acl badwebbrowers hdr_sub(User-Agent) -i curl wget


     http-request deny if badwebbrowers
     default_backend default-host

backend webcluster-host
     mode http
     server web1 172.25.254.10:80 check inter 2 fall 2 rise 5

backend default-host
     mode http
     server web2 172.25.254.20:80 check inter 2 fall 2 rise 5

测试

[C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    93  100    93    0     0  62207      0 --:--:-- --:--:-- --:--:-- 93000
<html><body><h1>403 Forbidden</h1>
                                  Request forbidden by administrative rules.
                                                                            </body></html>

基于后缀名实现动静分离

安装php服务

[root@webserver1 ~]# dnf install php -y

编辑文件

[root@webserver1 ~]# vim /var/www/html/index.php
<?php
        phpinfo();
?>

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


frontend webcluster
     bind *:80
     mode http
     acl static path_end -i .html .jpg .png .css .js  # 静态 
     acl php    path_end -i .php  # 动态


    use_backend webcluster-host if php  
    default_backend default-host   

backend webcluster-host
     mode http
     server web1 172.25.254.10:80 check inter 2 fall 2 rise 5

backend default-host
     mode http
     server web2 172.25.254.20:80 check inter 2 fall 2 rise 5

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

创建文件夹

[root@webserver2 ~]# mkdir /usr/share/nginx/html/static -p

写入到文件

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

测试

[root@webserver2 ~]# curl 172.25.254.20/static/
static - 172.25.254.20

创建php文件

[root@webserver1 ~]# mkdir -p /var/www/html/php

复制文件

[root@webserver1 ~]# cp /var/www/html/index.php /var/www/html/php/

编辑文件

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

frontend webcluster
     bind *:80
     mode http
     acl static path_sub -m sub static
     acl php    path_sub -m sub php



    use_backend webcluster-host if php
    default_backend default-host

backend webcluster-host
     mode http
     server web1 172.25.254.10:80 check inter 2 fall 2 rise 5

backend default-host
     mode http
     server web2 172.25.254.20:80 check inter 2 fall 2 rise 5

基于http重定向错误页面

停止这两个服务

[root@webserver1 ~]# systemctl stop httpd.service
[root@webserver2 ~]# systemctl stop nginx.service

创建文件夹

[root@haproxy ~]# mkdir /etc/haproxy/errorpage -p

编辑文件

[root@haproxy ~]# vim /etc/haproxy/errorpage/503.http 

HTTP/1.0 503 Service Unavailable
Cache-Control: no-cache
Connection: close
Content-Type: text/html;charset=UTF-8

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

编辑文件

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

重启服务

[root@haproxy ~]# systemctl restart haproxy.service
haproxy四层负载

给webserver1、2安装服务

webserver1

[root@webserver1 ~]# dnf install mariadb-server -y

webserver2

[root@webserver2 ~]# dnf install mariadb-server -y

编辑文件

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

启动服务

[root@webserver1 ~]# systemctl start mariadb
[root@webserver1 ~]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 10.5.22-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> SELECT @@server_id;
+-------------+
| @@server_id |
+-------------+
|           1 |
+-------------+
1 row in set (0.000 sec)

MariaDB [(none)]> create user xx@'%' identified by 'xx';
Query OK, 0 rows affected (0.001 sec)

MariaDB [(none)]> grant all on *.* to xx@'%';
Query OK, 0 rows affected (0.001 sec) 

webserver2编辑文件配置

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

启动服务

[root@webserver2 ~]# systemctl start mariadb
[root@webserver2 ~]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 10.5.22-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> SELECT @@server_id;
+-------------+
| @@server_id |
+-------------+
|           2 |
+-------------+
1 row in set (0.000 sec)

MariaDB [(none)]> create user xx@'%' identified by 'xx';
Query OK, 0 rows affected (0.001 sec)

MariaDB [(none)]> grant all on *.* to xx@'%';
Query OK, 0 rows affected (0.001 sec)

给测试主机安装服务

[root@test ~]# dnf install mariadb -y
[root@test ~]# mysql -uwcm -p -h 172.25.254.10
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 4
Server version: 10.5.22-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> 

编辑hap主机

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

listen dbserver
    bind *:3306
    mode tcp
    balance roundrobin
    server db1 172.25.254.10:3306 check inter 2 fall 2 rise 5
    server db2 172.25.254.20:3306 check inter 2 fall 2 rise 5

重启服务

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

test主机

[root@test ~]# mysql -uxx -pxx -h 172.25.254.100
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 5
Server version: 10.5.22-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> select @@server_id;
+-------------+
| @@server_id |
+-------------+
|           1 |
+-------------+
1 row in set (0.001 sec)

MariaDB [(none)]> exit
Bye
[root@test ~]# mysql -uxx -pxx -h 172.25.254.100
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 4
Server version: 10.5.22-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> select @@server_id;
+-------------+
| @@server_id |
+-------------+
|           2 |
+-------------+
1 row in set (0.001 sec)
haproxy的基于https的加密访问

创建文件夹

[root@haproxy ~]# mkdir -p /etc/haproxy/certs

 加密配置

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值