一.负载均衡
1.1.什么是负载均衡 负载均衡:Load Balance,简称LB,是一种服务或基于硬件设备等实现的高可用反向代理技术,负载均衡将特定的业务(web服务、网络流量等)分担给指定的一个或多个后端特定的服务器或设备,从而提高了公司业务的并发处理能力、保证了业务的高可用性、方便了业务后期的水平动态扩展 阿里云SLB介绍 :https://yq.aliyun.com/articles/1803
1.2.为什么用负载均衡 • Web服务器的动态水平扩展–>对用户无感知
• 增加业务并发访问及处理能力–>解决单服务器瓶颈问题
• 节约公网IP地址–>降低IT支出成本
• 隐藏内部服务器IP–>提高内部服务器安全性
• 配置简单–>固定格式的配置文件
• 功能丰富–>支持四层和七层,支持动态下线主机
• 性能较强–>并发数万甚至数十万
1.3.负载均衡类型
1.3.1硬件:
F5 美国F5网络公司 https://f5.com/zh
Netscaler 美国思杰公司 https://www.citrix.com.cn/products/citrix-adc/
Array 华耀 https://www.arraynetworks.com.cn/
AD-1000 深信服 http://www.sangfor.com.cn/
1.3.2.四层负载均衡
1.通过ip+port决定负载均衡的去向。
2.对流量请求进行NAT处理,转发至后台服务器。
3.记录tcp、udp流量分别是由哪台服务器处理,后续该请求连接的流量都通过该服务器处理。
4.支持四层的软件
• lvs:重量级四层负载均衡器。
• Nginx:轻量级四层负载均衡器,可缓存。(nginx四层是通过upstream模块)
• Haproxy:模拟四层转发。
1.3.3.七层负载均衡
1.通过虚拟ur|或主机ip进行流量识别,根据应用层信息进行解析,决定是否需要进行负载均衡。
2.代理后台服务器与客户端建立连接,如nginx可代理前后端,与前端客户端tcp连接,与后端服务器建立tcp连接
3.支持7层代理的软件:
• Nginx:基于http协议(nginx七层是通过proxy_pass)
• Haproxy:七层代理,会话保持、标记、路径转移等。
1.3.4 四层和七层的区别 所谓的四到七层负载均衡,就是在对后台的服务器进行负载均衡时,依据四层的信息或七层的信息来决定怎么样转发流量
四层的负载均衡,就是通过发布三层的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是法国开发者 威利塔罗(Willy Tarreau) 在2000年使用C语言开发的一个开源软件 是一款具备高并发(万级以上)、高性能的TCP和HTTP负载均衡器 支持基于cookie的持久性,自动故障切换,支持正则表达式及web状态统计
企业版网站:https://www.haproxy.com
社区版网站:http://www.haproxy.org
github:https://github.com/haprox
三、HAPORXY实验环境设定

1.haproxy主机
[root@haproxy ~]# vmset.sh eth0 172.25.254.100 haproxy
连接已成功激活(D-Bus 活动路径:/org/freedesktop/NetworkManager/ActiveConnection/7)
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
link/ether 00:0c:29:0c:6f:ee brd ff:ff:ff:ff:ff:ff
altname enp3s0
altname ens160
inet 172.25.254.100/24 brd 172.25.254.255 scope global noprefixroute eth0
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fe0c:6fee/64 scope link tentative noprefixroute
valid_lft forever preferred_lft forever
haproxy
[root@haproxy ~]# vmset.sh eth1 192.168.0.100 haproxy norouter
连接已成功激活(D-Bus 活动路径:/org/freedesktop/NetworkManager/ActiveConnection/8)
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
link/ether 00:0c:29:0c:6f:f8 brd ff:ff:ff:ff:ff:ff
altname enp19s0
altname ens224
inet 192.168.0.100/24 brd 192.168.0.255 scope global noprefixroute eth1
valid_lft forever preferred_lft forever
inet6 fe80::4ca7:8cde:1244:8df/64 scope link tentative noprefixroute
valid_lft forever preferred_lft forever
haproxy
#配置内核路由功能
[root@haproxy ~]# echo net.ipv4.ip_forward=1 > /etc/sysctl.conf
[root@haproxy ~]# sysctl -p
net.ipv4.ip_forward = 1
2.webserver1
[root@webserver1 ~]# vmset.sh eth0 192.168.0.10 webserver1 noroute
连接已成功激活(D-Bus 活动路径:/org/freedesktop/NetworkManager/ActiveConnection/4)
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
link/ether 00:0c:29:8c:96:72 brd ff:ff:ff:ff:ff:ff
altname enp3s0
altname ens160
inet 192.168.0.10/24 brd 192.168.0.255 scope global noprefixroute eth0
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fe8c:9672/64 scope link tentative noprefixroute
valid_lft forever preferred_lft forever
webserver1
[root@webserver1 ~]# dnf install httpd -y
root@webserver1 ~]# echo webserver1 – 192.168.0.10 > /var/www/html/index.html
[root@webserver1 ~]# systemctl enable –now httpd
Created symlink /etc/systemd/system/multi-user.target.wants/httpd.service → /usr/lib/systemd/system/httpd.service.
[root@webserver2 ~]# vmset.sh eth0 192.168.0.20 webserver2 noroute
连接已成功激活(D-Bus 活动路径:/org/freedesktop/NetworkManager/ActiveConnection/4)
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
link/ether 00:0c:29:8c:96:72 brd ff:ff:ff:ff:ff:ff
altname enp3s0
altname ens160
inet 192.168.0.20/24 brd 192.168.0.255 scope global noprefixroute eth0
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fe8c:9672/64 scope link tentative noprefixroute
valid_lft forever preferred_lft forever
webserver2
[root@webserver2 ~]# dnf install httpd -y
[root@webserver2 ~]# echo webserver2 – 192.168.0.20 > /var/www/html/index.html
[root@webserver2 ~]# systemctl enable –now httpd
Created symlink /etc/systemd/system/multi-user.target.wants/httpd.service → /usr/lib/systemd/system/httpd.service.
3.验证环境
#在haproxy中访问

