HAProxy 的 server 参数、 stats 相关参数和 cookie 参数详解(包含其它相关参数 rspadd / rspdel / option / mode / maxconn )

1、实验环境及基础配置请参考如下博客

HAProxy 简单示例及 HAProxy_Log 的简单配置
HAProxy Balance 调度算法详解

1.1 实验拓扑

在这里插入图片描述

2、HAProxy Server 参数

2.1 官方文档说明

点此链接,查看相关官方文档

2.2 常用参数说明

## server <name> <address>[:[port]] [param*]
	## 定义后端主机的各服务器及其选项
						
	## server <name> <address>[:port] [settings ...]
	## default-server [settings ...]
						
	## <name>      # 服务器在haproxy上的内部名称;出现在日志及警告信息中
	## <address>   # 服务器地址,支持使用主机名
	## [:[port]]   # 端口映射;省略时,表示同bind中绑定的端口
	## [param*]    # 参数
		## maxconn <maxconn>   # 当前server的最大并发连接数
		## backlog <backlog>   # 当前server的连接数达到上限后的后援队列长度
		## backup              # 设定当前server为备用服务器
		## check               # 对当前server做健康状态检测
			## addr            # 检测时使用的IP地址
			## port            # 针对此端口进行检测
			## inter <delay>   # 连续两次检测之间的时间间隔,默认为2000ms
			## rise <count>    # 连续多少次检测结果为“成功”才标记服务器为可用;默认为2
			## fall <count>    # 连续多少次检测结果为“失败”才标记服务器为不可用;默认为3
				## 注意:option httpchk,"smtpchk", "mysql-check", "pgsql-check" and ##
				## "ssl-hello-chk" 用于定义应用层检测方法 ##
									
		## cookie <value>      # 为当前server指定其cookie值,用于实现基于cookie的会话黏性
		## disabled            # 标记为不可用
		## on-error <mode>     # 后端服务故障时的行动策略
        	## - fastinter: force fastinter
            ## - fail-check: simulate a failed check, also forces fastinter (default)
            ## - sudden-death: simulate a pre-fatal failed health check, one more failed check will mark a server down, forces fastinter
            ## - mark-down: mark the server immediately down and force fastinter
		## redir <prefix>     # 将发往此server的所有GETHEAD类的请求重定向至指定的URL
		## weight <weight>    # 权重,默认为1	

3、HAProxy stats 相关参数

## stats enable                        # 启用统计页;基于默认的参数启用 stats page
	## - stats uri   : /haproxy?stats
	## - stats realm : "HAProxy Statistics"
	## - stats auth  : no authentication
	## - stats scope : no restriction
						
## stats auth <user>:<passwd>          # 认证时的账号和密码,可使用多次
							
## stats realm <realm>                 # 认证时的 realm
							
## stats uri <prefix>                  # 自定义 stats page uri
							
## stats refresh <delay>               # 设定自动刷新时间间隔
							
## stats admin { if | unless } <cond>  # 启用stats page中的管理功能								

3.1 HAProxy stats 相关参数配置示例

## stats enable           # 启用基于程序编译时默认设置的统计报告,不能用于"frontend"区段
## stats uri              # /haproxy?stats
## stats realm            # "HAProxy Statistics"
## stats auth             # no authentication
## stats scope            # no restriction

## 尽管"stats enable"一条就能够启用统计报告,但还是建议设定其它所有的参数,以免依赖于默认设定而带来非预期后果
backend public_www
    server websrv1 172.16.100.11:80
    stats enable
    stats hide-version                    # 启用统计报告并隐藏HAProxy版本报告,不能用于"frontend"区段
    stats scope   .
    stats uri     /haproxyadmin?stats
    stats realm   Haproxy\ Statistics     # stats auth身份认证时的提示信息。设置的提示信息中,如果有空白字符,则需要转义。仅在与"stats auth"配合使用时有意义
    stats auth    statsadmin:password     # 启用带认证的统计报告功能并授权一个用户帐号和对应的密码(明文)。也就是说,想要查看统计报告需要提供身份和密码。不能用于"frontend"区段。
    stats auth    statsmaster:password  
## stats admin    # 满足指定条件时启用统计报告页面的管理功能,它允许通过web接口启用或禁用后端服务器
	## stats admin { if | unless } <cond>

## 限制仅能在本机打开报告页面时启用管理功能
	backend stats_localhost
	    stats enable
	    stats admin if LOCALHOST
	    
## 定义了仅允许通过认证的用户使用管理功能 
	backend stats_auth
	    stats enable
	    stats auth  haproxyadmin:password
	    stats admin if TRUE
listen stats
	bind :9099
	stats enable
	stats realm HAPorxy\ Stats\ Page
	stats auth admin:admin
	stats admin if TRUE	

