haproxy算法与具体实现

一、负载均衡

1.什么是负载均衡

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

2.为什么用负载均衡

  • Web服务器的动态水平扩展-->对用户无感知
  • 增加业务并发访问及处理能力-->解决单服务器瓶颈问题
  • 节约公网IP地址-->降低IT支出成本
  • 隐藏内部服务器IP-->提高内部服务器安全性
  • 配置简单-->固定格式的配置文件
  • 功能丰富-->支持四层和七层,支持动态下线主机
  • 性能较强-->并发数万甚至数十万

3.四层负载均衡

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

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

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

4.支持四层的软件 lvs:重量级四层负载均衡器。 Nginx:轻量级四层负载均衡器,可缓存。(nginx四层是通过upstream模块) Haproxy:模拟四层转发。 

4.七层负载均衡

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

2.代理后台服务器与客户端建立连接,如nginx可代理前后端,与前端客户端tcp连接,与后端服务器建立 tcp连接, 3.支持7层代理的软件: Nginx:基于http协议(nginx七层是通过proxy_pass) Haproxy:七层代理,会话保持、标记、路径转移等。 

 3.支持7层代理的软件: Nginx:基于http协议(nginx七层是通过proxy_pass) Haproxy:七层代理,会话保持、标记、路径转移等

5. 四层和七层的区别

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

1.分层位置:四层负载均衡在传输层及以下,七层负载均衡在应用层及以下

2.性能 :四层负载均衡架构无需解析报文消息内容,在网络吞吐量与处理能力上较高:七层可支持解析应用 层报文消息内容,识别URL、Cookie、HTTP header等信息。

3.原理 :四层负载均衡是基于ip+port;七层是基于虚拟的URL或主机IP等。

4.功能类比:四层负载均衡类似于路由器;七层类似于代理服务器。

5.安全性:四层负载均衡无法识别DDoS攻击;七层可防御SYN Cookie/Flood攻击

二、haproxy的安装和服务信息

我们的lvs是集成在内核中的,响应速度快,但是当客户访问的一台rs挂了之后,lvs默认并没有能力进行后端检测,而是会直接报一个connection refused的错误

这个时候就需要用到我们的haproxy了,当一台rs崩溃了,客户也不会察觉到,而且lvs只能做四层,而haproxy可以做七层负载。

在linux系统中,直接用以下命令安装haproxy即可

dnf install haproxy -y

1.haproxy基本配置实验

实验环境:克隆三台主机,设置在同一个网段

haproxy:ip为172.25.254.100 主机名haproxy.karl.org

web1:ip为172.25.254.10 主机名webserver1.karl.org

web2:ip为172.25.254.20 主机名webserver2.karl.org

在haproxy中:

dnf install haproxy -y

分别在web1和web2中安装nginx服务,写入东西并启动:

dnf install nginx -y
echo webserver1 - 172.25.254.10 > /usr/share/nginx/html/index.html
systemctl enable --now nginx.service

最后在haproxy上测试:

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

 如果你不知道haproxy的配置文件在哪里,可以用rpm -qc命令查找:

[root@haproxy ~]# rpm -qc haproxy
/etc/haproxy/haproxy.cfg
/etc/logrotate.d/haproxy
/etc/sysconfig/haproxy

如果你在编写haproxy的配置文件的时候感觉tab不补齐不方便,你可以编写~/.vimrc

[root@haproxy ~]# cat ~/.vimrc
set ts=4 ai sw=4

其中ts是一个tab缩进的长度是4,ai代表自动缩进,sw代表在缩进代码时的缩进量(shiftwidth)为 4

打开/etc/haproxy/haproxy.cfg这个配置文件,找到fronted板块,添入fronted webcluster及以下的内容:

#---------------------------------------------------------------------
# main frontend which proxys to the backends
#---------------------------------------------------------------------
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

更改之后不要忘记了重启,不过我们是第一次配置,所以是启动,但是我查看状态发现没有启动,所以用两个命令把haproxy启动了

