haproxy知识点整理

haproxy七层代理

负载均衡

什么是负载均衡

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

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

负载均衡类型

四层负载均衡

在这里插入图片描述

  1. 通过ip+port决定负载均衡的去向
  2. 对流量请求进行NAT处理,转发至后台服务器
  3. 记录tcp,udp流量分别是由哪台服务器处理,后续该请求连接的流量都通过该服务器处理
  4. 支持四层的软件:
    • lvs:重量级四层负载均衡器
    • Nginx:轻量级四层负载均衡器,可缓存,(Nginx四层是通过upstream模块)
    • Haproxy:模拟四层转发
七层负载均衡

在这里插入图片描述

  1. 通过虚拟url或主机ip进行流量识别,根据应用层信息进行解析,决定是否需要进行负载均衡
  2. 代理后台服务器与客户端建立连接,如nginx可代理前后端,与前端客户端tcp连接,与后端服务器建立tcp连接
  3. 支持七层代理软件:
    • Nginx:属于http协议(nginx七层是通过proxy_pass)
    • Haproxy:七层代理,会话保持,标记,路径转移等
四层和七层的区别

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

四层的负载均衡,就是通过发布三层的IP地址(VIP),然后加四层的端口号,来决定哪些流量需要做负 载均衡,对需要处理的流量进行NAT处理,转发至后台服务器,并记录下这个TCP或者UDP的流量是由哪 台服务器处理的,后续这个连接的所有流量都同样转发到同一台服务器处理

七层的负载均衡,就是在四层的基础上(没有四层是绝对不可能有七层的),再考虑应用层的特征,比 如同一个Web服务器的负载均衡,除了根据VIP加80端口辨别是否需要处理的流量,还可根据七层的 URL、浏览器类别、语言来决定是否要进行负载均衡。

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

环境搭建:

客户端(client)

随便创一台虚拟机就行,注意ip地址不能和其他实验机器重合

haproxy服务器

eth0: NAT模式 ip:172.25.254.100

安装haproxy