4、其它参数

## default_backend <backend>     # 设定默认的backend,用于frontend中
						
## default-server [param*]       # 为backend中的各server设定默认选项;
## maxconn <conns>               # 为指定的frontend定义其最大并发连接数;默认为2000
	Fix the maximum number of concurrent connections on a frontend.  
## mode { tcp|http|health }   # 定义haproxy的工作模式;
	## tcp                    # 基于layer4实现代理;可代理mysql, pgsql, ssh, ssl等协议
	## http                   # 仅当代理的协议为http时使用
	## health                 # 工作为健康状态检查的响应模式,当连接请求到达时回应“OK”后即断开连接

## mode tcp 示例 ##
	listen ssh
		bind :22022
		balance leastconn
		mode tcp
		server sshsrv1 172.16.100.6:22 check
		server sshsrv2 172.16.100.7:22 check
## cookie <name> [ rewrite | insert | prefix ] [ indirect ] [ nocache ]  [ postonly ] [ preserve ] [ httponly ] [ secure ]  [ domain <domain> ]* [ maxidle <idle> ] [ maxlife <life> ]
	## <name> is the name of the cookie which will be monitored, modified or inserted in order to bring persistence.
		## rewirte        # 重写
		## insert         # 插入
		## prefix         # 前缀

## 基于cookie的session sticky的实现 ##
	backend websrvs
		cookie WEBSRV insert nocache indirect
		server srv1 172.16.100.6:80 weight 2 check rise 1 fall 2 maxconn 3000 cookie srv1
		server srv2 172.16.100.7:80 weight 1 check rise 1 fall 2 maxconn 3000 cookie srv2		

## 在backend服务器组启用cookie功能,以便实现cookie绑定。需要同时设置server指令中的cookie选项
## 当客户端绑定cookie对应的后端服务器宕机后,应该为此客户端重新调度一个后端server,否则将打不开页面
## 这时需要使用option redispatch,表示当找不到cookie对应的服务器时分配新的服务器给客户端
## option forwardfor [ except <network> ] [ header <name> ] [ if-none ]
	Enable insertion of the X-Forwarded-For header to requests sent to servers
	## except <network>:可选参数,当指定时表示请求中的源地址能匹配此网络时禁用此功能
	## header <name>:可选参数,自定义首部名,如"X-Client"来替代"X-Forwarded-For"。有些独特的web服务器的确需要一个独特的首部
	## if-none:仅在此首部不存在时才将其添加至请求报文首部

## 允许在发往服务器的请求首部中插入"X-Forwarded-For"首部
	## HAProxy工作于反向代理模式,其发往服务器的请求中的客户端IP均为HAProxy主机的地址而非真正客户端的地址
	## 这会使得服务器端的日志信息记录不了真正的请求来源,"X-Forwarded-For"首部则可用于解决此问题
	## HAProxy可以向每个发往服务器的请求上添加此首部,并以客户端IP为其value
	
## 在由haproxy发往后端主机的请求报文中添加“X-Forwarded-For”首部,其值前端客户端的地址;用于向后端主发送真实的客户端IP
	## [ except <network> ]      # 请求报请来自此处指定的网络时不予添加此首部
	## [ header <name> ]         # 使用自定义的首部名称,而非“X-Forwarded-For”

## 示例 ## 
	frontend www
	    mode http
	    option forwardfor except 127.0.0.1
## errorfile <code> <file>
	## Return a file contents instead of errors generated by HAProxy
						
	## <code>:is the HTTP status code. Currently, HAProxy is capable of  generating codes 200, 400, 403, 408, 500, 502, 503, and 504.
	## <file>:designates a file containing the full HTTP response.
						
## 示例 ## 
	## errorfile 400 /etc/haproxy/errorfiles/400badreq.http
	## errorfile 408 /dev/null  # workaround Chrome pre-connect bug
	## errorfile 403 /etc/haproxy/errorfiles/403forbid.http
	## errorfile 503 /etc/haproxy/errorfiles/503sorry.http	
## errorloc <code> <url>
## errorloc302 <code> <url>
	## errorloc 403 http://www.tang.com/error_pages/403.html
## reqadd  <string> [{if | unless} <cond>]
	## Add a header at the end of the HTTP request
						
## rspadd <string> [{if | unless} <cond>]
	## Add a header at the end of the HTTP response

## 示例 ##
	## rspadd X-Via:\ HAPorxy

## 满足条件时向请求首部或响应首部的尾端添加自定义的字段
## 条件可选,当不给定条件时表示所有的请求首部或响应首部尾端都添加字段
## 其中string包含了字段名和字段值,当然,既然是自定义,值肯定是可以省略的。注意,空白字符需要转义
## reqdel  <search> [{if | unless} <cond>]
## reqidel <search> [{if | unless} <cond>]  (ignore case)
	Delete all headers matching a regular expression in an HTTP request
						