四、Haproxy的安装及配置参数
1.安装
#在调度器(双网卡主机中)
[root@haproxy ~]# dnf install haproxy.x86_64 -y
[root@haproxy ~]# systemctl enable –now haproxy
Created symlink /etc/systemd/system/multi-user.target.wants/haproxy.service → /usr/lib/systemd/system/haproxy.service.
2.harpoxy的参数详解实验
1.实现最基本的负载
#设定vim中tab键的空格个数
[root@haproxy ~]# vim ~/.vimrc
set ts=4 ai
#前后端分开设定
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
frontend webcluster
bind *:80
mode http
use_backend webserver-80
backend webserver-80
server web1 192.168.0.10:80 check inter 3s fall 3 rise 5
server web2 192.168.0.20:80 check inter 3s fall 3 rise 5
[root@haproxy ~]# systemctl restart haproxy.service
#测试:
[root@haproxy ~]# curl 172.25.254.100
webserver2 – 192.168.0.20
[root@haproxy ~]# curl 172.25.254.100
webserver1 – 192.168.0.10

#用listen方式书写负载均衡
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
mode http
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5
[root@haproxy ~]# systemctl restart haproxy.service
#测试
[root@haproxy ~]# curl 172.25.254.100
webserver2 – 192.168.0.20
[root@haproxy ~]# curl 172.25.254.100
webserver1 – 192.168.0.10

2.log 127.0.0.1 local2
指定把日志发送到哪里 实验。指定日志发送到192.168.0.10
#在192.168.0.10 开启接受日志的端口
[root@webserver1 ~]# vim /etc/rsyslog.conf
32 module(load="imudp") # needs to be done just once
33 input(type="imudp" port="514")
[root@webserver1 ~]# systemctl restart rsyslog.service
#测试接受日志端口是否开启
[root@webserver1 ~]# netstat -antlupe | grep rsyslog
udp 0 0 0.0.0.0:514 0.0.0.0:* 0 74140 30965/rsyslogd
udp6 0 0 :::514 :::* 0 74141 30965/rsyslogd
#在haproxy主机中设定日志发送信息
[root@haproxy haproxy]# vim haproxy.cfg
log 192.168.0.10 local2

3.实现haproxy的多进程
#默认haproxy是单进程
[root@haproxy ~]# pstree -p | grep haproxy
|-haproxy(31439)—haproxy(31441)-+-{haproxy}(31442)
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
nbproc 2
[root@haproxy ~]# systemctl restart haproxy.service
#多进程cpu绑定
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
nbproc 2
cpu-map 1 0
cpu-map 2 1
[root@haproxy ~]# systemctl restart haproxy.service
#为不同进程准备不同套接字
[root@haproxy ~]# systemctl stop haproxy.service
[root@haproxy ~]# rm -fr /var/lib/haproxy/stats
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
#stats socket /var/lib/haproxy/stats
stats socket /var/lib/haproxy/haproxy1 mode 600 level admin process 1
stats socket /var/lib/haproxy/haporxy2 mode 660 level admin process 1
[root@haproxy ~]# systemctl restart haproxy.service
#效果
[root@haproxy ~]# ll /var/lib/haproxy/