[root@haproxy ~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:30:39:d6 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::1754:9db0:e78b:69a1/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
[root@haproxy ~]# 
[root@haproxy ~]# dnf install haproxy -y
#启动haproxy服务并开机自启
两台服务器
hapserver1

eth0: NAT模式 ip:172.25.254.10

安装nginx

[root@hapserver1 ~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:2e:15:aa brd ff:ff:ff:ff:ff:ff
    altname enp3s0
    altname ens160
    inet 172.25.254.10/24 brd 172.25.254.255 scope global noprefixroute eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::34d7:b06d:8e72:697b/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
[root@hapserver1 ~]# dnf install nginx -y
#编写nginx的http服务配置文件
[root@hapserver1 ~]# echo webserver1 - 172.25.254.10 > /usr/share/nginx/html/index.html
#启动nginx服务并开机自启
[root@hapserver1 ~]# systemctl enable --now nginx
#关闭防火墙和SELinux
[root@hapserver1 ~]# systemctl stop firewalld.service 
[root@hapserver1 ~]# setenforce 0
hapserver2

eth0: NAT模式 ip:172.25.254.20

安装nginx

[root@hapserver2 ~]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:f6:87:0a brd ff:ff:ff:ff:ff:ff
    altname enp3s0
    altname ens160
    inet 172.25.254.20/24 brd 172.25.254.255 scope global noprefixroute eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::33e:4b1b:d2be:4a45/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
[root@hapserver2 ~]# dnf install nginx -y
#编写nginx的http服务配置文件
[root@hapserver2 ~]# echo webserver2 - 172.25.254.20 > /usr/share/nginx/html/index.html
#启动nginx服务并开机自启
[root@hapserver2 ~]# systemctl enable --now nginx
#关闭防火墙和SELinux
[root@hapserver2 ~]# systemctl stop firewalld.service 
[root@hapserver2 ~]# setenforce 0

测试:

[root@client ~]# curl 172.25.254.10
webserver1 - 172.25.254.10
[root@client ~]# curl 172.25.254.20
webserver2 - 172.25.254.20
[root@client ~]# 
简单的haproxy负载均衡
......
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
......

测试:

[root@client ~]# curl 172.25.254.100
webserver1 - 172.25.254.10
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# curl 172.25.254.100
webserver1 - 172.25.254.10
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# curl 172.25.254.100
webserver1 - 172.25.254.10
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# curl 172.25.254.100
webserver1 - 172.25.254.10
#前后端合并后的测试
[root@client ~]# for i in {1..10}; do curl 172.25.254.100; done
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
[root@client ~]# 

测试后端检测:

在webserver1关闭nginx服务之后从客户端进入的流量又proxy自动分配到了webserver2

[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# 

haproxy的基本配置信息

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

global:

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

proxies:代理配置段

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

global配置参数说明

参数类型作用
chroot全局锁定运行目录
deamon全局以守护进程运行
user,group,uid,gid全局运行haproxy的用户身份
stats,socket全局套接字文件
nbproc N全局开启的haproxy worker 进程数,默认进程数是一个
nbthread 1(和nvproc互斥)全局指定每个haproxy进程开启的线程数,默认为每个进程一个线程
cpu-map1 0全局绑定haproxy worker进程至指定的cpu,将第一个work进程绑定到0号cpu
cpu-map 2 1全局绑定haproxt worker进程至指定的cpu,将第二个worker进程绑定到1号cpu
maxconn N全局每个haproxy进程的最大并发连接数
maxsslconn N全局每个haproxy进程ssl最大连接数,用于haproxy配置了证书的场景下
maxconnrate N全局每个进程每秒创建的最大连接数量
spread-checks N全局后端server状态check随机提前或延迟百分比时间,建议2-5(20%-50%)之间,默认值为0
pidfile全局指定pid文件路径
log 127.0.0.1 local2 info全局定义全局的syslog服务器,日志服务器需要开启UDP协议,最多可以定义两个
proxies配置
proxies参数说明proxies
参数类型作用
defaults[]proxies默认配置,针对以下的frontend,backend和insten生效,可以多个name也可以没有name
frontendproxies前端servername,类似Nginx的一个虚拟主机,server和LVS服务集群
backendproxies#后端服务器组,等于nginx的upstream和LVS中的LVS服务器
listenproxies将frontend和backend合并在一起配置,相当于frontend和backend配置更简洁,生产使用
proxies配置defaults
defaults
    mode                    http					#HAProxy实例使用的连接协议
    log                     global					#指定日志地址和记录日志条目的syslog/rsyslog日志设备
    												#此处的global表示使用global配置段中设定的log值
    option                  httplog					#日志记录选项,httplog表示记录与 HTTP会话相关的各种属性值
    												#包括 HTTP请求、会话状态、连接数、源地址以及连接时间等
    option                  dontlognull				#dontlognull表示不记录空会话连接日志
    option http-server-close						#等待客户端完整HTTP请求的时间,此处为等
    option forwardfor       except 127.0.0.0/8		#透传客户端真实IP至后端web服务器
    												#在apache配置文件中加入:<br>%{X-Forwarded-For}i
													#后在webserer中看日志即可看到地址透传信息
    option                  redispatch				#当server Id对应的服务器挂掉后,强制定向到其他健康的服务器,重新派发
    retries                 3						#连接后端服务器失败次数
    timeout http-request    10s						#等待客户端请求完全被接收和处理的最长时间

    timeout queue           1m						#设置删除连接和客户端收到503或服务不可用等提示信息前的等待时间
    timeout connect         10s						#设置等待服务器连接成功的时间
    timeout client          1m						#设置允许客户端处于非活动状态,即既不发送数据也不接收数据的时间
    timeout server          1m						#设置服务器超时时间,即允许服务器处于既不接收也不发送数据的非活动时间
    timeout http-keep-alive 10s						#session 会话保持超时时间,此时间段内会转发到相同的后端服务器
    timeout check           10s						#指定后端服务器健康检查的超时时间
    maxconn                 3000
proxies配置frontend
bind:指定HAProxy的监听地址,可以是IPV4或IPV6,可以同时监听多个IP或端口,可同时用于listen字段中
#格式:
bind [<address>]:<port_range> [, ...] [param*]
#注意:如果需要绑定在非本机的IP,需要开启内核参数:net.ipv4.ip_nonlocal_bind=1
backlog <backlog> #针对所有server配置,当前端服务器的连接数达到上限后的后援队列长度,注意:不支持backend
proxies配置backend
  • 定义一组后端服务器,backend服务器将被frontend进行调用。
  • 注意: backend 的名称必须唯一,并且必须在listen或frontend中事先定义才可以使用,否则服务无法 启动
mode http|tcp 		#指定负载协议类型,和对应的frontend必须一致
option 				#配置选项
server 				#定义后端real server,必须指定IP和端口

server配置

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

示例:

......
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 2
......

测试:

[root@client ~]# for i in {1..10}; do curl 172.25.254.100; done
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
#将hapserver1和hapserver2中的nginx关闭进行访问
[root@client ~]# curl 172.25.254.100
<html><body><h1>503 Service Unavailable</h1>
No server is available to handle this request.
</body></html>
[root@client ~]# 

在这里插入图片描述

配置sorryserver

配置这个可以在haproxy上也可以新创一个机器

#在haproxy下载httpd
[root@haproxy ~]# dnf install httpd -y
#在httpd的/etc/httpd/conf/httpd.conf中监听的80端口改为8080
[root@haproxy ~]# vim /etc/httpd/conf/httpd.conf
[root@haproxy ~]# cat /etc/httpd/conf/httpd.conf
......
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.
#编写在不能访问hapserver的时候访问的页面
[root@haproxy ~]# echo sorry 下班了 > /var/www/html/index.html

编写backup示例

[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg
[root@haproxy ~]# cat /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
	server web_sorry 172.25.254.100:8080 backup
......
[root@haproxy ~]# systemctl restart haproxy.service

测试,hapserver两个机器的nginx已经关闭

[root@client ~]# curl 172.25.254.100
sorry 下班了
[root@client ~]# 
#hapserver1开启了nginx
[root@client ~]# curl 172.25.254.100
webserver1 - 172.25.254.10
[root@client ~]# curl 172.25.254.100
webserver1 - 172.25.254.10
[root@client ~]# curl 172.25.254.100
webserver1 - 172.25.254.10
[root@client ~]# curl 172.25.254.100
webserver1 - 172.25.254.10
[root@client ~]# 

disabled实验

diaabled:下线指定的realserver

#haproxy配置文件
[root@haproxy ~]# cat /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 disabled
	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 ~]# systemctl restart haproxy.service 

测试:

#hapserver两台机器都开启了nginx
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# 

请求定向到指定网站实验

#haproxy文件配置
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
......
listen webcluster
	bind *:80
	mode http
	balance roundrobin
	redirect prefix http://www.baidu.com
......
#重启服务
[root@haproxy ~]# systemctl restart haproxy.service 

测试:

在这里插入图片描述

socat工具

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

[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
......
    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats mode 600 level admin
......
#重启服务
[root@haproxy ~]# systemctl restart haproxy.service 
[root@haproxy ~]# ll /var/lib/haproxy/stats 
srw-------. 1 root root 0 Aug 11 21:05 /var/lib/haproxy/stats
[root@haproxy ~]# 
#下载socat
[root@haproxy ~]# dnf install socat -y
#查询帮助
[root@haproxy ~]# echo "help" | socat stdio /var/lib/haproxy/stats 
The following commands are valid at this level:
  abort ssl cert <certfile>               : abort a transaction for a certificate file
  add acl [@<ver>] <acl> <pattern>        : add an acl entry
  add map [@<ver>] <map> <key> <val>      : add a map entry (payload supported instead of key/val)
  add ssl crt-list <list> <cert> [opts]*  : add to crt-list file <list> a line <cert> or a payload
  clear acl [@<ver>] <acl>                : clear the contents of this acl
  clear counters [all]                    : clear max statistics counters (or all counters)
  clear map [@<ver>] <map>                : clear the contents of this map
  clear table <table> [<filter>]*         : remove an entry from a table (filter: data/key)
  commit acl @<ver> <acl>                 : commit the ACL at this version
  commit map @<ver> <map>                 : commit the map at this version
  commit ssl cert <certfile>              : commit a certificate file
  del acl <acl> [<key>|#<ref>]            : delete acl entries matching <key>
  del map <map> [<key>|#<ref>]            : delete map entries matching <key>
  del ssl cert <certfile>                 : delete an unused certificate file
  del ssl crt-list <list> <cert[:line]>   : delete a line <cert> from crt-list file <list>
  disable agent                           : disable agent checks
  disable dynamic-cookie backend <bk>     : disable dynamic cookies on a specific backend
  disable frontend <frontend>             : temporarily disable specific frontend
  disable health                          : disable health checks
  disable server (DEPRECATED)             : disable a server for maintenance (use 'set server' instead)
  enable agent                            : enable agent checks
  enable dynamic-cookie backend <bk>      : enable dynamic cookies on a specific backend
  enable frontend <frontend>              : re-enable specific frontend
  enable health                           : enable health checks
  enable server  (DEPRECATED)             : enable a disabled server (use 'set server' instead)
  get acl <acl> <value>                   : report the patterns matching a sample for an ACL
  get map <acl> <value>                   : report the keys and values matching a sample for a map
  get var <name>                          : retrieve contents of a process-wide variable
  get weight <bk>/<srv>                   : report a server's current weight
  new ssl cert <certfile>                 : create a new certificate file to be used in a crt-list or a directory
  operator                                : lower the level of the current CLI session to operator
  prepare acl <acl>                       : prepare a new version for atomic ACL replacement
  prepare map <acl>                       : prepare a new version for atomic map replacement
  set dynamic-cookie-key backend <bk> <k> : change a backend secret key for dynamic cookies
  set map <map> [<key>|#<ref>] <value>    : modify a map entry
  set maxconn frontend <frontend> <value> : change a frontend's maxconn setting
  set maxconn global <value>              : change the per-process maxconn setting
  set maxconn server <bk>/<srv>           : change a server's maxconn setting
  set profiling <what> {auto|on|off}      : enable/disable resource profiling (tasks,memory)
  set rate-limit <setting> <value>        : change a rate limiting value
  set server <bk>/<srv> [opts]            : change a server's state, weight, address or ssl
  set severity-output [none|number|string]: set presence of severity level in feedback information
  set ssl cert <certfile> <payload>       : replace a certificate file
  set ssl ocsp-response <resp|payload>    : update a certificate's OCSP Response from a base64-encode DER
  set ssl tls-key [id|file] <key>         : set the next TLS key for the <id> or <file> listener to <key>
  set table <table> key <k> [data.* <v>]* : update or create a table entry's data
  set timeout [cli] <delay>               : change a timeout setting
  set weight <bk>/<srv>  (DEPRECATED)     : change a server's weight (use 'set server' instead)
  show acl [@<ver>] <acl>]                : report available acls or dump an acl's contents
  show activity                           : show per-thread activity stats (for support/developers)
  show backend                            : list backends in the current running config
  show cache                              : show cache status
  show cli level                          : display the level of the current CLI session
  show cli sockets                        : dump list of cli sockets
  show env [var]                          : dump environment variables known to the process
  show errors [<px>] [request|response]   : report last request and/or response errors for each proxy
  show events [<sink>] [-w] [-n]          : show event sink state
  show fd [num]                           : dump list of file descriptors in use or a specific one
  show info [desc|json|typed|float]*      : report information about the running process
  show libs                               : show loaded object files and libraries
  show map [@ver] [map]                   : report available maps or dump a map's contents
  show peers [dict|-] [section]           : dump some information about all the peers or this peers section
  show pools                              : report information about the memory pools usage
  show profiling [<what>|<#lines>|byaddr]*: show profiling state (all,status,tasks,memory)
  show resolvers [id]                     : dumps counters from all resolvers section and associated name servers
  show schema json                        : report schema used for stats
  show servers conn [<backend>]           : dump server connections status (all or for a single backend)
  show servers state [<backend>]          : dump volatile server information (all or for a single backend)
  show sess [id]                          : report the list of current sessions or dump this exact session
  show ssl cert [<certfile>]              : display the SSL certificates used in memory, or the details of a file
  show ssl crt-list [-n] [<list>]         : show the list of crt-lists or the content of a crt-list file <list>
  show startup-logs                       : report logs emitted during HAProxy startup
  show stat [desc|json|no-maint|typed|up]*: report counters for each proxy and server
  show table <table> [<filter>]*          : report table usage stats or dump this table's contents (filter: data/key)
  show tasks                              : show running tasks
  show threads                            : show some threads debugging information
  show tls-keys [id|*]                    : show tls keys references or dump tls ticket keys when id specified
  show trace [<module>]                   : show live tracing state
  show version                            : show version of the current process
  shutdown frontend <frontend>            : stop a specific frontend
  shutdown session [id]                   : kill a specific session
  shutdown sessions server <bk>/<srv>     : kill sessions on a server
  trace [<module>|0] [cmd [args...]]      : manage live tracing (empty to list, 0 to stop all)
  user                                    : lower the level of the current CLI session to user
  help [<command>]                        : list matching or all commands
  prompt                                  : toggle interactive mode with prompt
  quit                                    : disconnect

[root@haproxy ~]# 

使用示例:

#查看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: 8
Nbproc: 1
Process_num: 1
......
Build info: 2.4.22-f8e3218
Memmax_bytes: 0
PoolAlloc_bytes: 162976
PoolUsed_bytes: 162976
Start_time_sec: 1723381548
Tainted: 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
4 static 1 static 127.0.0.1 0 0 1 1 386 8 2 0 6 0 0 0 - 4331 - 0 0 - - 0
5 app 1 app1 127.0.0.1 0 0 1 1 386 8 2 0 6 0 0 0 - 5001 - 0 0 - - 0
5 app 2 app2 127.0.0.1 0 0 1 1 385 8 2 0 6 0 0 0 - 5002 - 0 0 - - 0
5 app 3 app3 127.0.0.1 0 0 1 1 385 8 2 0 6 0 0 0 - 5003 - 0 0 - - 0
5 app 4 app4 127.0.0.1 0 0 1 1 384 8 2 0 6 0 0 0 - 5004 - 0 0 - - 0

[root@haproxy ~]# 
#查看集群权重
[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 ~]#
#设置权重
[root@haproxy ~]# echo "set weight webcluster/web2 2 " | socat stdio /var/lib/haproxy/stats 

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

[root@haproxy ~]# 
#下线后端服务器
[root@haproxy ~]# echo "disable server webcluster/web1" | socat stdio /var/lib/haproxy/stats
#测试
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# 
#上线后端服务器
[root@haproxy ~]# echo "enable server webcluster/web1" | socat stdio /var/lib/haproxy/stats 
#测试
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# curl 172.25.254.100
webserver1 - 172.25.254.10
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# curl 172.25.254.100
webserver1 - 172.25.254.10
[root@client ~]# 

针对多进程处理方法

如果开启多进程那么我们在对进程的sock文件进行操作时其对进程的操作时随机的 如果需要指定操作进程那么需要用多soct文件方式来完成

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

这样每个进程就会有单独的sock文件来进行单独管理

[root@haproxy ~]# ll /var/lib/haproxy/
总用量 0
srw------- 1 root root 0 88 13:43 stats
srw------- 1 root root 0 88 13:46 stats1
srw------- 1 root root 0 88 13:46 stats2

haproxy的算法

注: 如果是接着上面的实验延续,则需要在做下面实验前还原为单进程

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

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

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

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

静态算法

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

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

注:慢启动是指在服务器刚刚启动上不会把他所应该承担的访问压力全部给它,而是先给一部分,当没 问题后在给一部分

[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
......
listen webcluster
	bind *:80
	mode http
	balance static-rr
	#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 ~]# systemctl restart haproxy.service 
#测试
[root@client ~]# for i in {1..10}; do curl 172.25.254.100; done
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
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
[root@client ~]
first
  • 根据服务器在列表中的位置,自上而下进行调度
  • 其只会当第一台服务器的连接数达到上限,新请求才会分配给下一台服务
  • 其会忽略服务器的权重设置
  • 不支持用socat进行动态修改权重,可以设置0和1,可以设置其它值但无效
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
......
listen webcluster
	bind *:80
	mode http
	#balance static-rr
	balance first
	#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 ~]# systemctl restart haproxy.service
#测试
#在两台主机上分别执行此循环,测试效果,10多20少
while true;do curl 172.25.254.100 ; sleep 0.1;done
动态算法
  • 基于后端服务器状态进行调度适当调整
  • 新请求将优先调度至当前负载较低的服务器
  • 权重可以在haproxy运行时动态调整无需重启
roundrobin
  1. 基于权重的轮询动态调度算法
  2. 支持权重的运行时调整,不同于lvs中的rr轮训模式
  3. HAProxy中的roundrobin支持慢启动(新加的服务器会逐渐增加转发数)
  4. 其每个后端backend中最多支持4095个real server
  5. 支持对real server权重动态调整
  6. roundrobin为默认调度算法,此算法使用广泛
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
......
listen webcluster
	bind *:80
	mode http
	#balance static-rr
	#balance first
	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 ~]# systemctl restart haproxy.service
#测试
[root@client ~]# 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
[root@client ~]# 
leastconn
  • leastconn加权的最少连接的动态
  • 支持权重的运行时调整和慢启动,即:根据当前连接最少的后端服务器而非权重进行优先调度(新客户 端连接)
  • 比较适合长连接的场景使用,比如:MySQL等场景
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
listen webcluster
	bind *:80
	mode http
	#balance static-rr
	#balance first
	#balance roundrobin
	balance leastconn
	#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 ~]# systemctl restart haproxy.service 
#测试
[root@client ~]# for i in {1..10}; do curl 172.25.254.100; done
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
[root@client ~]# 
其他算法

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

source

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

[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
......
listen webcluster
	bind *:80
	mode http
	#balance static-rr
	#balance first
	#balance roundrobin
	#balance leastconn
	balance source
	#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 ~]# systemctl restart haproxy.service
#测试
[root@client ~]# for i in {1..10}; do curl 172.25.254.100; done
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
webserver1 - 172.25.254.10
[root@client ~]#
map-base 取模法

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

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

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

hash-type 指定的默值为此算法

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

比如当源hash值时1111,1112,1113,三台服务器a b c的权重均为1,
即abc的调度标签分别会被设定为 0 1 2(1111%3=1,1112%3=2,1113%3=01111 ----- > nodeb
1112 ------> nodec
1113 ------> nodea
如果a下线后,权重数量发生变化
1111%2=1,1112%2=0,1113%2=1
1112和1113被调度到的主机都发生变化,这样会导致会话丢失

示例

[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
......
listen webcluster
	bind *:80
	mode http
	#balance static-rr
	#balance first
	#balance roundrobin
	#balance leastconn
	balance source
	#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 ~]#
#不支持动态调整权重值
#只能动态上线和下线
一致性hash

一致性哈希,当服务器的总权重发生变化时,对调度结果影响是局部的,不会引起大的变动hash(o) mod n

该hash算法是动态的,支持使用 socat等工具进行在线权重调整,支持慢启动

算法:

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

在这里插入图片描述

hash环偏斜问题

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

hash对象

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

在这里插入图片描述

一致性hash示意图

后端服务器在线与离线的调度方式
在这里插入图片描述

在这里插入图片描述

示例

[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
listen webcluster
	bind *:80
	mode http
	#balance static-rr
	#balance first
	#balance roundrobin
	#balance leastconn
	#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@haproxy ~]# systemctl restart haproxy.service
#测试
[root@client ~]# for i in {1..10}; do curl 172.25.254.100; done
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
webserver1 - 172.25.254.10
webserver2 - 172.25.254.20
[root@client ~]# 
uri

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

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

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

在这里插入图片描述

uri取模法示例:

[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
listen webcluster
	bind *:80
	mode http
	#balance static-rr
	#balance first
	#balance roundrobin
	#balance leastconn
	#balance source
	#hash-type consistent
	balance uri
	#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@haproxy ~]# systemctl restart haproxy.service
#测试
[root@client ~]# 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
[root@client ~]# 

uri 一致性hash配置示例

[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
listen webcluster
	bind *:80
	mode http
	#balance static-rr
	#balance first
	#balance roundrobin
	#balance leastconn
	#balance source
	#hash-type consistent
	balance uri
	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@haproxy ~]# systemctl restart haproxy.service 
#在hapserver1中写入
[root@hapserver1 ~]# echo 172.25.254.10 - index1.html > /usr/share/nginx/html/index1.html 
[root@hapserver1 ~]# echo 172.25.254.10 - index2.html > /usr/share/nginx/html/index2.html 
[root@hapserver1 ~]# echo 172.25.254.10 - index3.html > /usr/share/nginx/html/index3.html 
[root@hapserver1 ~]#
#在hapserver2中写入
[root@hapserver2 ~]# echo 172.25.254.20 - index3.html > /usr/share/nginx/html/index3.html
[root@hapserver2 ~]# echo 172.25.254.20 - index2.html > /usr/share/nginx/html/index2.html
[root@hapserver2 ~]# echo 172.25.254.20 - index1.html > /usr/share/nginx/html/index1.html
[root@hapserver2 ~]# 
#测试
[root@client ~]# curl 172.25.254.100/index1.html
172.25.254.10 - index1.html
[root@client ~]# curl 172.25.254.100/index2.html
172.25.254.20 - index2.html
[root@client ~]# curl 172.25.254.100/index3.html
172.25.254.10 - index3.html
[root@client ~]# 
url_param

url_param对用户请求的url中的 params 部分中的一个参数key对应的value值作hash计算,并由服务器 总权重相除以后派发至某挑出的服务器,后端搜索同一个数据会被调度到同一个服务器,多用与电商

通常用于追踪用户,以确保来自同一个用户的请求始终发往同一个real server

如果无key,将按roundrobin算法

url_param取模法配置示例

[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
listen webcluster
	bind *:80
	mode http
	#balance static-rr
	#balance first
	#balance roundrobin
	#balance leastconn
	#balance source
	#hash-type consistent
	#balance uri
	balance url_param name,userid
	#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@haproxy ~]# systemctl restart haproxy.service 
#测试
[root@client ~]# curl 172.25.254.100/index1.html?userid=111
172.25.254.10 - index1.html
[root@client ~]# curl 172.25.254.100/index1.html?userid=222
172.25.254.20 - index1.html
[root@client ~]# curl 172.25.254.100/index1.html?userid=333
172.25.254.10 - index1.html
[root@client ~]# curl 172.25.254.100/index1.html?userid=444
172.25.254.20 - index1.html
[root@client ~]# curl 172.25.254.100/index1.html?userid=555
172.25.254.10 - index1.html
[root@client ~]# curl 172.25.254.100/index1.html?userid=666
172.25.254.20 - index1.html
[root@client ~]# 

url_param一致性hash配置示例

[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
listen webcluster
	bind *:80
	mode http
	#balance static-rr
	#balance first
	#balance roundrobin
	#balance leastconn
	#balance source
	#hash-type consistent
	#balance uri
	balance url_param name,userid
	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@haproxy ~]# systemctl restart haproxy.service 
#测试
[root@client ~]# curl 172.25.254.100/index1.html?userid=wu
172.25.254.20 - index1.html
[root@client ~]# curl 172.25.254.100/index1.html?userid=wu
172.25.254.10 - index1.html
[root@client ~]# curl 172.25.254.100/index1.html?userid=test
172.25.254.10 - index1.html
[root@client ~]# curl 172.25.254.100/index1.html?userid=test
172.25.254.10 - index1.html
[root@client ~]# curl 172.25.254.100/index1.html?userid=test
172.25.254.20 - index1.html
[root@client ~]# 
hdr

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

hdr取模法配置示例

[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
listen webcluster
	bind *:80
	mode http
	#balance static-rr
	#balance first
	#balance roundrobin
	#balance leastconn
	#balance source
	#hash-type consistent
	#balance uri
	#balance url_param name,userid
	balance hdr(User-Angent)
	#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@haproxy ~]# systemctl restart haproxy.service
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
listen webcluster
	bind *:80
	mode http
	#balance static-rr
	#balance first
	#balance roundrobin
	#balance leastconn
	#balance source
	#hash-type consistent
	#balance uri
	#balance url_param name,userid
	balance hdr(User-Angent)
	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@haproxy ~]# systemctl restart haproxy.service
#测试
[root@client ~]# curl -v 172.25.24
*   Trying 172.25.0.24:80...
^[[A^[[A^[[A^C
[root@client ~]# curl -v 172.25.254.100
*   Trying 172.25.254.100:80...
* Connected to 172.25.254.100 (172.25.254.100) port 80 (#0)
> GET / HTTP/1.1
> Host: 172.25.254.100
> User-Agent: curl/7.76.1
> Accept: */*
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< server: nginx/1.20.1
< date: Sun, 11 Aug 2024 14:54:32 GMT
< content-type: text/html
< content-length: 27
< last-modified: Sun, 11 Aug 2024 08:17:25 GMT
< etag: "66b87395-1b"
< accept-ranges: bytes
< 
webserver2 - 172.25.254.20
* Connection #0 to host 172.25.254.100 left intact
[root@client ~]# curl -vA "firefox" 172.25.254.100
*   Trying 172.25.254.100:80...
* Connected to 172.25.254.100 (172.25.254.100) port 80 (#0)
> GET / HTTP/1.1
> Host: 172.25.254.100
> User-Agent: firefox
> Accept: */*
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< server: nginx/1.20.1
< date: Sun, 11 Aug 2024 14:54:52 GMT
< content-type: text/html
< content-length: 27
< last-modified: Sun, 11 Aug 2024 08:17:06 GMT
< etag: "66b87382-1b"
< accept-ranges: bytes
< 
webserver1 - 172.25.254.10
* Connection #0 to host 172.25.254.100 left intact
[root@client ~]# curl -vA "sougou" 172.25.254.100
*   Trying 172.25.254.100:80...
* Connected to 172.25.254.100 (172.25.254.100) port 80 (#0)
> GET / HTTP/1.1
> Host: 172.25.254.100
> User-Agent: sougou
> Accept: */*
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< server: nginx/1.20.1
< date: Sun, 11 Aug 2024 14:55:00 GMT
< content-type: text/html
< content-length: 27
< last-modified: Sun, 11 Aug 2024 08:17:06 GMT
< etag: "66b87382-1b"
< accept-ranges: bytes
< 
webserver1 - 172.25.254.10
* Connection #0 to host 172.25.254.100 left intact
[root@client ~]# 

在这里插入图片描述

高级功能及配置

基于cookie的会话保持

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

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

haproxy主机的haproxy主机配置文件/etc/haproxy/haproxy.cfg

配置选项

参数描述
namecookie的key名称,用于实现持久连接
insert插入新的cookie,默认不插入cookie
indirect如果用户端已经有cookie,则不会再发送cookie信息
nocache当client和haproxy之间有缓存服务器(如:CDN)时,不允许中间缓存器缓存cookie,因为这会导致很多经过同一个CDN的请求都发送到同一台后端服务器

实验示例:

[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
listen webcluster
	bind *:80
	mode http
	#balance static-rr
	#balance first
	balance roundrobin
	#balance leastconn
	#balance source
	#hash-type consistent
	#balance uri
	#balance url_param name,userid
	#balance hdr(User-Angent)
	#hash-type consistent
	cookie WEBCOOKIE insert nocache indirect
	#redirect prefix http://www.baidu.com
	server web1 172.25.254.10:80 cookie wu1 check inter 2 fall 3 rise 5 weight 1
	server web2 172.25.254.20:80 cookie wu2 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@client ~]# curl -b WEBCOOKIE=wu1 172.25.254.100
webserver1 - 172.25.254.10
[root@client ~]# curl -b WEBCOOKIE=wu2 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# 

在这里插入图片描述

HAProxy状态页

通过web界面,显示当前HAProxy的运行状态

配置项:

配置项说明
stats enable基于默认的参数启用stats page
stats hide-version将状态页中的haproxy版本隐藏
stats refresh 设定自动刷新时间间隔,默认不自动刷新
stats uri 自定义stats page uri,默认值:/haproxy?stats
stats auth :认证时的账号和密码,可以定义多个用户,每行指定一个用户
默认:no authentication
stats admin { if | unless } 启用stats page中的管理功能

实验示例:

启动状态页:
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
listen webcluster
	bind *:80
	mode http
	#balance static-rr
	#balance first
	balance roundrobin
	#balance leastconn
	#balance source
	#hash-type consistent
	#balance uri
	#balance url_param name,userid
	#balance hdr(User-Angent)
	#hash-type consistent
	cookie WEBCOOKIE insert nocache indirect
	#redirect prefix http://www.baidu.com
	server web1 172.25.254.10:80 cookie wu1 check inter 2 fall 3 rise 5 weight 1
	server web2 172.25.254.20:80 cookie wu2 check inter 2 fall 3 rise 5 weight 1
	#server web_sorry 172.25.254.100:8080 backup

listen stats
	mode http
	bind *:9999
	stats enable
	stats refresh 2		#设定自动刷新时间间隔为2s
	stats uri /status
	stats auth wu:wu
...
[root@haproxy ~]# systemctl restart haproxy.service 
[root@haproxy ~]# 

在这里插入图片描述

在这里插入图片描述

可以将listen后面的内容注释掉

在这里插入图片描述

登录状态页:
#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(每秒的连接会话信息):
cur:每秒的当前会话数量 :
max:每秒新的最大会话数量
limit:每秒新的会话限制量
sessions(会话信息):
cur:当前会话量
max:最大会话量
limit: 限制会话量
Total:总共会话量
LBTot:选中一台服务器所用的总时间
Last:和服务器的持续连接时间
Wght:权重
Bytes(流量统计):
In:网络的字节输入总量
Out:网络的字节输出总量
Dwn:后端服务器连接后都是DOWN的数量
Denied(拒绝统计信息):
Req:拒绝请求量
Resp:拒绝回复量
Errors(错误统计信息):
Req:错误请求量
conn:错误链接量
Resp:错误响应量
Warnings(警告统计信息):
 Retr:重新尝试次数
Redis:再次发送次数
Server(real server信息):
Status:后端机的状态,包括UP和DOWN
LastChk:持续检查后端服务器的时间
Act:活动链接数量
Bck:备份的服务器数量
Chk:心跳检测时间
Dwntme:总的downtime时间
Thrtle:server 状态

IP透传

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

layer 4与layer 7

四层:IP+PORT转发

七层:协议+内交换

四层负载

在四层负载设备中,把client发送到报文目标地址(原来是负载均衡设备的IP地址),根据均衡设备设置的选择web服务器的规则选择对应的web服务器IP地址,这样client就可以直接跟此服务器建立TCP连接并发送数据,而四层负载自身不参与建立连接,而和LVS不同,haproxy是伪四层负载均衡,因为haproxy需要分别和前端客户及后端服务器建立连接

七层代理

七层负载均衡服务器起了一个反向代理服务器的作用,服务器建立一次TCP连接要三次握手,而client要访问web server要先与七层负载设备进行三次握手后建立TCP连接,把要访问的报文信息发送给七层负载均衡,然后七层负载均衡再根据设置的均衡规则选择特定的web server,然后通过三次握手与此台web server建立TCP连接,然后web server把需要的数据发送给七层负载均衡设备,负载均衡设备再把数据发送给client,所以,七层负载均衡设备起到了代理服务器的作用,七层代理需要和client和后端服务器分别建立连接

四层IP透传
[root@haproxy ~]# cat /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

...
listen webcluster
        bind *:80
        mode tcp
        #balance static-rr
        #balance first
        balance roundrobin
        #balance leastconn
        #balance source
        #hash-type consistent
        #balance uri
        #balance url_param name,userid
        #balance hdr(User-Angent)
        #hash-type consistent
        #cookie WEBCOOKIE insert nocache indirect
        #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@haproxy ~]# systemctl restart haproxy.service 
#访问测试
[root@client ~]# curl 172.25.254.100
webserver - 172.25.254.10
[root@client ~]# 
#查看server2日志
172.25.254.100 - - [12/Aug/2024:00:13:47 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1" "-"
172.25.254.100 - - [12/Aug/2024:00:16:27 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1" "-"
[root@hapserver2 ~]# 
#haproxy日志设定
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
listen webcluster
        bind *:80
        mode tcp
        #balance static-rr
        #balance first
        balance roundrobin
        #balance leastconn
        #balance source
        #hash-type consistent
        #balance uri
        #balance url_param name,userid
        #balance hdr(User-Angent)
        #hash-type consistent
        #cookie WEBCOOKIE insert nocache indirect
        #redirect prefix http://www.baidu.com
        server web1 172.25.254.10:80 send-proxy 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
#修改server2的nginx的日志文件
[root@hapserver2 ~]# cat /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"';
...

    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 {
        }
...
#重启nginx服务
[root@hapserver2 ~]# systemctl restart nginx.service 
#访问测试
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]#
#查看server2日志内容
[root@hapserver2 ~]# cat /var/log/nginx/access.log
...
172.25.254.100 - - [12/Aug/2024:00:26:09 +0800] "GET / HTTP/1.1" 200 27 "-" "172.25.254.200""curl/7.76.1" "-"
[root@hapserver2 ~]#
#apache四层
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
listen webcluster
        bind *:80
        mode tcp
        #balance static-rr
        #balance first
        balance roundrobin
        #balance leastconn
        #balance source
        #hash-type consistent
        #balance uri
        #balance url_param name,userid
        #balance hdr(User-Angent)
        #hash-type consistent
        #cookie WEBCOOKIE insert nocache indirect
        #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 send-proxy check inter 2 fall 3 rise 5 weight 1
        #server web_sorry 172.25.254.100:8080 backup
...
#访问测试
webserver2 - 172.25.254.20
[root@client ~]# curl 172.25.254.100
webserver - 172.25.254.10
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# 
#查看日志
#server1
- 172.25.254.100 - - [12/Aug/2024:00:30:58 +0800] "PROXY TCP4 172.25.254.100" 400 226 "-" "-"
- 172.25.254.100 - - [12/Aug/2024:00:30:58 +0800] "PROXY TCP4 172.25.254.100" 400 226 "-" "-"
- 172.25.254.100 - - [12/Aug/2024:00:30:58 +0800] "PROXY TCP4 172.25.254.100" 400 226 "-" "-"
#server2
[root@hapserver2 ~]# cat /var/log/nginx/access.log
172.25.254.100 - - [12/Aug/2024:00:26:09 +0800] "GET / HTTP/1.1" 200 27 "-" "172.25.254.200""curl/7.76.1" "-"
172.25.254.100 - - [12/Aug/2024:00:31:02 +0800] "GET / HTTP/1.1" 200 27 "-" "172.25.254.200""curl/7.76.1" "-"
172.25.254.100 - - [12/Aug/2024:00:31:04 +0800] "GET / HTTP/1.1" 200 27 "-" "172.25.254.200""curl/7.76.1" "-"
[root@hapserver2 ~]# 
七层IP透传

当haproxy工作在七层的时候,也可以透传客户端真实IP至后台服务器

HAProxy配置

在由haproxy发往后端主机的请求报文中添加"X-Forwareded-For"首部,其值为前端客户端的地址;用于向后端主发送真实的客户端IP

option forwardfor [ except <network> ] [ header <name> ] [ if-none ]
[ except <network> ]:请求报请来自此处指定的网络时不予添加此首部,如haproxy自身所在网络
[ header <name> ]: 使用自定义的首部名称,而非“X-Forwarded-For",示例:X-client
[ if-none ] 如果没有首部才添加首部,如果有使用默认值

配置hapserver的httpd服务

#关闭nginx
[root@hapserver1 ~]# systemctl stop nginx.service
#下载httpd
[root@hapserver1 ~]# dnf install httpd -y
#编辑访问文件
[root@hapserver1 ~]# echo webserver - 172.25.254.10 > /var/www/html/index.html 
#重启httpd服务
[root@hapserver1 ~]# systemctl restart httpd
#测试
[root@client ~]# curl 172.25.254.100
webserver - 172.25.254.10
[root@client ~]#
#设定日志/etc/httpd/conf/httpd.conf中加入%{X-Forwarded-For}i
    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
#重启httpd服务
[root@hapserver1 ~]# systemctl restart httpd
#访问测试
[root@client ~]# curl 172.25.254.100
webserver - 172.25.254.10
[root@client ~]# 
#查看日志
[root@hapserver1 ~]# cat /etc/httpd/logs/access_log 
172.25.254.200 172.25.254.100 - - [12/Aug/2024:00:05:33 +0800] "GET / HTTP/1.1" 200 26 "-" "curl/7.76.1"
[root@hapserver1 ~]# 
#server2
172.25.254.100 - - [12/Aug/2024:00:13:45 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1" "-"
172.25.254.100 - - [12/Aug/2024:00:13:47 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1" "-"
[root@hapserver2 ~]# 

ACL

访问控制列表ACL(Access Control Lists)

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

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

ACL配置选项
#用acl来定义或声明一个acl
acl	<aclname>	<criterion>	[flags]	[opertor]	[<value>]
acl		名称		匹配规范	匹配模式  具体操作符		操作对象类型
ACL-Name名称
acl	image_service	hdr_dom(host)	-i	img.lanjinli.com
#ACL名称,可以使用大写字母A-Z,小写字母a-z,数字0-9,冒号:,点.,中横线和下划线,并且严格区分大小写,比如:my_acl和My_Acl就是两个完全不同的acl5.8.1.2 ACL-criterion
CL-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

实验示例:

#listen webcluster部分的内容已经全部注释
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
frontend webcluster
        bind *:80
        mode http
        acl test hdr(dom) -i www.lanjinli.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
#将client中的hosts文件添加本地解析/etc/hoats
172.25.254.100 www.lanjinli.org
#访问测试
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# curl www.lanjinli.org
webserver2 - 172.25.254.20
[root@client ~]# 
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
frontend webcluster
        bind *:80
        mode http
        acl test hdr(host) -i www.lanjinli.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
#访问测试
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# curl www.lanjinli.org
webserver1 - 172.25.254.10
[root@client ~]#
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
frontend webcluster
        bind *:80
        mode http
        acl test hdr_end(host) -i www.lanjinli.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
#访问测试
[root@client ~]# curl www.lanjinli.org
webserver1 - 172.25.254.10
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]# 
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
frontend webcluster
        bind *:80
        mode http
        acl test hdr_beg(host) -i 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@haproxy ~]# systemctl restart haproxy.service
#将client中的hosts文件添加本地解析/etc/hoats
172.25.254.100 www.lanjinli.org www.lanjinli.com bbs.lanjinli.org
#访问测试
[root@client ~]# curl bbs.lanjinli.org
webserver1 - 172.25.254.10
[root@client ~]# 

[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
frontend webcluster
        bind *:80
        mode http
        #acl test hdr_beg(host) -i bbs
        acl test base_sub -i 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@haproxy ~]# systemctl restart haproxy.service
#访问测试
[root@client ~]# curl bbs.lanjinli.org
webserver1 - 172.25.254.10
[root@client ~]# curl 172.25.254.100
webserver2 - 172.25.254.20
[root@client ~]#
#精准匹配
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
frontend webcluster
        bind *:80
        mode http
        #acl test hdr_beg(host) -i bbs
        acl test base_reg -i wu/$
        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
#在server1中设置一个子文件
[root@hapserver1 ~]# mkdir /usr/share/nginx/html/wu
[root@hapserver1 ~]# echo 172.25.254.10 wu > /usr/share/nginx/html/wu/index.html
[root@hapserver1 ~]# 
#在client中添加本地解析
172.25.254.100 www.lanjinli.org www.lanjinli.com bbs.lanjinli.org www.test.com
#访问测试
[root@client ~]# curl www.test.com
webserver2 - 172.25.254.20
[root@client ~]# curl www.test.com/wu/
172.25.254.10 wu
[root@client ~]# 

[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
frontend webcluster
        bind *:80
        mode http
        #acl test hdr_beg(host) -i bbs
        #acl test base_reg -i wu/$
        acl test base_sub -m sub wu
        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
#访问测试
[root@client ~]# curl www.lanjinli.org
webserver2 - 172.25.254.20
[root@client ~]# curl www.lanjinli.org/wu/
172.25.254.10 wu
[root@client ~]# curl www.test.com/wu/
172.25.254.10 wu
[root@client ~]# 
ACL-flags 匹配模式
-i 不区分大小写
-m 使用指定的正则表达式匹配方法
-n 不做DNS解析
-u 禁止acl重名,否则多个同名ACL匹配或关系
ACL-operator 具体操作符
整数比较: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-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进制
多个ACL的组合调用方式

多个ACL的逻辑处理

与:隐式(默认)使用
或:使用"or""||"表示
否定:使用 "!" 表示

多个ACL调用方式:

#示例:
if valid_src valid_port #与关系,ACL中A和B都要满足为true,默认为与
if invalid_src || invalid_port #或,ACL中A或者B满足一个为true
if ! invalid_src #非,取反,不满足ACL才为true

实验示例

#server2中创键nginx子访问目录
[root@hapserver2 ~]# mkdir -p /usr/share/nginx/html/wu
[root@hapserver2 ~]# echo 172.25.254.20 wu > /usr/share/nginx/html/wu/index.html
[root@hapserver2 ~]# 
#编辑haproxy文件
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
frontend webcluster
        bind *:80
        mode http
        #acl test hdr_beg(host) -i bbs
        #acl test base_reg -i wu/$
        acl test base_sub -m sub wu
        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
#访问测试
[root@client ~]# curl www.test.com/wu/
172.25.254.20 wu
[root@client ~]# curl www.test.com
webserver1 - 172.25.254.10
[root@client ~]# 
#或
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
frontend webcluster
        bind *:80
        mode http
        #acl test hdr_beg(host) -i bbs
        #acl test base_reg -i wu/$
        acl domain hdr_beg(host) -i bbs
        acl test base_sub -m sub wu
        use_backend webcluster-host if test || 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@haproxy ~]# systemctl restart haproxy.service
#访问测试
[root@client ~]# curl www.test.com
webserver1 - 172.25.254.10
[root@client ~]# curl bbs.lanjinli.org
webserver1 - 172.25.254.10
[root@client ~]# curl bbs.lanjinli.org/wu/
172.25.254.10 wu
[root@client ~]# curl www.lanjinli.org/wu/
172.25.254.10 wu
[root@client ~]# curl www.test.com
webserver2 - 172.25.254.20
[root@client ~]#
#与
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
frontend webcluster
        bind *:80
        mode http
        #acl test hdr_beg(host) -i bbs
        #acl test base_reg -i wu/$
        acl domain hdr_beg(host) -i bbs
        acl test base_sub -m sub wu
        use_backend webcluster-host if test || 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@haproxy ~]# systemctl restart haproxy.service
#访问测试
[root@client ~]# curl www.test.com
webserver2 - 172.25.254.20
[root@client ~]# curl www.test.com
webserver2 - 172.25.254.20
[root@client ~]# curl bbs.lanjinli.org
webserver2 - 172.25.254.20
[root@client ~]# curl bbs.lanjinli.org/wu/
172.25.254.10 wu
[root@client ~]# curl www.lanjinli.org/wu/
172.25.254.20 wu
[root@client ~]# 
基于域名的访问匹配
#haproxy配置文件
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
frontend webcluster
	bind *:80
	mode http
	#acl test hdr_beg(host) -i bbs
	#acl test base_reg -i wu/$
	acl domain hdr_dom(host) -i www.lanjinli.org
	#acl test base_sub -m sub wu
	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@haproxy ~]# systemctl restart haproxy.service 
#访问测试,只有指定了的域名才能访问10其他访问20
[root@client ~]# curl www.lanjinli.org
webserver1 - 172.25.254.10
[root@client ~]# curl www.test.com
webserver2 - 172.25.254.20
[root@client ~]# 
基于源ip或子网调度访问
#haproxy配置文件
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
frontend webcluster
	bind *:80
	mode http
	acl ctrl_ip src 172.25.254.200 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
...
#重启服务
[root@haproxy ~]# systemctl restart haproxy.service 
#访问测试
#client的ip为200
[root@client ~]# curl www.test.com
webserver1 - 172.25.254.10
[root@client ~]# 
#server2的ip是172.25.254.20
[root@hapserver2 ~]# curl 172.25.254.100
webserver1 - 172.25.254.10
[root@hapserver2 ~]# 


#拒绝访问
#haproxy配置文件
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
frontend webcluster
	bind *:80
	mode http
	acl ctrl_ip src 172.25.254.200 172.25.254.20 192.168.0.0/24
    #use_backend webcluster-host if ctrl_ip
    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
...
#重启服务
[root@haproxy ~]# systemctl restart haproxy.service 
#访问测试
[root@hapserver2 ~]# curl 172.25.254.100
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>
[root@hapserver2 ~]# 
[root@client ~]# curl www.test.com
webserver1 - 172.25.254.10
[root@client ~]# curl www.test.com
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>
[root@client ~]# 
匹配浏览器类型

匹配客户端浏览器,将不同类型的浏览器调动至不同的服务器组

[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
frontend webcluster
	bind *:80
	mode http
	acl badwebrowers hdr_sub(User-Agent) -i curl wget
	#use_backend webcluster-host if ctrl_ip
	http-request deny if badwebrowers
	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 
#访问测试
[root@client ~]# curl 172.25.254.100
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>
[root@client ~]# 

在这里插入图片描述

基于文件后缀名实现动静分离
#hapserver1下载php
[root@hapserver1 ~]# dnf install php -y
#重启httpd服务
[root@hapserver1 ~]# systemctl restart httpd
#编写测试页面
[root@hapserver1 ~]# cat /var/www/html/index.php 
<?php
	phpinfo();
?>
[root@hapserver1 ~]# 
#编写haproxy配置文件
[root@haproxy ~]# cat /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@haproxy ~]# systemctl restart haproxy.service
#访问测试

在这里插入图片描述

匹配访问路径实现动静分离
#在server2中创建文件
[root@hapserver2 ~]# mkdir /usr/share/nginx/html/static -p
[root@hapserver2 ~]# echo static - 172.25.254.20 > /usr/share/nginx/html/static/index.html
[root@hapserver2 ~]# curl 172.25.254.20/static/
static - 172.25.254.20
[root@hapserver2 ~]# 
#在server1中创建测试文件
[root@hapserver1 ~]# mkdir -p /var/www/html/php
[root@hapserver1 ~]# cp /var/www/html/index.php /var/www/html/php/
[root@hapserver1 ~]# cat /var/www/html/php/index.php 
<?php
	phpinfo();
?>
[root@hapserver1 ~]# 
#haproxy编写配置文件
[root@haproxy ~]# cat /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
...
#重启服务
[root@haproxy ~]# systemctl restart haproxy.service
#访问测试
[root@client ~]# curl 172.25.254.100/static/
static - 172.25.254.20
[root@client ~]# 

在这里插入图片描述

自定义haproxy错误界面

#自定义错误页
errorfile <code> <file>
<code> #HTTP status code.支持200, 400, 403, 405, 408, 425, 429, 500, 502,503,504
<file> #包含完整HTTP响应头的错误页文件的绝对路径。 建议后缀".http",以和一般的html文件相区分
#示例:
errorfile 503 /haproxy/errorpages/503page.http

实验示例

基于自定义的错误页面文件
#server1关闭了httpd与nginx服务
[root@hapserver1 ~]# systemctl stop nginx
[root@hapserver1 ~]# systemctl stop httpd
[root@hapserver1 ~]# 
#查找状态码信息文件
[root@haproxy ~]# rpm -ql haproxy | grep http
/usr/share/doc/haproxy/design-thoughts/http2.txt
/usr/share/doc/haproxy/design-thoughts/http_load_time.url
/usr/share/doc/haproxy/internals/http-cookies.txt
/usr/share/doc/haproxy/internals/http-docs.txt
/usr/share/doc/haproxy/internals/http-parsing.txt
/usr/share/doc/haproxy/option-http_proxy.cfg
/usr/share/haproxy/400.http
/usr/share/haproxy/403.http
/usr/share/haproxy/408.http
/usr/share/haproxy/500.http
/usr/share/haproxy/502.http
/usr/share/haproxy/503.http
/usr/share/haproxy/504.http
[root@haproxy ~]# 

在这里插入图片描述

#重新编辑503状态码的配置文件
[root@haproxy ~]# mkdir /etc/haproxy/errorpage -p
[root@haproxy ~]# cat /etc/haproxy/errorpage/bedpage.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 ~]# 
#编辑haproxy配置文件
[root@haproxy ~]# cat /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/bedpage.http
...
#重启服务
[root@haproxy ~]# systemctl restart haproxy.service 
#访问测试

在这里插入图片描述

基于http重定向错误页面
#编辑haproxy配置文件
[root@haproxy ~]# cat /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/bedpage.http
    errorloc 503 https://www.baidu.com
...
#重启服务
[root@haproxy ~]# systemctl restart haproxy.service 
#访问测试

在这里插入图片描述

HAProxy 四层负载

针对除HTTP以外的TCP协议应用服务访问的应用场景

MySQL
Redis
Memcache
RabbitMQ

实验示例

#server2和server1安装呢maridb
[root@hapserver1 ~]# dnf install mariadb-server -y
#######
[root@hapserver2 ~]# dnf install mariadb-server -y
#更改mariadb配置文件,找到[mysqld]在后面加入
#server1的
[root@hapserver1 ~]# grep server-id /etc/my.cnf.d/mariadb-server.cnf 
server-id=1
#server2的
[root@hapserver2 ~]# grep server-id /etc/my.cnf.d/mariadb-server.cnf
server-id=1
[root@hapserver2 ~]# 
#server1数据库配置
#server1
[root@hapserver1 ~]# 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.001 sec)

MariaDB [(none)]> CREATE USER wu@'%' identified by 'wu';
Query OK, 0 rows affected (0.002 sec)

MariaDB [(none)]> GRANT ALL ON *.* TO wu@'%';
Query OK, 0 rows affected (0.002 sec)

MariaDB [(none)]> QUIT
Bye
[root@hapserver1 ~]#  
#server2
[root@hapserver2 ~]# 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 wu@'%' identified by 'wu';
Query OK, 0 rows affected (0.002 sec)

MariaDB [(none)]> GRANT ALL ON *.* TO wu@'%';
Query OK, 0 rows affected (0.001 sec)

MariaDB [(none)]>QUIT
Bye
[root@hapserver2 ~]#  

#haproxy安装mariadb的客户端
[root@haproxy ~]# yum install mariadb -y
#查看3306端口是否打开
[root@hapserver1 ~]# netstat -atnlupe | grep 3306
tcp6       0      0 :::3306                 :::*                    LISTEN      27         535197     6308/mariadbd       
[root@hapserver1 ~]# 
######
[root@hapserver2 ~]# netstat -atnlupe | grep 3306
tcp6       0      0 :::3306                 :::*                    LISTEN      27         32636      3953/mariadbd       
[root@hapserver2 ~]# 
#测试访问
[root@haproxy ~]# mysql -uwu -p -h 172.25.254.10
Enter password: 
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)]> quit
Bye
[root@haproxy ~]#
#编辑haproxy配置文件实现负载
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
#    errorfile 503 /etc/haproxy/errorpage/bedpage.http
    errorloc 503 https://www.baidu.com

listen dbserver
        bind *:3306
        mode tcp
        balance static-rr
        server db1 172.25.254.10:3306 check inter 2 rise 5
        server db2 172.25.254.20:3306 check inter 2 rise 5
...
[root@haproxy ~]# systemctl restart haproxy.service 
#访问测试
[root@haproxy ~]# mysql -uwu -pwu -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.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.002 sec)

MariaDB [(none)]> quit
Bye
[root@haproxy ~]# mysql -uwu -pwu -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 |
+-------------+
|           1 |
+-------------+
1 row in set (0.002 sec)

MariaDB [(none)]> quit
Bye
[root@haproxy ~]#
#server1访问
[root@hapserver1 ~]# mysql -uwu -pwu -h 172.25.254.100
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 7
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.002 sec)

MariaDB [(none)]> quit
Bye
[root@hapserver1 ~]# mysql -uwu -pwu -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.002 sec)

MariaDB [(none)]> quit
Bye
[root@hapserver1 ~]# 
#server2访问
[root@hapserver2 ~]# mysql -uwu -pwu -h 172.25.254.100
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 8
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.002 sec)

MariaDB [(none)]> quit
Bye
[root@hapserver2 ~]# mysql -uwu -pwu -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.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.002 sec)

MariaDB [(none)]> quit
Bye
[root@hapserver2 ~]# 

HAProxy https 实现

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

#在haproxy章创建放证书秘钥
[root@haproxy ~]# mkdir -p /etc/haproxy/certs
[root@haproxy ~]# mkdir -p /etc/haproxy/certs
[root@haproxy ~]# openssl req -newkey rsa:2048 -node -sha256 -keyout /etc/haproxy/certs/lanjinli.org.key -x509 -day 365 -out /etc/haproxy/certs/lanjinli.org.crt
req: Use -help for summary.
[root@haproxy ~]# openssl req -newkey rsa:2048 -nodes -sha256 -keyout /etc/haproxy/certs/lanjinli.org.key -x509 -day 365 -out /etc/haproxy/certs/lanjinli.org.crt
req: Use -help for summary.
[root@haproxy ~]# openssl req -newkey rsa:2048 -nodes -sha256 -keyout /etc/haproxy/certs/lanjinli.org.key -x509 -days 365 -out /etc/haproxy/certs/lanjinli.org.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) []:SHANNXI
Locality Name (eg, city) [Default City]:XI'AN
Organization Name (eg, company) [Default Company Ltd]:LANJINLI
Organizational Unit Name (eg, section) []:webserver
Common Name (eg, your name or your server's hostname) []:www.lanjinli.org
Email Address []:admin@lanjinli.org
[root@haproxy ~]# ls /etc/haproxy/certs/
lanjinli.org.crt  lanjinli.org.key
[root@haproxy ~]# cat /etc/haproxy/certs/lanjinli.org.key /etc/haproxy/certs/lanjinli.org.crt > /etc/haproxy/certs/lanjinli.pem
#编辑haproxy配置文件
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
...
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
listen web-https
        bind *:443 ssl crt /etc/haproxy/certs/lanjinli.pem
        mode http
        balance roundrobin
        server web2 172.25.254.20:80 check inter 2 fall 2 rise 5
        server web1 172.25.254.10:80 check inter 2 fall 2 rise 5
...
[root@haproxy ~]# systemctl restart haproxy.service 
#访问测试

在这里插入图片描述

在这里插入图片描述

全站加密
#haproxy的配置文件
[root@haproxy ~]# cat /etc/haproxy/haproxy.cfg
#---------------------------------------------------------------------
# Example configuration for a possible web application.  See the
# full configuration options online.
#
#   https://www.haproxy.org/download/1.8/doc/configuration.txt
#
#---------------------------------------------------------------------

#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
    # to have these messages end up in /var/log/haproxy.log you will
    # need to:
    #
    # 1) configure syslog to accept network log events.  This is done
    #    by adding the '-r' option to the SYSLOGD_OPTIONS in
    #    /etc/sysconfig/syslog
    #
    # 2) configure local2 events to go to the /var/log/haproxy.log
    #   file. A line like the following can be added to
    #   /etc/sysconfig/syslog
    #
    #    local2.*                       /var/log/haproxy.log
    #
    log         127.0.0.1 local2

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

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

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

#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
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/bedpage.http
    errorloc 503 https://www.baidu.com

listen dbserver
	bind *:3306
	mode tcp
	balance static-rr
	server db1 172.25.254.10:3306 check inter 2 rise 5
	server db2 172.25.254.20:3306 check inter 2 rise 5



#---------------------------------------------------------------------
# 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 tcp
#	balance static-rr
#	#balance first
#	balance roundrobin
#	#balance leastconn
#	#balance source
#	#hash-type consistent
#	#balance uri
#	#balance url_param name,userid
##	#balance hdr(User-Angent)
#	#hash-type consistent
#	#cookie WEBCOOKIE insert nocache indirect
#	#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

listen stats
	mode http
	bind *:9999
	stats enable
	stats refresh 2
	stats uri /status
	stats auth wu:wu

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
	redirect scheme https if !{ ssl_fc }


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
listen web-https
	bind *:443 ssl crt /etc/haproxy/certs/lanjinli.pem
	mode http
	balance roundrobin
	server web2 172.25.254.20:80 check inter 2 fall 2 rise 5
	server web1 172.25.254.10:80 check inter 2 fall 2 rise 5
#frontend main
#    bind *:5000
#    acl url_static       path_beg       -i /static /images /javascript /stylesheets
#    acl url_static       path_end       -i .jpg .gif .png .css .js
#
#    use_backend static          if url_static
##    default_backend             app
#
#---------------------------------------------------------------------
# static backend for serving up images, stylesheets and such
#---------------------------------------------------------------------
##backend static
#    balance     roundrobin
#    server      static 127.0.0.1:4331 check
#
#---------------------------------------------------------------------
# round robin balancing between the various backends
#---------------------------------------------------------------------
#backend app
#    balance     roundrobin
#    server  app1 127.0.0.1:5001 check
#    server  app2 127.0.0.1:5002 check
##    server  app3 127.0.0.1:5003 check
#    server  app4 127.0.0.1:5004 check
[root@haproxy ~]# systemctl restart haproxy.service

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值