## rspdel  <search> [{if | unless} <cond>]
## rspidel <search> [{if | unless} <cond>]  (ignore case)
	Delete all headers matching a regular expression in an HTTP response
						
## 示例 ##
	## rspidel  Server.*

5、stats 相关参数示例

5.1 HAProxy cfg 文件配置

[root@Tang ~]# vim /etc/haproxy/haproxy.cfg 
listen stats                             # 进行 Listen 名称定义
    bind *:7777                          # 为了安全,定义不常用的端口号进行 status 界面访问
    stats enable                         # 使能 stats
    stats uri /tang?status               # 定义 ststs 的访问 uri
    stats realm HAPorxy\ Stats\ Page     
    stats auth tang:tang                 # 定义认证时使用的用户名和密码
    stats admin if TRUE

frontend web
    bind *:80
    default_backend     websrvs

backend websrvs
    balance roundrobin
    server srv1 172.16.141.209:80 weight 1 check
    server srv2 172.16.141.209:8080 weight 1 check
[root@Tang ~]# systemctl restart haproxy     # 重启服务
[root@Tang ~]# ss -tnl                       # 查看端口是否监听
State       Recv-Q Send-Q                     Local Address:Port                                    Peer Address:Port              
LISTEN      0      128                                    *:80                                                 *:*                  
LISTEN      0      128                                    *:22                                                 *:*                  
LISTEN      0      100                            127.0.0.1:25                                                 *:*                  
LISTEN      0      128                                    *:7777                                               *:*                  
LISTEN      0      25                                     *:514                                                *:*                  
LISTEN      0      128                                   :::22                                                :::*                  
LISTEN      0      25                                    :::514                                               :::*                  

5.2 登陆页面,进行访问

在这里插入图片描述
在这里插入图片描述

6、ccokie 参数示例

6.1 cfg 配置文件修改

[root@Tang ~]# vim /etc/haproxy/haproxy.cfg 
listen stats
    bind *:7777
    stats enable
    stats uri /tang?status
    stats realm HAPorxy\ Stats\ Page
    stats auth tang:tang
    stats admin if TRUE

frontend web
    bind *:80
    default_backend     websrvs

backend websrvs
    cookie WEBSRVS insert nocache indirect    # 定义 cookie 名称
    server srv1 172.16.141.209:80 weight 1 weight 2 check rise 1 fall 2 maxconn 3000 cookie srv1-tangtang
    server srv2 172.16.141.209:8080 weight 1 weight 2 check rise 1 fall 2 maxconn 3000 cookie srv2-tangtang
[root@Tang ~]# systemctl restart haproxy     # 重启服务
[root@Tang ~]# ss -tnl                       # 查看端口是否监听
State       Recv-Q Send-Q                     Local Address:Port                                    Peer Address:Port              
LISTEN      0      128                                    *:80                                                 *:*                  
LISTEN      0      128                                    *:22                                                 *:*                  
LISTEN      0      100                            127.0.0.1:25                                                 *:*                  
LISTEN      0      128                                    *:7777                                               *:*                  
LISTEN      0      25                                     *:514                                                *:*                  
LISTEN      0      128                                   :::22                                                :::*                  
LISTEN      0      25                                    :::514                                               :::*                  

6.2 进行访问

在这里插入图片描述

7、rspadd 和 rspdel 参数示例

7.1 原访问页面

在这里插入图片描述

7.2 HAProxy cfg 文件修改

[root@Tang ~]# vim /etc/haproxy/haproxy.cfg 
listen stats
    bind *:7777
    stats enable
    stats uri /tang?status
    stats realm HAPorxy\ Stats\ Page
    stats auth tang:tang
    stats admin if TRUE

frontend web
    bind *:80
    default_backend     websrvs
    rspadd X-Via:\ Tangtang's\ HAPorxy     # 增加相应的 X-Via 字段信息(空格前要使用 \ 进行转义)
    rspdel  Server.*                       # 删除关于服务器的相关字段信息

backend websrvs
    cookie WEBSRVS insert nocache indirect
    server srv1 172.16.141.209:80 weight 1 weight 2 check rise 1 fall 2 maxconn 3000 cookie srv1-tangtang
    server srv2 172.16.141.209:8080 weight 1 weight 2 check rise 1 fall 2 maxconn 3000 cookie srv2-tangtang
