haproxy七层代理

一、负载均衡

1.1、什么是负载均衡

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

1.2.为什么用负载均衡

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

1.3.负载均衡类型

1.3.1四层负载均衡

1.通过ip+port决定负载均衡的去向。
2.对流量请求进行NAT处理,转发至后台服务器
3.记录tcp、udp流量分别是由哪台服务器处理,后续该请求连接的流量都通过该服务器处理
4.支持四层的软件

  •  lvs: 重量级四层负载均衡器
  •  Nginx: 轻量级四层负载均衡器,可缓存。(nginx四层是通过upstream模块
  •  Haproxy: 模拟四层转发

1.3.2 七层负载均衡

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

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

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

  • Nginx:基于http协议(nginx七层是通过proxy_pass)
  • Haproxy:七层代理,会话保持、标记、路径转移等。

1.3.3 四层和七层的区别

所谓的四到七层负载均衡,就是在对后台的服务器进行负载均衡时,依据四层的信息或七层的信息来决定怎么样转发流量。


四层的负载均衡,就是通过发布三层的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简介

HAProxy是一种免费、非常快速且可靠的反向代理,可为基于TCP和HTTP的应用程序提供高可用性、负载平衡和代理。它特别适用于流量非常大的网站,并为世界上访问量最大的网站中的很大一部分提供支持。多年来,它已成为事实上的标准开源负载均衡器,现在随大多数主流Linux发行版一起提供,并且通常默认部署在云平台中。由于它不为自己做广告,我们只有在管理员报告时才知道它被使用了HAProxy核心团队并行维护多个版本。从1.8版本开始,每年发布两个主要版本。第一个数字通常表示重大更改(配置格式等),但实际上很少更改。第二位数字表示新功能。两者构成一个分支。这些数字后面会出现一个额外的数字,表示错误修复版本偶数号的分支称为“LTS”(“长期支持 ,区域在发布后保留5年。在此期间,他们将收到对发布后发现的错误的修复,这些分支针对的是般用户,他们寻求极度的稳定性并且不想过于频繁地验证新版本但仍希望获得修复。奇数分支仅称为“稳定”,它们针对的是高技能用户,他们喜欢经常升级以从现代功能中受益,并且在出现问题时也能够回滚。这些版本的维护时间为12到18个月。持续时间短并且故意不严格,以便根据反馈与用户一起决定维护周期,并且这些版本不会最终出现在嵌入式产品中。如果有一些合理的需求并且该操作被认为足够无风险,则可能会向后移植一些功能到这些版本。

三、haproxy实验

环境说明

haproxy: ip172.25.254.100/24

[root@haproxy ~]# dnf install nginx -y                 #下载服务!

webserver1: ip172.25.254.10/24

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

[root@webserver1 ~]# echo webserver -172.25.254.10 > /usr/share/nginx/html/index.html

[root@webserver1 ~]# systemctl enable --now nginx

webserver2:ip172.25.254.20/24

[root@webserver2 ~]#dnf install nginx -y

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

[root@webserver2 ~]#systemctl enable --now nginx

3.1haproxy负载均衡的实现

编辑配置文件

vim /etc/haproxy/haproxy.cfg

将webserver1的ngnix服务停掉之后测试

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

设置多进程

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

[root@haproxy ~]# systemctl restart haproxy           #重启服务

设置多线程

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

[root@haproxy ~]# systemctl restart haproxy           #重启服务

多线程跟多进程只能开启一个 不能同时启动

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

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

[root@haproxy ~]# systemctl restart haproxy           #重启服务

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

3.3 常用配置参数

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

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

[root@haproxy ~]# vim /etc/hhtpd/conf/httpd.conf   #监听端口改为8080

[root@haproxy ~]# systemctl restart httpd

下线指定realserver

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

测试

访问重定向

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

[root@haproxy ~]# systemctl restart haproxy

测试

3.4 haproxy热更新方法

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

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

#查看权重

[root@haproxy ~]# echo get weight webcluster/web1 | socat stdio /var/lib/haproxy/stats

#更改web1的权重为1

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

[root@haproxy ~]# echo get weight webcluster/web1 | socat stdio /var/lib/haproxy/stats

[root@haproxy ~]# echo 'get servers state' | socat stdio /var/lib/haproxy/stats
[root@haproxy ~]# echo 'show servers state' | socat stdio /var/lib/haproxy/stats

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

多进程进行热处理

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

[root@haproxy ~]# echo 'show info ' | socat stdio /var/lib/haproxy/stats1

[root@haproxy ~]# echo 'show info ' | socat stdio /var/lib/haproxy/stats2

3.5haproxy算法

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

static-rr:基于权重的轮询调度
不支持运行时利用socat进行权重的动态调整(只支持0和1)

不支持端服务器慢启动(服务刚启动时缓慢的给流量)

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

listen webcluster
    bind *:80
    mode http
    balance static-rr #设置static-rr
   # 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 1
    server web_sorry 172.25.254.100:8080 backup

[root@haproxy ~] echo "set weight webcluster/web1 1" | socat stdio /var/lib/haproxy/stats 
Backend is using a static LB algorithm and only accepts weights '0%' and '100%'.
#不能修改


效果展示

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

 


根据服务器在列表的位置,从上往下调度,只有第一个满了才调度到下一台

会忽略服务器的权重设置

不支持socat进行动态修改权重

listen webcluster
    bind *:80
    mode http
    balance first
   # balance static-rr 
   # balance roundrobin
   # redirect prefix http://www.baidu.com/
    server web1 172.25.254.10:80 maxconn 1 check inter 2 fall 3 rise 5 weight 2 #最大连接数改为1
    server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1
    server web_sorry 172.25.254.100:8080 backup



效果展示

[root@servera ~]# 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
webserver2 - 172.25.254.20#在多台虚拟机上做死循环,模拟web1服务器满了的情况,所以出现20
webserver1 - 172.25.254.10


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

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

支持权重的运行时调整,不同于lvs中的rr轮询的一点是支持慢启动

后端支持4095个real server

支持对real server权重动态调整,将流量打到权重高且负载小的主机,优先选择负载小

使用广泛,为默认算法

listen webcluster
    bind *:80
    mode http
   # balance first
   # balance static-rr 
    balance roundrobin
   # redirect prefix http://www.baidu.com/
    server web1 172.25.254.10:80 maxconn 1 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
    server web_sorry 172.25.254.100:8080 backup

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

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


1 (initial 2)
效果展示

[root@servera ~]# 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
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10


#这样显示的原因为开启了多台虚拟机上做死循环,roundrobin选择负载小且权重高的主机,优先选择负载小
leastconn
加权最少链接的动态

支持权重的运行时调整和慢启动,根据当前连接最少的后端服务器而不是权重进行优先调度

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

listen webcluster
    bind *:80
    mode http
   # balance first
   # balance static-rr 
   # balance roundrobin
     balance leastconn
   # redirect prefix http://www.baidu.com/
    server web1 172.25.254.10:80 maxconn 1 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
    server web_sorry 172.25.254.100:8080 backup

其他算法
其他算法既可以作为静态,也可以通过选项作为动态,通过在haproxy.cfg中设置hash-type consistent改为动态

source
源地址hash,基于用户源地址hash并将请求转发到后端服务器,后续同一个源地址请求将被转发至同一个web服务器中。默认为静态方式,可以通过hash-type支持选项更改,一般是在不插入Cookie的TCP模式下使用,也可以拒绝会话cookie的客户提供最好的会话粘性,有两种转发客户端请求到后端服务器选取计算方法,分别为取模法和hashi一致法

map-base取模法
对source地址进行hash计算,再基于服务器总权重的取模决定此请求转发至对应的后端服务器。此方法为静态,不支持在线调整权重,不支持慢启动,是hash-type指定的默认算法

缺点:服务器总权重发生变化时,如有服务器上线或下线,都会导致调度结果整体改变,导致会话丢失

hash一致性
当服务器总权重发生变化时,对调度结果的影响是局部的,不会引起大的变动。此方法是动态的,支持haproxy的热处理,支持慢启动

算法:

1、后端服务器哈希环点keyA=hash(后端服务器虚拟ip)%(2^32),得到的值在[0---2^32-1]之间
2、客户机哈希环点key1=hash(client_ip)%(2^32) 得到的值在[0---2^32-1]之间
3、将keyA和key1都放在hash环上,将用户请求调度到离key1最近的keyA对应的后端服务器,以顺时针在hash环上找

listen webcluster
    bind *:80
    mode http
   # balance first
   # balance static-rr 
   # balance roundrobin
   # balance leastconn
   # redirect prefix http://www.baidu.com/
   # cookie webcookie insert nocache indirect
    balance source
    hash-type consistent #加上为动态,使用hash一致性,不加则为静态,使用source
    server web1 172.25.254.10:80 send-proxy 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
    server web_sorry 172.25.254.100:8080 backup

uri
uri:资源在互联网中的唯一标识符,url:资源在服务器中的真实位置

基于对用户请求的uri的左半部分或整个uri做hash,再将hash结果对总权重进行取模后根据最终结果将请求转发到后端指定服务器

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

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

<scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<frag>
#<scheme>协议名称,<user>:<password>用户和密码(web中不写),<params>:指令<query>:指令指定的某一字段,<frag>:快速索引文章中的某一片段
左半部分:/<path>;<params>
整个uri:/<path>;<params>?<query>#<frag>
listen webcluster
    bind *:80
    mode http
   # balance first
   # balance static-rr 
   # balance roundrobin
   # balance leastconn
     balance uri
   # balance source
    hash-type consistent
   # 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 1
   # server web_sorry 172.25.254.100:8080 backup

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

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

效果:

[root@servera ~] curl 172.25.254.100/index1.html
172.25.254.10 - index1.html
[root@servera ~] curl 172.25.254.100/index2.html
172.25.254.20 - index2.html
[root@servera ~] curl 172.25.254.100/index3.html
172.25.254.10 - index3.html
[root@servera ~] curl 172.25.254.100/index3.html
172.25.254.10 - index3.html #uri不变,访问的路径或地址也不变



url-param
对用户请求的url中的params部分中的一个参数key对应的value值进行hash计算,常用于追踪用户,确保来自同一个用户的请求始终发往同一个real server,如果没key按rr算法执行

listen webcluster
    bind *:80
    mode http
   # balance first
   # balance static-rr 
   # balance roundrobin
   # balance leastconn
   # balance uri
    balance url_param name,userid #关键字为name,userid
   # balance source
    hash-type consistent
   # redirect prefix http://www.baidu.com/

    server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 1
    server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1
   # server web_sorry 172.25.254.100:8080 backup

[root@servera ~]# curl 172.25.254.100/index.html?name=lee
webserver1 - 172.25.254.10
[root@servera ~]# curl 172.25.254.100/index.html?name=lee
webserver1 - 172.25.254.10
[root@servera ~]# curl 172.25.254.100/index.html?name=lee
webserver1 - 172.25.254.10
[root@servera ~]# curl 172.25.254.100/index.html?name=test
webserver2 - 172.25.254.20
[root@servera ~]# curl 172.25.254.100/index.html?name=test
webserver2 - 172.25.254.20
#搜索为同一name,则被调度到同一服务器上


hdr
针对用户每个http头部(header)请求中的指定信息做hash,由name指定的http头部将会被取出并做hash,然后由服务器总权重取模之后派发至某跳出的服务器,如果无有效值则会使用默认的轮询调度,适用于不同的浏览器访问不同的主机

listen webcluster
    bind *:80
    mode http
   # balance first
   # balance static-rr 
   # balance roundrobin
   # balance leastconn
   # balance uri
   # balance url_param name,userid
    balance hdr(User-Agent) #User-Agent:浏览器
   # balance source
    hash-type consistent
   # redirect prefix http://www.baidu.com/

    server web1 172.25.254.10:80 check inter 2 fall 3 rise 5 weight 1
    server web2 172.25.254.20:80 check inter 2 fall 3 rise 5 weight 1
   # server web_sorry 172.25.254.100:8080 backup



算法总结

#静态
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状态页
通过web界面显示当前haproxy的运行状态

stats enable #基于默认的参数启用stats page
stats hide-version #将状态页中haproxy版本隐藏
stats refresh <delay> #设定自动刷新时间间隔,默认不自动刷新
stats uri <prefix> #自定义stats page uri,默认值:/haproxy?stats
stats auth <user>:<passwd> #认证时的账号和密码,可定义多个用户,每行指定一个用户
#默认:不用认证
stats admin { if | unless } <cond> #启用stats page中的管理功能,为了安全性一般不启动
#---------------------------------------------------------------------
listen stats
    mode http #模式为http
    bind *:1234 #监听端口为1234
    stats enable #打开状态页功能
    stats uri /status #自定义status,访问时应写:172.25.254.100:1234/status
    stats auth lee:lee #验证时账号密码都为lee
    
#---------------------------------------------------------------------

3.6高级功能及配置


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

listen webcluster
    bind *:80
    mode http
   # balance first
   # balance static-rr 
    balance roundrobin
   # balance leastconn
   # redirect prefix http://www.baidu.com/
    cookie webcookie insert nocache indirect
    #cookie的名字为webcookie,insert:插入新的cookie,nocache:如果有缓存服务器则不缓存cookie,indirect
    server web1 172.25.254.10:80 cookie lee1 check inter 2 fall 3 rise 5 weight 2
    #当被调度到10rs上时,会发送一个cookie=lee1并进行缓存,下次访问时验证cookie的值,为lee1就继续调度到10的rs上
    server web2 172.25.254.20:80 cookie lee2 check inter 2 fall 3 rise 5 weight 1
    server web_sorry 172.25.254.100:8080 backup

IP透传技术

[root@haproxy ~]#dnf insatll httpd -y

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

ACL
是一种基于包过滤的访问控制技术

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

acl匹配规范
hdr
[root@haproxy haproxy]# vim haproxy.cfg
frontend webcluster
    bind *:80
    mode http
    acl test hdr_dom(host) -i www.jisoo.org 
    # -i:忽略大小写, hdr_dom(host):与host进行匹配
    #acl test hdr_end(host) -i .org #hdr_end(host):与结尾为.org的host进行匹配
    #acl test hdr_beg(host) -i  bbs #hdr_beg(host):与开头为bbs的host进行匹配
    use_backend webcluster-host if test 
    #如果符合test的设定,就访问webcluster-host设定的10
    default_backend default-host
    #如果不符合就访问default-host设定的20,默认

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 haproxy]# systemctl restart haproxy.service
 

在虚拟机中添加解析
[root@servera ~]# vim /etc/hosts
  127.0.0.1   localhost localhost.localdomain localhost4      localhost4.localdomain4
  ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
  172.25.254.100 www.jisoo.org                         
[root@servera ~]# curl www.jisoo.org
webserver1 - 172.25.254.10(apache)
[root@servera ~]# curl 172.25.254.100
webserver2 - 172.25.254.20

base
#返回第一个主机头和请求的路径部分的连接,该请求从主机名开始,并在问号之前结束,对虚拟主机有用

<scheme>://<user>:<password>@#<host>:<port>/<path>;<params>#?<query>#<frag> <scheme>://<user>:<password>@#<host>:<port>/<path>;<params>为base

frontend webcluster
    bind *:80
    mode http
    #acl test hdr_dom(host) -i www.jisoo.org
    #acl test hdr_end(host) -i .org
    acl test base_sub -m sub bbs
    #表示与在名字中包含bbs的匹配
    #acl test base_reg -i bbs/$ #匹配名字中以bbs结尾
    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@server1 ~] mkdir /var/www/html/bbs -p
