【三】haproxy高级功能配置

介绍HAProxy高级配置及实用案例

一.基于cookie会话保持

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

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

配置选项

cookie name [rewrite linsertl 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的请求都发送到同一台后端服务器

 配置举例

listen webcluster
    bind *:80
    mode http
    balance roundrobin
    #balance static-rr
    #balance first
    #balance leastconn
    #balance source
    #balance uri
    #balance url_param name,userid
    #balance hdr(User-Agent)
    #hash-type consistent
    cookie WEBCOOKIE insert nocache indirect
    server web1 172.25.254.10:80 cookie lee1 check inter 2 fall 3 rise 5 weight 1
    server web2 172.25.254.20:80 cookie lee2 check inter 2 fall 3 rise 5 weight 1

验证

[root@haproxy ~]# curl -b WEBCOOKIE=lee1 172.25.254.100
172.25.254.10 - index.html
[root@haproxy ~]# curl -b WEBCOOKIE=lee2 172.25.254.100
172.25.254.20 - index.html

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<cond> 
stats admin{if | unless }       #启用stats page中的管理功能

启用状态页

listen stats
    mode http
    bind 0.0.0.0:8888
    stats enable
    log global
    stats uri /status
    stats auth lee:lee

80e7f07f47bb41228d2a5c40921d6626.png

4859a7395d194d12ae0036609c833e26.png 登录状态页

pid = 3698 (process #2, nbproc = 2, nbthread = 2)

#pid为当前pid号,process为当前进程号,nbproc和nbthread为一共多少进程和每个进程多少个线程

uptime = 0d 0h00m08s #启动了多长时间

system limits: memmax = unlimited; ulimit-n = 131124 #系统资源限制:内存/最大打开文件数/

maxsock = 131124; maxconn = 65536; maxpipes = 0 #最大socket连接数/单进程最大连接数/最大管道数maxpipes

current conns = 1; current pipes = 0/0;

conn rate = 1/sec #当前连接数/当前管道数/当前连接速率 (取决于访问量: 访问量越大,值越大)

Running tasks: 1/9;

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 or backup DOWN for maintenance (MAINT) #active或者backup服务器 手动下线的
active or backup SOFT STOPPED for maintenance #active或者backup被认为软下线(人为将weight改成0)

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:拒绝回复量

ip透传

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

layer 4 与 layer 7

四层ip透传与七层ip透传

四层:IP+PORT转发

七层:协议+内容交换

四层负载

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

七层代理

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

七层ip透传

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

HAProxy配置


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

 例:

[root@webserver1 ~]# systemctl disable nginx.service 
Removed "/etc/systemd/system/multi-user.target.wants/nginx.service".
[root@webserver1 ~]# systemctl stop nginx.service

[root@webserver1 ~]# dnf install httpd -y
[root@webserver1 ~]# echo webserver1 172.25.254.10 > /var/www/html/html.index
[root@webserver1 ~]# systemctl start httpd


验证
172.25.254.10 - index.html
[root@haproxy ~]# curl 172.25.254.100
172.25.254.20 - index.html
[root@haproxy ~]# curl 172.25.254.100
172.25.254.10 - index.html
[root@haproxy ~]# curl 172.25.254.100
172.25.254.20 - index.html
[root@haproxy ~]# curl 172.25.254.100
172.25.254.10 - index.html

[root@webserver1 ~]# cat /etc/httpd/logs/access_log 
172.25.254.100 - - [11/Aug/2024:22:49:45 +0800] "GET / HTTP/1.1" 403 27 "-" "curl/7.76.1"
172.25.254.100 - - [11/Aug/2024:22:50:06 +0800] "GET / HTTP/1.1" 403 27 "-" "curl/7.76.1"
172.25.254.100 - - [11/Aug/2024:22:50:08 +0800] "GET / HTTP/1.1" 403 27 "-" "curl/7.76.1"
# 没有日志

四层ip透传

开始四层穿透

[root@webserver2 ~]# vim /etc/nginx/nginx.conf
http {
    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@webserver2 ~]# vim /etc/nginx/nginx.conf
    server {
        listen       80 proxy_protocol;

[root@webserver2 ~]# systemctl restart nginx.service 

访问
[root@haproxy ~]# curl 172.25.254.100
172.25.254.20 - index.html

#查看日志
[root@webserver2 ~]# tail /var/log/nginx/access.log 

172.25.254.100 - - [11/Aug/2024:23:07:38 +0800] "GET / HTTP/1.1" 200 27 "-" "curl/7.76.1" "-"
172.25.254.100 - - [11/Aug/2024:23:11:57 +0800] "GET / HTTP/1.1" "172.25.254.100"200 27 "-" "curl/7.76.1" "-"
透传成功
[root@webserver1 ~]# dnf install httpd-manual
[root@webserver1 ~]# systemctl restart httpd


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

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

[root@haproxy ~]# systemctl restart haproxy.service
[root@haproxy ~]# curl 172.25.254.100
172.25.254.10 - index.html
[root@haproxy ~]# curl 172.25.254.100
172.25.254.20 - index.html
[root@haproxy ~]# curl 172.25.254.100
172.25.254.10 - index.html
[root@haproxy ~]# curl 172.25.254.100
172.25.254.20 - index.html

查看日志
nginx
[root@webserver2 ~]# tail /var/log/nginx/access.log 
172.25.254.100 - - [11/Aug/2024:23:11:57 +0800] "GET / HTTP/1.1" "172.25.254.100"200 27 "-" "curl/7.76.1" "-"
172.25.254.100 - - [11/Aug/2024:23:18:04 +0800] "GET / HTTP/1.1" "172.25.254.100"200 27 "-" "curl/7.76.1" "-"
172.25.254.100 - - [11/Aug/2024:23:18:06 +0800] "GET / HTTP/1.1" "172.25.254.100"200 27 "-" "curl/7.76.1" "-"

web服务器日志格式配置

配置web服务器,记录负载均衡透传的客户端IP地址

参数Forwarded

[root@webserver1 ~]# vim /etc/httpd/conf/httpd.conf 
###省略###
 LogFormat "%{X-Forwarded-For}i %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
#combined 混合形式,全部控制

验证
[root@haproxy ~]# curl 172.25.254.100
172.25.254.20 - index.html
[root@haproxy ~]# curl 172.25.254.100
172.25.254.10 - index.html
[root@haproxy ~]# 

# 查看日志
[root@webserver1 ~]# cat /etc/httpd/logs/access_log 
172.25.254.100 - - [11/Aug/2024:22:49:45 +0800] "GET / HTTP/1.1" 403 27 "-" "curl/7.76.1"
172.25.254.100 - - [11/Aug/2024:22:50:06 +0800] "GET / HTTP/1.1" 403 27 "-" "curl/7.76.1"
172.25.254.100 - - [11/Aug/2024:22:50:08 +0800] "GET / HTTP/1.1" 403 27 "-" "curl/7.76.1"
172.25.254.100 172.25.254.100 - - [11/Aug/2024:22:55:57 +0800] "GET / HTTP/1.1" 403 27 "-" "curl/7.76.1"

ACL(访问控制列表)

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

 ACL 配置选项

#用ac1来定义或声明一个ac1 
acl <aclname>    <criterion> [f1ags]   [operator]   [<value>]
ac1 名称匹配规范   匹配模式    匹配模式    具体操作符   操作对象类型

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-flags 匹配模式

-i   不区分大小写
-m   使用指定的正则表达式匹配方法
-n   不做DNS解析
-u   禁止ac1重名,否则多个同名ACL匹配或关系

ACL-operator 操作对象

The ACL engine can match these types against patterns of the following types
-Boolean #布尔值-integer or integer range #整数或整数范围,比如用于匹配端口范围
-IP addressnetwork #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-criterion 匹配规范

定义ACL匹配规范,即判断条件

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

frontend webcluster
    bind *:80
    mode http
    acl test hdr(dom) -i www.timinglee.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 

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

 hdr(<string>)用于测试请求头部首部指定内容

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

[root@haproxy ~]# curl 172.25.254.100
172.25.254.10 - index.html
[root@haproxy ~]# curl 172.25.254.100
172.25.254.10 - index.html
[root@haproxy ~]# curl 172.25.254.100
172.25.254.10 - index.html

hdr(<string>)用于测试请求头部首部指定内容

frontend webcluster
    bind *:80
    mode http
    acl test hdr_beg(host) -i bbs
    use_backend webcluster-host if test
    default_backend default-host

配置前做好wndows解析

988d3a51800f4083b3ef540860f596d4.png

base:string

frontend webcluster
    bind *:80
    mode http
    #acl test hdr_beg(host) -i lee
    acl test base_sub -m sub bbs
    use_backend webcluster-host if test
    default_backend default-host

验证
[root@haproxy ~]# curl www.test.com
webserver2 - 172.25.254.20

[root@webserver1 ~]# mkdir /var/www/html/lee -p
[root@webserver1 ~]# echo 172.25.254.10 lee > /var/www/html/lee/index.html


[root@webserver1 ~]# curl 172.25.254.10/lee/index.html
172.25.254.10 lee
frontend webcluster
    bind *:80
    mode http
    #acl test hdr_beg(host) -i bbs
    #acl test base_sub -m sub lee
    acl test base_reg -i lee/$
    use_backend webcluster-host if test
    default_backend default-host

[root@haproxy ~]# curl www.test.com/lee/
172.25.254.10 lee

path:string

frontend webcluster
    bind *:80
    mode http
    #acl test hdr_beg(host) -i bbs
    #acl test base_sub -m sub lee
    #acl test base_reg -i lee/$
    acl test path_sub -m sub lee
    use_backend webcluster-host if test
    default_backend default-host

同一网址,不同路径,访问的同一主机
[root@haproxy ~]# curl www.timimglee.org/lee/
172.25.254.10 lee

[root@haproxy ~]# curl www.test.com lee/
172.25.254.10 lee

ACL示例-域名匹配

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


[root@haproxy ~]# curl www.timimglee.org
webserver1 - 172.25.254.10 

[root@haproxy ~]# curl www.test.com 
webserver2 - 172.25.254.20

ACL示例-基于源ip或子网调度方向


frontend webcluster
    bind *:80
    mode http
    acl ctrl_ip src -i 172.25.254.1 172.25.254.20 192.168.0.0/24
    use_backend webcluster-host if ctrl_ip
    default_backend default-host

符合条件
[root@webserver2 ~]# curl 172.25.254.100
172.25.254.10 - index.html
不符合
[root@haproxy ~]# curl 172.25.254.100
172.25.254.20 - index.html


拒绝

frontend webcluster
    bind *:80
    mode http
    acl ctrl_ip src -i 172.25.254.1 172.25.254.20 192.168.0.0/24
    #use_backend webcluster-host if ctrl_ip
    http-reqoest deny if ctrl_ip
    default_backend default-host

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

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

[root@webserver1 ~]# systemctl restart httpd

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


[root@haproxy ~]# vim /etc/haproxy/haproxy.cfg 
frontend webcluster
    bind *:80
    mode http
    acl static path_end -i .html .jpg .png .css .js
    acl php    path_end -i .php
    #use_backend webcluster-host if ctrl_ip
    use_backend default-host if php
    default_backend default-host
[root@haproxy ~]# systemctl restart haproxy.service 

 验证

 2ac99188ba084a4b9a5b5fb909747a4d.png

自定义haproxy错误界面

对指定的报错进行重定向,进行优雅的显示错误页面

使用errorfile和erroroc指令的两种方法,可以实现自定义各种错误页面

#haproxy默认使用的错误错误页面
[root@haproxy ~]# rpm -ql haproxy24z-2.4.27-1.el7.zenetys.x86_64 | grep -E http$
/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

 基于自定义的错误页面文件

#自定义错误页
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 

示例 

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

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

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

[root@haproxy ~]# vim  /etc/haproxy/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 

    errorfile 503   /etc/haproxy/errorpage/503.http

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

验证

测试:关闭webserver主机,去访问172.25.254.100

a7fa2e4d89ba4deb8844f3cda058f879.png

基于http中定向错误页面

#错误页面重定向

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

#   errorfile 503 /etc/haproxy/errorpage/503.http
    errorloc 503 https://www.baidu.com

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

#浏览器访问172.25.254.100自动跳转到百度

访问172.25.254.100

6c7ada1da6da4e7eb36eb638f7b35936.png

 haproxy四层负载

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


MySQL
Redis
Memcache
RabbitMQ

四层负载示例

注意:如果使用frontend和backend,一定在 frontend 和 backend 段中都指定mode tcp

listen mysql-port
   bind 10.0.0.7:6379
   mode tcp
   balance leastconn
   server server1 10.0.0.17:3306 check
   server server2 10.0.0.27:3306 check backup

HAProxy https 实现

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

#配置HAProxy支持https协议,支持ssl会话;
 bind *:443 ssl crt /PATH/TO/SOME_PEM_FILE 
#指令 crt 后证书文件为PEM格式,需要同时包含证书和所有私钥
 cat demo.key demo.crt > demo.pem 
#把80端口的请求重向定443
 bind *:80
 redirect scheme https if !{ ssl_fc } 

证书制作

[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

https配置示例

haproxy ~]# vim /etc/haproxy/haproxy.cfg
frontend webserver
   bind *:80
   redirect scheme https if !{ ssl_fc }
   mode http
   use_backend webcluster
frontend webserver-https
   bind *:443 ssl crt /etc/haproxy/timinglee.org.pem
   mode http
   use_backend webcluster
backend webcluster
   mode http
   balance roundrobin
   server web1 172.25.254.10:80 check inter 3 fall 3 rise 5
   server web2 172.25.254.20:80 check inter 3 fall 3 rise 5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值