[root@Tang ~]# systemctl restart haproxy     # 重启服务
[root@Tang ~]# ss -tnl                       # 查看端口是否监听
State       Recv-Q Send-Q                     Local Address:Port                                    Peer Address:Port              
LISTEN      0      128                                    *:80                                                 *:*                  
LISTEN      0      128                                    *:22                                                 *:*                  
LISTEN      0      100                            127.0.0.1:25                                                 *:*                  
LISTEN      0      128                                    *:7777                                               *:*                  
LISTEN      0      25                                     *:514                                                *:*                  
LISTEN      0      128                                   :::22                                                :::*                  
LISTEN      0      25                                    :::514                                               :::*                  

7.3 再次进行访问(发现其 Server 相关信息已被删除,并增加了相关信息)

在这里插入图片描述

8、option 参数示例

8.1 HTTPD 服务器配置文件中的原日志格式定义

[root@Tang-1 ~]# ipinfo                        # 查看地址
enp1s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.16.141.209  netmask 255.255.255.0  broadcast 172.16.141.255
[root@Tang-1 ~]# vim /etc/httpd/conf/httpd.conf
<IfModule log_config_module>
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined      # 定义 combined 格式
    CustomLog "logs/access_log" combined       # 绑定日志格式为 combined
</IfModule>
[root@Tang-1 ~]# systemctl restart httpd       # 重启服务

8.2 HTTPD 服务器原日志格式,不包含实际的用户地址

[root@Tang-1 ~]# tail -3 /var/log/httpd/access_log
172.16.141.252 - - [07/Nov/2019:15:43:15 +0800] "GET / HTTP/1.1" 304 - "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36"
172.16.141.252 - - [07/Nov/2019:16:04:10 +0800] "GET / HTTP/1.1" 304 - "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36"
172.16.141.252 - - [07/Nov/2019:16:07:04 +0800] "GET / HTTP/1.1" 304 - "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36"

8.3 HTTPD 服务器原日志格式进行修改,包含实际的用户地址

[root@Tang-1 ~]# ipinfo                        # 查看地址
enp1s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.16.141.209  netmask 255.255.255.0  broadcast 172.16.141.255
[root@Tang-1 ~]# vim /etc/httpd/conf/httpd.conf
<IfModule log_config_module>
    LogFormat "%{X-Forwarded-For}i %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined      
    										   # 定义 combined 格式,包含 X-Forwarded-For 参数
    CustomLog "logs/access_log" combined       # 绑定日志格式为 combined
</IfModule>
[root@Tang-1 ~]# systemctl restart httpd       # 重启服务

8.4 HAProxy 服务器的 cfg 文件配置

[root@Tang ~]# vim /etc/haproxy/haproxy.cfg 
listen stats
    bind *:7777
    stats enable
    stats uri /tang?status
    stats realm HAPorxy\ Stats\ Page
    stats auth tang:tang
    stats admin if TRUE

frontend web
    bind *:80
    default_backend     websrvs
  	rspadd X-Via:\ Tangtang's\ HAPorxy
    rspdel  Server.*
    option forwardfor                        # 添加 option 字段信息
    
backend websrvs
    cookie WEBSRVS insert nocache indirect    # 定义 cookie 名称
    server srv1 172.16.141.209:80 weight 1 weight 2 check rise 1 fall 2 maxconn 3000 cookie srv1-tangtang
    server srv2 172.16.141.209:8080 weight 1 weight 2 check rise 1 fall 2 maxconn 3000 cookie srv2-tangtang
[root@Tang ~]# systemctl restart haproxy     # 重启服务
[root@Tang ~]# ss -tnl                       # 查看端口是否监听
State       Recv-Q Send-Q                     Local Address:Port                                    Peer Address:Port              
LISTEN      0      128                                    *:80                                                 *:*                  
LISTEN      0      128                                    *:22                                                 *:*                  
LISTEN      0      100                            127.0.0.1:25                                                 *:*                  
LISTEN      0      128                                    *:7777                                               *:*                  
LISTEN      0      25                                     *:514                                                *:*                  
LISTEN      0      128                                   :::22                                                :::*                  
LISTEN      0      25                                    :::514                                               :::*                  

8.5 重新进行访问后,HTTPD 服务器新日志查看,已经包含了用户的实际访问地址

[root@Tang-1 ~]# tail -3 /var/log/httpd/access_log
172.16.141.99 172.16.141.252 - - [07/Nov/2019:16:24:30 +0800] "GET / HTTP/1.1" 304 - "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36"
172.16.141.99 172.16.141.252 - - [07/Nov/2019:16:24:30 +0800] "GET / HTTP/1.1" 304 - "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36"
172.16.141.99 172.16.141.252 - - [07/Nov/2019:16:24:32 +0800] "GET / HTTP/1.1" 304 - "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36"
发布了158 篇原创文章 · 获赞 7 · 访问量 9755

猜你喜欢

转载自blog.csdn.net/weixin_44983653/article/details/102953483