[root@server1 ~] echo 172.25.254.10 bbs > /var/www/html/bbs/index.html

效果展示

[root@servera ~] vim /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
172.25.254.100 www.jisoo.org bbs.jisoo.org www.jisoobbs.org 
[root@servera ~] curl www.jisoobbs.org
webserver1 - 172.25.254.10(apache)
[root@servera ~] curl bbs.jisoo.org
webserver1 - 172.25.254.10(apache)
[root@servera ~] curl www.jisoo.org
webserver2 - 172.25.254.20
[root@servera ~] curl www.jisoo.org
webserver2 - 172.25.254.20
[root@servera ~] curl www.jisoo.org/bbs/ #尽管地址中没有带有bbs,但访问带有bbs的文件即路径包含bbs还是能访问到10
172.25.254.10 bbs

path
#提取请求的URL路径,该路径从第一个斜杠开始,并在问号之前结束(无主机部分)

<scheme>://<user>:<password>@<host>:<port>#/<path>;<params>#?<query>#<frag> <path>;<params>为path

base中包含path,因为base表示的更多,包括path表示的

frontend webcluster
    bind *:80
    mode http
    #acl test hdr_dom(host) -i www.jisoo.org
    #acl test hdr_end(host) -i .org
    #acl test base_sub -m sub bbs
    acl test path_sub -m sub bbs
    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@servera ~] curl www.jisoo.org