[root@haproxy ~]# systemctl enable haproxy.service 
Created symlink /etc/systemd/system/multi-user.target.wants/haproxy.service → /usr/lib/systemd/system/haproxy.service.
[root@haproxy ~]# systemctl status haproxy
○ haproxy.service - HAProxy Load Balancer
     Loaded: loaded (/usr/lib/systemd/system/haproxy.service; enabled; vendo>
     Active: inactive (dead)
[root@haproxy ~]# systemctl start haproxy
[root@haproxy ~]# systemctl status haproxy
● haproxy.service - HAProxy Load Balancer
     Loaded: loaded (/usr/lib/systemd/system/haproxy.service; enabled; vendo>
     Active: active (running) since Sun 2024-08-11 17:59:31 CST; 3s ago
    Process: 31019 ExecStartPre=/usr/sbin/haproxy -f $CONFIG -f $CFGDIR -c ->
   Main PID: 31021 (haproxy)

现在我们可以来测试一下haproxy有没有后端检测当rs掉线了,客户这边会不显示掉线的rs的情况,同时也是把负载转移到没有宕机的real server上

rs1宕机前:

C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     100    27  100    27    0     0   1086      0 --:--:-- --:--:-- --:--:--  1125
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
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     100    27  100    27    0     0   7812      0 --:--:-- --:--:-- --:--:--  9000
webserver2 - 172.25.254.20

现在把rs1关闭nginx服务:

systemctl stop nginx.service

无论客户机访问多少次,已经停止nginx服务的rs1都不会再提供给客户端:

[C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--       0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     100    27  100    27    0     0   9066      0 --:--:-- --:--:-- --:--:--  9000
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
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     100    27  100    27    0     0   6991      0 --:--:-- --:--:-- --:--:--  9000
webserver2 - 172.25.254.20

 刚刚的haproxy配置文件写法是前后端分开写的,这里提供一种一起写的方法:

#---------------------------------------------------------------------
# main frontend which proxys to the backends
#---------------------------------------------------------------------
#frontend webcluster
#   bind *:80
#   mode http
#   use_backend webcluster-host
#
#backend webcluster-host
#   balance roundrobin
#   server web1 172.25.254.10:80
#   server web2 172.25.254.20:80

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

 重启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
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     100    27  100    27    0     0   1034      0 --:--:-- --:--:-- --:--:--  1038
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
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     100    27  100    27    0     0   8287      0 --:--:-- --:--:-- --:--:--  9000
webserver2 - 172.25.254.20

2.haproxy的全局配置参数及日志分离

在默认情况下,haproxy只有一个进程:

[root@haproxy ~]# pstree -p | grep haproxy
           |-haproxy(31115)---haproxy(31117)---{haproxy}(31118)

设置haproxy worker的进程数为2

vim /etc/haproxy/haproxy.cfg

在global板块的最后一行添加nbproc 2

    # utilize system-wide crypto-policies
    ssl-default-bind-ciphers PROFILE=SYSTEM
    ssl-default-server-ciphers PROFILE=SYSTEM
    nbproc 2
#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------

重启haproxy

systemctl restart haproxy.service

这个时候再过滤一下haproxy的进程数

[root@haproxy ~]# pstree -p |  grep haproxy
           |-haproxy(31168)-+-haproxy(31171)
           |                `-haproxy(31172)

我们就使用nbproc 2参数把haproxy的进程数更改为了2

这里科普两个参数:

cpu-map 1 0 全 局 绑定haproxy worker 进程至指定CPU,将第1个work进程绑 定至0号CPU

 cpu-map 2 1 全 局 绑定haproxy worker 进程至指定CPU,将第2个work进程绑 定至1号CPU

添加参数到haproxy配置文件中,重启查看效果

    nbproc 2
    cpu-map 1 0
    cpu-map 2 1
#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------

查看效果

[root@haproxy ~]# pstree -p |  grep haproxy
           |-haproxy(31184)-+-haproxy(31187)
           |                `-haproxy(31188)

定向haproxy的日志:

查看global中的log那一行的参数可知,haproxy的日志属于local2

    log         127.0.0.1 local2

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

进入rsyslog的日志采集文件

vim /etc/rsyslog.conf 

开启udp采集,在rhel9中需要开启,在rhel7版本和欧拉操作系统不需要

# Provides UDP syslog reception
# for parameters see http://www.rsyslog.com/doc/imudp.html
module(load="imudp") # needs to be done just once
input(type="imudp" port="514")

将采集到的日志保存在/var/log/haproxy.log中

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

重启rsyslog

systemctl restart rsyslog.service

默认这个目录是没有创建的

[root@haproxy ~]# ll /var/log/haproxy.log
ls: 无法访问 '/var/log/haproxy.log': 没有那个文件或目录

我们在客户端访问haproxy的时候,由于rs1的nginx此时处于报废状态,所以haproxy会让客户无法察觉,并把原来rs1的负载全分配给rs2,此时rsyslog便会采集到haproxy的日志:

[C:\~]$ curl 172.25.254.100
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --100    27  100    27    0     0   7690      0 --:--:-- --:--:-- --:--:--  9000
webserver2 - 172.25.254.20
[root@haproxy ~]# ll /var/log/haproxy.log
-rw------- 1 root root 174  8月 11 22:46 /var/log/haproxy.log

查看一下日志的具体内容:

[root@haproxy ~]# cat /var/log/haproxy.log
Aug 11 22:46:57 localhost haproxy[31326]: 172.25.254.1:52537 [11/Aug/2024:22:46:57.640] webcluster webcluster/web2 0/0/0/1/1 200 226 - - ---- 1/1/0/0/+1 0/0 "GET / HTTP/1.1"

三、haproxy的算法

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

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

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

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

1、静态算法 静态算法:

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

static-rr:

基于权重的轮询调度 不支持运行时利用socat进行权重的动态调整(只支持0和1,不支持其它值)

不支持端服务器慢启动

其后端主机数量没有限制,相当于LVS中的 wrr

first

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

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

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

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

2 、动态算法 动态算法

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

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

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

 roundrobin

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

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

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

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

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

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

leastconn leastconn

加权的最少连接的动态

支持权重的运行时调整和慢启动

即:根据当前连接最少的后端服务器而非权重进行优先调度(新客户 端连接)

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

3 、其他算法

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

source

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

map-base 取模法

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

一致性hash

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

hash环偏斜问题

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

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

一致性hash示意图 后端服务器在线与离线的调度方式: 

uri

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

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

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

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

 

四、haproxy-ip透传 

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

当我们的客户端访问的是nginx发布的东西时,取消haproxy配置文件中我注释的这一行,便可看见是哪个ip访问的nginx

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

更改后重启haproxy

systemctl restart haproxy.service

模拟客户访问rs

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

查看我们的nginx日志文件,可以发现172.25.254.1正是客户端的ip

[root@webserver2 ~]# > /var/log/nginx/access.log 
[root@webserver2 ~]# cat /var/log/nginx/access.log 
172.25.254.100 - - [11/Aug/2024:23:27:26 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/8.7.1" "172.25.254.1"

五、haproxy中利用acl完成动静分离

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

打开haproxy配置文件

vim /etc/haproxy/haproxy.cfg
frontend testacl
   bind :80
   mode http
   ###########     ACL settings   #######################
   acl url_static path_end -i .jpg .png .css .js .html
   acl url_php     path_end -i .php
   ###########     host       ###########################
   use_backend static_host if url_static
   use_backend php_host if url_php
   ###########     default server     ###################
   default_backend default_webserver


backend static_host
   mode http
   server web2 192.168.0.101:80 check weight 1 inter 3s fall 3 rise 5
backend php_host
   mode http
   server web1 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

测试一下:

[root@rs1 ~]# echo css 192.168.0.101 > /usr/share/nginx/html/index.css
[root@rs2 ~]# echo php 192.168.0.102 > /var/www/html/index.php
[root@node10 ~]# curl 172.25.254.100/index.php
php 192.168.0.102
[root@node10 ~]# curl 172.25.254.100/index.css
css 192.168.0.101

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

打开haproxy配置文件

vim /etc/haproxy/haproxy.cfg
frontend testacl
   bind :80
   mode http
   ###########     ACL settings   #######################
   acl url_static path_end -i .jpg .png .css .js .html
   acl url_static path_end -m sub /static /images /javascript
   acl acl_app     path_beg -m sub /api
   ###########     host       ###########################
   use_backend static_host if url_static
   use_backend api_host if acl_app
   ###########     default server     ###################
   default_backend default_webserver


backend static_host
   mode http
   server web2 192.168.0.101:80 check weight 1 inter 3s fall 3 rise 5
backend api_host
   mode http
   server web1 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

创建相关文件

[root@rs1 ~]# mkdir /usr/share/nginx/html/static
[root@rs1 ~]# echo static 192.168.0.101 > /usr/share/nginx/html/static/index.html
[root@rs2 ~]# mkdir /var/www/html/api/
[root@rs2 ~]# echo api 192.168.0.102 > /var/www/html/api/index.html

测试访问

[root@node10 ~]# curl 172.25.254.100/api/
api 192.168.0.102
[root@node10 ~]# curl 172.25.254.100/static/
static 192.168.0.101

六、HAProxy 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 } 

1.证书制作

haproxy ~]# mkdir /etc/haproxy/certs/
haproxy ~]# openssl req -newkey rsa:2048 \ 
-nodes -sha256 –keyout /etc/haproxy/certs/timinglee.org.key \ 
-x509 -days 365 -out /etc/haproxy/certs/timinglee.org.crt

2.https配置示例

haproxy ~]# vim /etc/haproxy/haproxy.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.200:80 check inter 3s fall 3 rise 5
   server web2 172.25.254.201:80 check inter 3s fall 3 rise 5
[root@客户端 ~]#curl -IkL http://172.25.254.100
HTTP/1.1 302 Found
content-length: 0 
location: https://www.timinglee.org/
cache-control: no-cache
HTTP/1.1 200 OK
date: Sat, 04 Apr 2020 02:31:31 GMT
server: Apache/2.4.6 (CentOS) PHP/5.4.16
last-modified: Thu, 02 Apr 2020 01:44:13 GMT
etag: "a-5a244f01f8adc"
accept-ranges: bytes
content-length: 10
content-type: text/html; charset=UTF-8
[root@centos6 ~]#curl -Ik https://www.timinglee.org
HTTP/1.1 200 OK
date: Sat, 04 Apr 2020 02:31:50 GMT
server: Apache/2.4.6 (CentOS) PHP/5.4.16
last-modified: Thu, 02 Apr 2020 01:44:28 GMT
etag: "a-5a244f0fd5175"
accept-ranges: bytes
content-length: 10
content-type: text/html; charset=UTF-8

至此,haproxy的笔记大致总结完成。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值