4.haproxy实现多线程
#查看当前haproxy的进程信息
[root@haproxy ~]# pstree -p | grep haproxy
|-haproxy(31742)-+-haproxy(31744)
| `-haproxy(31745)
#查看haproxy子进程的线程信息
[root@haproxy ~]# cat /proc/31744/status | grep Threads
Threads: 1
#启用多线程
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
#nbproc 2
#cpu-map 1 0
#cpu-map 2 1
nbthread 2
# turn on stats unix socket
stats socket /var/lib/haproxy/stats
#stats socket /var/lib/haproxy/haproxy1 mode 600 level admin process 1
#stats socket /var/lib/haproxy/haporxy2 mode 660 level admin process 1
[root@haproxy ~]# systemctl restart haproxy.service
#效果

5.socat热更新工具
对服务器动态权重和其它状态可以利用 socat工具进行调整,Socat 是 Linux 下的一个多功能的网络工具,名字来由是Socket CAT,相当于netCAT的增强版.Socat 的主要特点就是在两个数据流之间建立双向通道,且支持众多协议和链接方式。如 IP、TCP、 UDP、IPv6、Socket文件等
热更新 在服务或软件不停止的情况下更新软件或服务的工作方式,完成对软件不停工更新,典型的热更新设备,usb,在使用usb进行插拔时,电脑系统时不需要停止工作的,这中设备叫热插拔设备
1.安装socat
[root@haproxy ~]# dnf install socat -y
[root@haproxy ~]# socat -h
2.利用socat查看haproxy信息
[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 haha 192.168.0.10 2 0 1 1 275 6 3 7 6 0 0 0 – 80 – 0 0 – – 0
2 webcluster 2 hehe 192.168.0.20 2 0 1 1 275 6 3 7 6 0 0 0 – 80 – 0 0 – – 0
[root@haproxy ~]# echo "get weight webcluster/haha" | socat stdio /var/lib/haproxy/stats
1 (initial 1)
[root@haproxy ~]# echo "get weight webcluster/hehe" | socat stdio /var/lib/haproxy/stats
1 (initial 1)
3.利用socat更改haproxy信息
#直接更改报错
[root@haproxy ~]# echo "set weight webcluster/haha 2 " | socat stdio /var/lib/haproxy/stats
Permission denied
#对socket进行授权
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
stats socket /var/lib/haproxy/stats mode 600 level admin
[root@haproxy ~]# rm -rf /var/lib/haproxy/*
[root@haproxy ~]# systemctl restart haproxy.service
[root@haproxy ~]# ll /var/lib/haproxy/
总用量 0
srw——- 1 root root 0 1月 25 10:04 stats
#执行权重更改
[root@haproxy ~]# echo "get weight webcluster/hehe" | socat stdio /var/lib/haproxy/stats
1 (initial 1)
[root@haproxy ~]# echo "set weight webcluster/hehe 4 " | socat stdio /var/lib/haproxy/stats
[root@haproxy ~]# echo "get weight webcluster/hehe" | socat stdio /var/lib/haproxy/stats
4 (initial 1)
#测试

6.haproxy的算法
HAProxy通过固定参数 balance 指明对后端服务器的调度算法
balance参数可以配置在listen或backend选项中。
HAProxy的调度算法分为静态和动态调度算法
有些算法可以根据参数在静态和动态算法中相互转换。
(1)静态算法
静态算法:按照事先定义好的规则轮询公平调度,不关心后端服务器的当前负载、连接数和响应速度等,且无法实时修改权重(只能为0和1,不支持其它值),只能靠重启HAProxy生效。
static-rr:基于权重的轮询调度 • 不支持运行时利用socat进行权重的动态调整(只支持0和1,不支持其它值) • 不支持端服务器慢启动 • 其后端主机数量没有限制,相当于LVS中的 wrr
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance static-rr
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 2
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1

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

#检测是否支持热更新
[root@haproxy ~]# echo "get weight webcluster/haha" | socat stdio /var/lib/haproxy/stats
2 (initial 2)
[root@haproxy ~]# echo "set weight webcluster/haha 1 " | socat stdio /var/lib/haproxy/stats Backend is using a static LB algorithm and only accepts weights '0%' and '100%'
first
• 根据服务器在列表中的位置,自上而下进行调度
• 其只会当第一台服务器的连接数达到上限,新请求才会分配给下一台服务
• 其会忽略服务器的权重设置
• 不支持用socat进行动态修改权重,可以设置0和1,可以设置其它值但无效
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance first
server haha 192.168.0.10:80 maxconn 1 check inter 3s fall 3 rise 5 weight 2
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1

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


(2)动态算法
-
基于后端服务器状态进行调度适当调整,
-
新请求将优先调度至当前负载较低的服务器
-
权重可以在haproxy运行时动态调整无需重启
roundrobin
1. 基于权重的轮询动态调度算法,
2. 支持权重的运行时调整,不同于lvs中的rr轮训模式,
3. HAProxy中的roundrobin支持慢启动(新加的服务器会逐渐增加转发数),
4. 其每个后端backend中最多支持4095个real server,
5. 支持对real server权重动态调整,
6. roundrobin为默认调度算法,此算法使用广泛
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance roundrobin
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 2
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1
[root@haproxy ~]# systemctl restart haproxy.service
#测试
[Administrator.DESKTOP-VJ307M3] ➤ for i in {1..10}; do curl 172.25.254.100; done

#动态权重更新
[root@haproxy ~]# echo "get weight webcluster/haha" | socat stdio /var/lib/haproxy/stats
2 (initial 2)
[root@haproxy ~]# echo "set weight webcluster/haha 1 " | socat stdio /var/lib/haproxy/stats
[root@haproxy ~]# echo "get weight webcluster/haha" | socat stdio /var/lib/haproxy/stats
1 (initial 2)
#效果
[Administrator.DESKTOP-VJ307M3] ➤ for i in {1..10}; do curl 172.25.254.100; done

leastconn
leastconn加权的最少连接的动态
支持权重的运行时调整和慢启动,即:根据当前连接最少的后端服务器而非权重进行优先调度(新客户端连接)
比较适合长连接的场景使用,比如:MySQL等场景。
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance leastconn
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 2
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1
[root@haproxy ~]# systemctl restart haproxy.service

(3)混合算法
source
源地址hash,基于用户源地址hash并将请求转发到后端服务器,后续同一个源地址请求将被转发至同一个后端web服务器。此方式当后端服务器数据量发生变化时,会导致很多用户的请求转发至新的后端服务器,默认为静态方式,但是可以通过hash-type支持的选项更改这个算法一般是在不插入Cookie的TCP模式下使用,也可给拒绝会话cookie的客户提供最好的会话粘性,适用于session会话保持但不支持cookie和缓存的场景源地址有两种转发客户端请求到后端服务器的服务器选取计算方式,分别是取模法和一致性hash
#默认静态算法
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance source
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 2
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1
[root@haproxy ~]# systemctl restart haproxy.service
#source动态算法
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance source
hash-type consistent
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 2
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1
[root@haproxy ~]# systemctl restart haproxy.service

uri
基于对用户请求的URI的左半部分或整个uri做hash,再将hash结果对总权重进行取模后 根据最终结果将请求转发到后端指定服务器 适用于后端是缓存服务器场景 默认是静态算法,也可以通过hash-type指定map-based和consistent,来定义使用取模法还是一致性hash
#主备实验环境
[root@webserver1 ~]# echo RS1 – 192.168.0.10 > /var/www/html/index1.html
[root@webserver1 ~]# echo RS1 – 192.168.0.10 > /var/www/html/index2.html
[root@webserver2 ~]# echo RS2 – 192.168.0.20 > /var/www/html/index1.html
[root@webserver2 ~]# echo RS2 – 192.168.0.20 > /var/www/html/index2.html
#设定uri算法
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance uri
hash-type consistent
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 2
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1
[root@haproxy ~]# systemctl restart haproxy.service

url_param
url_param对用户请求的url中的 params 部分中的一个参数key对应的value值作hash计算,并由服务器总权重相除以后派发至某挑出的服务器,后端搜索同一个数据会被调度到同一个服务器,多用与电商 通常用于追踪用户,以确保来自同一个用户的请求始终发往同一个real server 如果无没key,将按roundrobin算法
#主备实验环境
[root@webserver1 ~]# echo RS1 – 192.168.0.10 > /var/www/html/index1.html
[root@webserver1 ~]# echo RS1 – 192.168.0.10 > /var/www/html/index2.html
[root@webserver2 ~]# echo RS2 – 192.168.0.20 > /var/www/html/index1.html
[root@webserver2 ~]# echo RS2 – 192.168.0.20 > /var/www/html/index2.html
#设定url_param算法
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance url_param name
hash-type consistent
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 2
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1
[root@haproxy ~]# systemctl restart haproxy.service

hdr
针对用户每个http头部(header)请求中的指定信息做hash, 此处由 name 指定的http首部将会被取出并做hash计算, 然后由服务器总权重取模以后派发至某挑出的服务器,如果无有效值,则会使用默认的轮询调度。
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance hdr(User-Agent)
hash-type consistent
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 2
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1
[root@haproxy ~]# systemctl restart haproxy.service

(4)基于cookie的会话保持
cookie value:为当前server指定cookie值,实现基于cookie的会话黏性,相对于基于 source 地址hash 调度算法对客户端的粒度更精准,但同时也加大了haproxy负载,目前此模式使用较少, 已经被session共享服务器代替
如果在haprorxy中设定算法为source,在同一台客户端主机中,无论使用什么浏览器访问的最终服务器是同一个 可以使用cookie值进行优化,让同一台客户端中同一个浏览器中访问的是同一个服务器 不同浏览器访问的是不同的服务器
配置选项
cookie name [ rewrite | insert | prefix ][ indirect ] [ nocache ][ postonly ] [ preserve ][ httponly ] [ secure ][ domain ]* [ maxidle <idle> ][ maxlife ]
name: #cookie 的 key名称,用于实现持久连接
insert: #插入新的cookie,默认不插入cookie
indirect: #如果客户端已经有cookie,则不会再发送cookie信息
nocache: #当client和hapoxy之间有缓存服务器(如:CDN)时,不允许中间缓存器缓存cookie,
#因为这会导致很多经过同一个CDN的请求都发送到同一台后端服务器
#配合基于cookie的会话保持方法
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance roundrobin
hash-type consistent
cookie WEBCOOKIE insert nocache indirect
server haha 192.168.0.10:80 cookie web1 check inter 3s fall 3 rise 5 weight 2
server hehe 192.168.0.20:80 cookie web2 check inter 3s fall 3 rise 5 weight 1
[root@haproxy ~]# systemctl restart haproxy.service


(5)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> #认证时的账号和密码,可定义多个用户,每行指定一个用户
#默认:no authentication
stats admin { if | unless } <cond> #启用stats page中的管理功能
启用状态页
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen stats
mode http
bind 0.0.0.0:4321
stats enable
log global
# stats refresh
stats uri /status #自定义stats page uri
stats auth lee:lee #认证,此行可以出现多次
[root@haproxy ~]# systemctl restart haproxy.service
登录测试

登录状态页
#pid为当前pid号,process为当前进程号,nbproc和nbthread为一共多少进程和每个进程多少个线程
pid = 27134 (process #1, nbproc = 1, nbthread = 1)
#启动了多长时间
uptime = 0d 0h00m04s
#系统资源限制:内存/最大打开文件数/
system limits: memmax = unlimited; ulimit-n = 200029
#最大socket连接数/单进程最大连接数/最大管道数maxpipes
maxsock = 200029; maxconn = 100000; maxpipes = 0
#当前连接数/当前管道数/当前连接速率
current conns = 2; current pipes = 0/0; conn rate = 2/sec; bit rate = 0.000 kbps
#运行的任务/当前空闲率
Running tasks: 1/14; idle = 100 %
active UP: #在线服务器
backup UP: #标记为backup的服务器
active UP, going down: #监测未通过正在进入down过程
backup UP, going down: #备份服务器正在进入down过程
active DOWN, going up: #down的服务器正在进入up过程
backup DOWN, going up: #备份服务器正在进入up过程
active or backup DOWN: #在线的服务器或者是backup的服务器已经转换成了down状态
not checked: #标记为不监测的服务器
#active或者backup服务器人为下线的
active or backup DOWN for maintenance (MAINT)
#active或者backup被人为软下线(人为将weight改成0)
active or backup SOFT STOPPED for maintenance
backend server信息
session rate(每秒的连接会话信息): Errors(错误统计信息):
cur:每秒的当前会话数量 : Req:错误请求量
max:每秒新的最大会话数量 conn:错误链接量
limit:每秒新的会话限制量 Resp:错误响应量
sessions(会话信息): Warnings(警告统计信息):
cur:当前会话量 Retr:重新尝试次数
max:最大会话量 Redis:再次发送次数
limit: 限制会话量
Total:总共会话量 Server(real server信息):
LBTot:选中一台服务器所用的总时间 Status:后端机的状态,包括UP和DOWN
Last:和服务器的持续连接时间 LastChk:持续检查后端服务器的时间
Wght:权重
Bytes(流量统计): Act:活动链接数量
In:网络的字节输入总量 Bck:备份的服务器数量
Out:网络的字节输出总量 Chk:心跳检测时间
Dwn:后端服务器连接后都是DOWN的数量
Denied(拒绝统计信息): Dwntme:总的downtime时间
Req:拒绝请求量 Thrtle:server 状态
Resp:拒绝回复量
开启自动刷新


(6)IP透传
web服务器中需要记录客户端的真实IP地址,用于做访问统计、安全防护、行为分析、区域排行等场景。
七层IP透传
当haproxy工作在七层的时候,也可以透传客户端真实IP至后端服务器
在由haproxy发往后端主机的请求报文中添加“X-Forwarded-For"首部,其值为前端客户端的地址;用于向后端主发送真实的客户端IP
#实验环境
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
balance roundrobin
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 1
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1
[root@haproxy ~]# systemctl restart haproxy.service
#测试环境
[Administrator.DESKTOP-VJ307M3] ➤ for i in {1..5}
> do
> curl 172.25.254.100
> done
webserver1 – 192.168.0.10
webserver2 – 192.168.0.20
webserver1 – 192.168.0.10
webserver2 – 192.168.0.20
webserver1 – 192.168.0.10
#在rs主机中默认是未开启透传功能的
![]()
#开启ip透传的方式
[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 #开启haproxy透传功能
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
#在rs中设定采集透传IP
[root@webserver2 ~]# vim /etc/httpd/conf/httpd.conf
201 LogFormat "%h %l %u %t \\"%r\\" %>s %b \\"%{X-Forwarded-For}i\\" \\"%{Referer}i\\" \\"%{User-Agent}i \\"" combined
[root@webserver2 ~]# systemctl restart httpd

四层IP透传
#环境设置
#在RS中把apache停止
[root@webserver1 ~]# systemctl disable –now httpd
[root@webserver2 ~]# systemctl disable –now httpd
#部署nginx
[root@webserver1 ~]# dnf install nginx -y
[root@webserver2 ~]# dnf install nginx -y
[root@webserver1 ~]# echo RS1 – 192.168.0.10 > /usr/share/nginx/html/index.html
[root@webserver2 ~]# echo RS2 – 192.168.0.20 > /usr/share/nginx/html/index.html
[root@webserver1 ~]# systemctl enable –now nginx
[root@webserver2 ~]# systemctl enable –now nginx
#测环境
[Administrator.DESKTOP-VJ307M3] ➤ for i in {1..5}; do curl 172.25.254.100; done
RS1 – 192.168.0.10
RS2 – 192.168.0.20
RS1 – 192.168.0.10
RS2 – 192.168.0.20
RS1 – 192.168.0.10
#启用nginx的四层访问控制
[root@webserver1 ~]# vim /etc/nginx/nginx.conf
server {
listen 80 proxy_protocol; #启用四层访问控制
listen [::]:80;
server_name _;
root /usr/share/nginx/html;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
error_page 404 /404.html;
location = /404.html {
}
[root@webserver2 ~]# vim /etc/nginx/nginx.conf
server {
listen 80 proxy_protocol; #启用四层访问控制
listen [::]:80;
server_name _;
root /usr/share/nginx/html;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
error_page 404 /404.html;
location = /404.html {
}
[root@webserver1 ~]# systemctl restart nginx.service
[root@webserver2 ~]# systemctl restart nginx.service
#测试
Administrator.DESKTOP-VJ307M3] ➤ for i in {1..5}; do curl 172.25.254.100; done
<html><body><h1>502 Bad Gateway</h1>
The server returned an invalid or incomplete response.
</body></html>
出现上述报错标识nginx只支持四层访问
#设定haproxy访问4层
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
mode tcp #四层访问
balance roundrobin
server haha 192.168.0.10:80 send-proxy check inter 3s fall 3 rise 5 weight 1
server hehe 192.168.0.20:80 send-proxy check inter 3s fall 3 rise 5 weight 1
[root@haproxy ~]# systemctl restart haproxy.service
#测试四层访问
[Administrator.DESKTOP-VJ307M3] ➤ for i in {1..5}; do curl 172.25.254.100; done
RS1 – 192.168.0.10
RS2 – 192.168.0.20
RS1 – 192.168.0.10
RS2 – 192.168.0.20
RS1 – 192.168.0.10
#设置4层ip透传
[root@webserver1&2 ~]# vim /etc/nginx/nginx.conf
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"';
[root@webserver1&2 ~]# systemctl restart nginx.service
#测试
[Administrator.DESKTOP-VJ307M3] ➤ for i in {1..5}; do curl 172.25.254.100; done
RS2 – 192.168.0.20
RS1 – 192.168.0.10
RS2 – 192.168.0.20
RS1 – 192.168.0.10
RS2 – 192.168.0.20

(7)四层负载
针对除HTTP以外的TCP协议应用服务访问的应用场景
MySQL
Redis
Memcache
RabbitMQ
1.环境设定
#部署mariadb数据库
[root@webserver1+2 ~]# dnf install mariadb-server mariadb -y
[root@webserver1+1 ~]# vim /etc/my.cnf.d/mariadb-server.cnf
[mysqld]
server_id=10 #设定数据库所在主机的id标识,在20上设定id为20
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 ~]# mysql -ulee -plee -h 192.168.0.20 #测试10时修改ip即可

2.四层负载操作
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen mariadbcluster
bind *:6663
mode tcp
balance roundrobin
server haha 192.168.0.10:3306 check inter 3s fall 3 rise 5 weight 1
server hehe 192.168.0.20:3306 check inter 3s fall 3 rise 5 weight 1
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
#检测端口
[root@haproxy ~]# netstat -antlupe | grep haproxy
tcp 0 0 0.0.0.0:6663 0.0.0.0:* LISTEN 0 44430 2136/haproxy
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 0 44429 2136/haproxy
tcp 0 0 0.0.0.0:4321 0.0.0.0:* LISTEN 0 44431 2136/haproxy
backup参数
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen mariadbcluster
bind *:6663
mode tcp
balance roundrobin
server haha 192.168.0.10:3306 check inter 3s fall 3 rise 5 weight 1
server hehe 192.168.0.20:3306 check inter 3s fall 3 rise 5 weight 1 backup
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
#测试
[Administrator.DESKTOP-VJ307M3] ➤ mysql -ulee -plee -h172.25.254.100 -P 6663
Welcome to the MariaDB monitor. Commands end with ; or \\g.
Your MariaDB connection id is 4
Server version: 10.5.27-MariaDB MariaDB Server
Copyright (c) 2000, 2017, 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 |
+————-+
| 10 |
+————-+
1 row in set (0.00 sec)
MariaDB [(none)]> quit
Bye
[Administrator.DESKTOP-VJ307M3] ➤ mysql -ulee -plee -h172.25.254.100 -P 6663
Welcome to the MariaDB monitor. Commands end with ; or \\g.
Your MariaDB connection id is 4
Server version: 10.5.27-MariaDB MariaDB Server
Copyright (c) 2000, 2017, 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 |
+————-+
| 10 |
+————-+
1 row in set (0.00 sec)
MariaDB [(none)]> quit
Bye
#关闭10的mariadb并等待1分钟
[root@webserver1 ~]# systemctl stop mariadb
[Administrator.DESKTOP-VJ307M3] ➤ mysql -ulee -plee -h172.25.254.100 -P 6663
ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 1 "Operation not permitted" #标识haproxy 没有完成故障转换,需要等待
[Administrator.DESKTOP-VJ307M3] ➤ mysql -ulee -plee -h172.25.254.100 -P 6663
Welcome to the MariaDB monitor. Commands end with ; or \\g.
Your MariaDB connection id is 11
Server version: 10.5.27-MariaDB MariaDB Server
Copyright (c) 2000, 2017, 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 |
+————-+
| 20 |
+————-+
1 row in set (0.00 sec)
MariaDB [(none)]>
#还原故障主机等待片刻
[root@webserver1 ~]# systemctl start mariadb
[Administrator.DESKTOP-VJ307M3] ➤ mysql -ulee -plee -h172.25.254.100 -P 6663
Welcome to the MariaDB monitor. Commands end with ; or \\g.
Your MariaDB connection id is 4
Server version: 10.5.27-MariaDB MariaDB Server
Copyright (c) 2000, 2017, 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 |
+————-+
| 10 |
+————-+
1 row in set (0.00 sec)
MariaDB [(none)]>
#测试:
[Administrator.DESKTOP-VJ307M3] ➤ mysql -ulee -plee -h172.25.254.100 -P 6663

(8)自定义haproxy错误界面
对指定的报错进行重定向,进行优雅的显示错误页面 使用errorfile和errorloc指令的两种方法,可以实现自定义各种错误页面
1.sorryserver的设定
正常的所有服务器如果出现宕机,那么客户将被定向到指定的主机中,这个当业务主机出问题时被临时访问的主机叫做sorryserver
#在新主机中安装apache(可以用haproxy主机代替)
[root@haproxy ~]# dnf install httpd -y
[root@haproxy ~]# vim /etc/httpd/conf/httpd.conf
47 Listen 8080
[root@haproxy ~]# systemctl enable –now httpd
Created symlink /etc/systemd/system/multi-user.target.wants/httpd.service → /usr/lib/systemd/system/httpd.service.
[root@haproxy ~]# echo "李哥在,没意外" > /var/www/html/index.html
#配置sorryserver上线、
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
listen webcluster
bind *:80
mode tcp
balance roundrobin
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 1
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1
server wuwu 192.168.0.100:8080 backup #sorryserver
[root@haproxy ~]# systemctl restart haproxy.service


#关闭两台正常的业务主机
[root@webserver1+2 ~]# systemctl stop httpd

2.自定义错误页面
当所有主机包括sorryserver都宕机了,那么haproxy会提供一个默认访问的错误页面,这个错误页面跟报错代码有关,这个页面可以通过定义来机型设置
#出现的错误页面
[root@webserver1+2 ~]# systemctl stop httpd
[root@haproxy ~]# systemctl stop httpd
#所有后端web服务都宕机

[root@haproxy ~]# mkdir /errorpage/html/ -p
[root@haproxy ~]# vim /errorpage/html/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 /errorpage/html/503.http #error 页面
[root@haproxy ~]# systemctl restart haproxy.service

3.从定向错误到指定网站
[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
errorloc 503 http://www.baidu.com #error 页面
[root@haproxy ~]# systemctl restart haproxy.service
#在浏览器中访问

(9)ACL访问控制
访问控制列表(ACL,Access Control Lists) 是一种基于包过滤的访问控制技术 它可以根据设定的条件对经过服务器传输的数据包进行过滤(条件匹配)即对接收到的报文进行匹配和过滤,基于请求报文头部中的源地址、源端口、目标地址、目标端口、请求方法、URL、文件后缀等信息内容进行匹配并执行进一步操作,比如允许其通过或丢弃。
ACL配置选项
#用acl来定义或声明一个acl
acl <aclname> <criterion> [flags] [operator] [<value>]
acl 名称 匹配规范 匹配模式 具体操作符 操作对象类型
ACL-Name 名称
acl test path_end -m sub /a
#ACL名称,可以使用大字母A-Z、小写字母a-z、数字0-9、冒号:、点.、中横线和下划线,并且严格区分大小写,比如:my_acl和My_Acl就是两个完全不同的acl5.8.1.2 ACL-criterion
ACL-criterion 匹配规范
定义ACL匹配规范,即:判断条件
hdr string,提取在一个HTTP请求报文的首部
hdr([<name> [,<occ>]]):完全匹配字符串,header的指定信息,<occ> 表示在多值中使用的值的出现次数
hdr_beg([<name> [,<occ>]]):前缀匹配,header中指定匹配内容的begin
hdr_end([<name> [,<occ>]]):后缀匹配,header中指定匹配内容end
hdr_dom([<name> [,<occ>]]):域匹配,header中的dom(host)
hdr_dir([<name> [,<occ>]]):路径匹配,header的uri路径
hdr_len([<name> [,<occ>]]):长度匹配,header的长度匹配
hdr_reg([<name> [,<occ>]]):正则表达式匹配,自定义表达式(regex)模糊匹配
hdr_sub([<name> [,<occ>]]):子串匹配,header中的uri模糊匹配 模糊匹配c 报文中a/b/c也会匹配
#示例:
hdr(<string>) 用于测试请求头部首部指定内容
hdr_dom(host) 请求的host名称,如 www.timinglee.org
hdr_beg(host) 请求的host开头,如 www. img. video. download. ftp.
hdr_end(host) 请求的host结尾,如 .com .net .cn
#示例:
acl bad_agent hdr_sub(User-Agent) -i curl wget
http-request deny if bad_agent
#有些功能是类似的,比如以下几个都是匹配用户请求报文中host的开头是不是www
acl short_form hdr_beg(host) www.
acl alternate1 hdr_beg(host) -m beg www.
acl alternate2 hdr_dom(host) -m beg www.
acl alternate3 hdr(host) -m beg www.
base : string
#返回第一个主机头和请求的路径部分的连接,该请求从主机名开始,并在问号之前结束,对虚拟主机有用
<scheme>://<user>:<password>@#<host>:<port>/<path>;<params>#?<query>#<frag>
base : exact string match
base_beg : prefix match
base_dir : subdir match
base_dom : domain match
base_end : suffix match
base_len : length match
base_reg : regex match
base_sub : substring match
path : string
#提取请求的URL路径,该路径从第一个斜杠开始,并在问号之前结束(无主机部分)
<scheme>://<user>:<password>@<host>:<port>#/<path>;<params>#?<query>#<frag>
path : exact string match
path_beg : prefix match #请求的URL开头,如/static、/images、/img、/css
path_end : suffix match #请求的URL中资源的结尾,如 .gif .png .css .js .jpg .jpeg
path_dom : domain match
path_dir : subdir match
path_len : length match
path_reg : regex match
path_sub : substring match
#示例:
path_beg -i /haproxy-status/
path_end .jpg .jpeg .png .gif
path_reg ^/images.*\\.jpeg$
path_sub image
path_dir jpegs
path_dom timinglee
url : string
#提取请求中的整个URL。
url :exact string match
url_beg : prefix match
url_dir : subdir match
url_dom : domain match
url_end : suffix match
url_len : length match
url_reg : regex match
url_sub : substring match
dst #目标IP
dst_port #目标PORT
src #源IP
src_port #源PORT
#示例:
acl invalid_src src 10.0.0.7 192.168.1.0/24
acl invalid_src src 172.16.0.0/24
acl invalid_port src_port 0:1023
status : integer #返回在响应报文中的状态码
#七层协议
acl valid_method method GET HEAD
http-request deny if ! valid_method
ACL-flags 匹配模式
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进行匹配
value的类型
The ACL engine can match these types against patterns of the following types :
– Boolean #布尔值
– integer or integer range #整数或整数范围,比如用于匹配端口范围
– IP address / network #IP地址或IP范围, 192.168.0.1 ,192.168.0.1/24
– string–> www.timinglee.org
exact #精确比较
substring #子串
suffix #后缀比较
prefix #前缀比较
subdir #路径, /wp-includes/js/jquery/jquery.js
domain #域名,www.timinglee.org
– regular expression #正则表达式
– hex block #16进制
1.实验素材
#在浏览器或者curl主机中设定本地解析
在windows中设定解析


测试
ping bbs.timinglee.org
2.设定基础的haproxy实验配置
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
frontend webcluster
bind *:80
mode http
use_backend webserver-80-web1
backend webserver-80-web1
server web1 192.168.0.10:80 check inter 3s fall 3 rise 5
backend webserver-80-web2
server web2 192.168.0.20:80 check inter 3s fall 3 rise 5
[root@haproxy ~]# systemctl restart haproxy.service
3.基础acl示例
#在访问的网址中,所有以.com 结尾的访问10,其他访问20
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
frontend webcluster
bind *:80
mode http
acl test hdr_end(host) -i .com #acl列表
use_backend webserver-80-web1 if test #acl列表访问匹配
default_backend webserver-80-web2 #acl列表访问不匹配
backend webserver-80-web1
server web1 192.168.0.10:80 check inter 3s fall 3 rise 5
backend webserver-80-web2
server web2 192.168.0.20:80 check inter 3s fall 3 rise 5


#基于访问头部
acl head hdr_beg(host) -i bbs.
use_backend webserver-80-web1 if head
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
frontend webcluster
bind *:80
mode http
acl test hdr_end(host) -i .com #acl列表
acl head hdr_beg(host) -i bbs.
use_backend webserver-80-web1 if head
default_backend webserver-80-web2
backend webserver-80-web1
server web1 192.168.0.10:80 check inter 3s fall 3 rise 5
backend webserver-80-web2
server web2 192.168.0.20:80 check inter 3s fall 3 rise 5
#base参数acl
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
frontend webcluster
bind *:80
mode http
acl pathdir base_dir -i /lee
use_backend webserver-80-web1 if pathdir
default_backend webserver-80-web2 #acl列表访问不匹配
backend webserver-80-web1
server web1 192.168.0.10:80 check inter 3s fall 3 rise 5
backend webserver-80-web2
server web2 192.168.0.20:80 check inter 3s fall 3 rise 5
[root@webserver1+2 ~]# mkdir -p /var/www/html/lee/
[root@webserver1+2 ~]# mkdir -p /var/www/html/lee/test/
[root@webserver1 ~]# echo lee – 192.168.0.10 > /var/www/html/lee/index.html
[root@webserver1 ~]# echo lee/test – 192.168.0.10 > /var/www/html/lee/test/index.html
[root@webserver2 ~]# echo lee – 192.168.0.20 > /var/www/html/lee/index.html
[root@webserver2 ~]# echo lee/test – 192.168.0.10 > /var/www/html/lee/test/index.html
#测试



#acl禁止列表黑名单
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
frontend webcluster
bind *:80
mode http
acl test hdr_end(host) -i .com #acl列表
use_backend webserver-80-web1 if test #acl列表访问匹配
default_backend webserver-80-web2 #acl列表访问不匹配
acl invalid_src src 172.25.254.1
http-request deny if invalid_src
backend webserver-80-web1
server web1 192.168.0.10:80 check inter 3s fall 3 rise 5
backend webserver-80-web2
server web2 192.168.0.20:80 check inter 3s fall 3 rise 5
#测试:

#禁止列表白名单
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
frontend webcluster
bind *:80
mode http
acl test hdr_end(host) -i .com #acl列表
use_backend webserver-80-web1 if test #acl列表访问匹配
default_backend webserver-80-web2 #acl列表访问不匹配
acl invalid_src src 172.25.254.1
http-request deny if ! invalid_src
backend webserver-80-web1
server web1 192.168.0.10:80 check inter 3s fall 3 rise 5
backend webserver-80-web2
server web2 192.168.0.20:80 check inter 3s fall 3 rise 5
#测试:


(10)Haproxy全站加密
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.制作证书
[root@haproxy ~]# mkdir /etc/haproxy/certs/
[root@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

[root@haproxy ~]# ls /etc/haproxy/certs/
timinglee.org.crt timinglee.org.key
[root@haproxy ~]# cat /etc/haproxy/certs/timinglee.org.{key,crt} > /etc/haproxy/certs/timinglee.pem
2.全站加密
[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
frontend webcluster-http
bind *:80
redirect scheme https if ! { ssl_fc }
listen webcluster-https
bind *:443 ssl crt /etc/haproxy/certs/timinglee.pem
mode http
balance roundrobin
server haha 192.168.0.10:80 check inter 3s fall 3 rise 5 weight 1
server hehe 192.168.0.20:80 check inter 3s fall 3 rise 5 weight 1
[root@haproxy ~]# systemctl restart haproxy.service
#测试:curl -v -k -L http://172.25.254.100


网硕互联帮助中心



评论前必须登录!
注册