webserver2 - 172.25.254.20
[root@servera ~] curl bbs.jisoo.org 
#尽管包含了bbs但不在path包含的范围内,所以显示20
webserver2 - 172.25.254.20
[root@servera ~] curl bbs.jisoo.org/bbs/
172.25.254.10 bbs
[root@servera ~] curl www.jisoo.org/bbs/
#尽管没有bbs但最终是以bbs结尾,/后面为path包含的范围,所以可以显示10
172.25.254.10 bbs

acl匹配模式
-i 不区分大小写

-m 使用指定的正则表达式匹配方法

-n 不做DNS解析

-u 禁止acl重名,否则多个同名ACL匹配或关系

acl具体操作符
整数比较:eq、ge、gt、le、lt

字符比较:

exact match (-m str) :字符串必须完全匹配模式

substring match (-m sub) :在提取的字符串中查找模式,如果其中任何一个被发现,ACL将匹配

prefix match (-m beg) :在提取的字符串首部中查找模式,如果其中任何一个被发现,ACL将匹配

suffix match (-m end) :将模式与提取字符串的尾部进行比较,如果其中任何一个匹配,则ACL进行匹配

subdir match (-m dir) :查看提取出来的用斜线分隔(“/")的字符串,如其中任一个匹配,则ACL进行匹配

domain match (-m dom) :查找提取的用点(“.")分隔字符串,如果其中任何一个匹配,则ACL进行匹配

acl操作对象
- Boolean #布尔值

- integer or integer range #整数或整数范围,比如用于匹配端口范围

- IP address / network #IP地址或IP范围, 192.168.0.1 ,192.168.0.1/24

- string--> www.timinglee.org

exact #精确比较

substring #子串

suffix #后缀比较

prefix #前缀比较

subdir #路径, /wp-includes/js/jquery/jquery.js

domain #域名,www.timinglee.org

- regular expression #正则表达式

- hex block #16进制

acl逻辑处理
与:隐式(默认)使用

或:使用“or" 或 “||"表示

否定:使用 "!" 表示

利用acl做动静分离等访问控制
基于域名的访问

frontend webcluster
    bind *:80
    mode http
    acl domain hdr_dom(host) -i www.jisoo.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

[root@servera ~] curl www.jisoo.org
webserver1 - 172.25.254.10(apache)
[root@servera ~] curl www.jisoo.org/bbs/
172.25.254.10 bbs
[root@servera ~] curl bbs.jisoo.org
webserver2 - 172.25.254.20

自动错误页面内容

创建一个目录为 /etc/haproxy/errorpage/503.http

mkdir -p   /etc/haproxy/errorpage/503.http

然后将/usr/share/haproxy/503.http 中的内容复制在创建的目录中

cp /usr/share/haproxy/503.http   /etc/haproxy/errorpage/503.http

vim /etc/haproxy/errorpage/503.http 编辑内容

vim /etc/haproxy/haproxy.cfg  编辑配置文件

haproxy的四层负载示例

针对除HTTP以外的TCP协议应用服务访问的应用场景,如MySQL,Redis,Memcache,RabbitMQ

1.安装并配置数据库

[root@server1 ~] dnf install mariadb-server -y
[root@server2 ~] dnf install mariadb-server -y
[root@server1 ~] vim /etc/my.cnf.d/mariadb-server.cnf
[mysqld]
server-id=1 #设置serverid,便于区分
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-error=/var/log/mariadb/mariadb.log
pid-file=/run/mariadb/mariadb.pid

[root@server2 ~] 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@server1 ~] mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 10.5.16-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)]> 

[root@server2 ~] mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 10.5.16-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)

[root@haproxy haproxy] yum install mariadb -y 安装mariadb,使用里面的MySQL命令
2.数据库增加远程登录的用户,两台server上都做

MariaDB [(none)]> create user lee@'%' identified by 'lee';
#创建一个用户lee可以在除了本机以外的任何远程客户端登录,建立密码为lee
Query OK, 0 rows affected (0.001 sec)
MariaDB [(none)]> grant all on *.* to lee@'%';
# 将所有库的所有表都给lee
尝试访问

[root@haproxy haproxy]# mysql -ulee -plee -h 172.25.254.10
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 5
Server version: 10.5.16-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)]> 

3.配置haproxy

[root@haproxy 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 haproxy] systemctl restart haproxy.service
4.测试结果

[root@haproxy haproxy] mysql -ulee -plee -h 172.25.254.100
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 6
Server version: 10.5.16-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)]> quit
[root@haproxy haproxy] mysql -ulee -plee -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.16-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的加密访问
1.创建公钥私钥

[root@haproxy haproxy] mkdir /etc/haproxy/certs #创建存放证书和密钥的目录
[root@haproxy haproxy] openssl req -newkey rsa:2048 -nodes -sha256 -keyout /etc/haproxy/certs/timinglee.org.key -x509 -days 356 -out /etc/haproxy/certs/timinglee.org.crt 
#nodes:开启时不需要输密码 -sha256:加密方式  -x509:证书格式 -day 365:证书有效期
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:Shannxi
Locality Name (eg, city) [Default City]:Xi`An
Organization Name (eg, company) [Default Company Ltd]:AAAA
Organizational Unit Name (eg, section) []:webserver
Common Name (eg, your name or your server's hostname) []:www.timinglee.org  
Email Address []:123@aaa.org 
[root@haproxy haproxy] ls /etc/haproxy/certs/
timinglee.org.crt  timinglee.org.key
[root@haproxy haproxy] cat /etc/haproxy/certs/timinglee.org.crt /etc/haproxy/certs/timinglee.org.key > /etc/haproxy/certs/timinglee.pem
[root@haproxy haproxy] ls /etc/haproxy/certs/ #将公钥和私钥全部导入pem中
timinglee.org.crt  timinglee.org.key  timinglee.pem

2.配置haproxy

listen web-https
    bind *:443 ssl crt /etc/haproxy/certs/timinglee.pem #注意一定要与生成从pem文件路径相同
    mode http
    balance roundrobin
    server web1 172.25.254.10:80 check inter 2 fall 2 rise 5
    server web2 172.25.254.20:80 check inter 2 fall 2 rise 5

全站加密

[root@haproxy haproxy]# vim /etc/haproxy/haproxy.cfg
frontend webcluster
    bind *:80
    mode http
    redirect scheme https if !{ ssl_fc } #进行全站加密

haproxy的配置文件还能写在子配置文件中

#将haproxy.cfg中的配置除了global和defaults其余全部注释,恢复最初未配置的环境
[root@haproxy haproxy] vim /lib/systemd/system/haproxy.service #打开haproxy的启动脚本
Environment="CONFIG=/etc/haproxy/haproxy.cfg" "PIDFILE=/run/haproxy.pid" "CFGDIR=/etc/haproxy/conf.d"
#Environment:环境,CONFIG=/etc/haproxy/haproxy.cfg:变量写在/etc/haproxy/haproxy.cfg,CONFIG=/etc/haproxy/haproxy.cfg :子配置文件的目录
[root@haproxy haproxy] cd /etc/haproxy/conf.d/
[root@haproxy conf.d] ll
total 0
[root@haproxy conf.d] vim webcluster.cfg #编写子配置文件
[root@haproxy conf.d]# cat webcluster.cfg 
listen stats
    mode http
    bind *:1234
    stats enable
    stats uri /status
    stats auth lee:lee
[root@haproxy conf.d]# systemctl restart haproxy.service 
Warning: The unit file, source configuration file or drop-ins of haproxy.service changed on disk. Run 'systemctl daemon-reload' to reload units.
#重启后会显示警告,只要打开过启动脚本的文件,都需要执行systemctl daemon-reload

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值