Haproxy是既可以工作在7层也能工作在4层的反代工具.
Haproxy的功能:
- 路由HTTP请求到后端服务器,基于cookie作会话绑定.
- 能够将多个请求反代至后端主机完成负载均衡的效果.
- 主服务器失败时能自动切换到备服务器上.
- 接受特殊的端口连接完成服务监控
- 拒绝新连接时不会关闭已经连接的请求.
- 在两个方向上添加、修改和删除HTTP首部
- 根据特定匹配条件阻止相应请求.
- 通过一个URI接口web应用程序为通过身份验证的用户提供报告详细状态.
- 虽然主要提供http反代,但也能反代几乎所有基于tcp的协议
- 有强大的后端主机健康检测功能.
- 支持 单一进程模型,事件驱动,弹性二叉树;
Haproxy程序环境(目前有这四个版本:1.4, 1.5, 1.6, 1.7dev) Haproxy1.5官方文档
配置文件: /etc/haproxy/haproxy.cfg
Unit File: /usr/lib/systemd/system/haproxy.service (CentOS7)
主程序: /usr/sbin/haproxy
日志管理辅助: /usr/bin/halog
网段计算辅助文件: /usr/bin/iprange
内建的错误页文件:
/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
Haproxy配置文件剖析
global: 全局配置段,
proxles 代理配置段如下:
--- defaults
--- frontend
--- backend
--- listen
Haproxy简单体验
启动ibm1 ibm2上的httpd服务后再次访问
Haproxy详细配置
golbal配置参数
进程及安全配置相关的参数
性能调整相关的参数
Debug相关的参数
1.启用日志
log
:日志服务器地址;
[len]:每行日志记录的最大长度;
: 设备
[max level [min level]]: 记录日志级别
ca-base:
Assigns a default directory to fetch SSL CA certificates and CRLs from when a relative path is used with "ca-file" or "crl-file" directives.
crt-base:
Assigns a default directory to fetch SSL certificates from when a relative path is used with "crtfile" directives.
编辑/etc/rsyslog.conf文件
重启rsyslog服务:systemctl restart rsyslog.service
再次访问haproxy就能在指定日志文件记录日志了,如下图.
2. 性能调整(大都不需要自己调整,系统默认最优化)
nbproc
ulimit-n
maxconn
maxconnrate
maxcomprate
maxcompcpuusage
maxsslconn
maxsslrate
noepoll: 这个不能开启
spread-checks <0..50, in percent>: 分散后端RS的健康状态检测请求
tune.rcvbuf.client
tune.rcvbuf.server
tune.sndbuf.client
tune.sndbuf.server
tune.ssl.lifetime
3. 用户列表
userlist
group
user
userlist L1
group G1 users tiger,scott
group G2 users xdb,scott
user tiger password $6$k6y3o.eP$JlKBx9za9667qe4(...)xHSwRv6J.C0/D7cV91
user scott insecure-password elgato
user xdb insecure-password hello
userlist L2
group G1
group G2
user tiger password $6$k6y3o.eP$JlKBx(...)xHSwRv6J.C0/D7cV91 groups G1
user scott insecure-password elgato groups G1,G2
user xdb insecure-password hello groups G2
...
** 4.haproxy同步集群 **
peers
disabled
enable
peer
示例:
peers mypeers
peer haproxy1 192.168.0.1:1024
peer haproxy2 192.168.0.2:1024
peer haproxy3 10.2.0.1:1024
backend mybackend
mode tcp
balance roundrobin
stick-table type ip size 20k peers mypeers
stick on src
server srv1 192.168.0.30:80
server srv2 192.168.0.31:80
部分代理配置参数(关键字)说明
mode { tcp|http|health }: defaults frontend listen backend都可用.设置haproxy工作的模式(共3种),到底是工作在应用层还是传输层. health指工作为健康状态检查响应模式,当请求到达时仅回应“OK”即断开连接;
bind [
bind /
listen http_proxy
bind :80,:443
bind 10.0.0.1:10080,10.0.0.1:10443
bind /var/run/ssl-frontend.sock user root mode 600 accept-proxy
listen http_https_proxy
bind :80
bind :443 ssl crt /etc/haproxy/site.pem
listen http_https_proxy_explicit
bind ipv6@:80
bind ipv4@public_ssl:443 ssl crt /etc/haproxy/site.pem
bind [email protected] user root mode 600 accept-proxy
listen external_bind_app1
bind fd@${FD_APP1}
acl
balance
balance url_param [check_post]: 可用在defaults,listen,backend中,定义一个在后端使用的负载平均算法.
算法中的概念:
动态-->权重运行时调整 支持慢启动
hash-type
map-based:哈希表是一个包含了所有的可活动的主机列表
consistent: 一致性哈希,其数据结构是"树"
算法:
roundrobin: 动态,加权轮询,权重默认为1.其对最多能维持4095后端活动主机.
static-rr: 静态算法,不支持权重的运行时调整,但后端主机数量无限制.
leastconn: 动态算法,拥有最少连接数的后端接受请求.
first: 忽略权重,后端服务器名称标识符最短的优先
source:动态算法或静态算法 原地址哈希,是否动态取决于hash-type
uri: 根据uri请求路径(下面uri格式中黑体部分)进行调度,适合后端主机是缓存服务器,是否动态取决于hash-type
uri格式:scheme://user:pwd@host:port/uri;params?query#fragment
**url_param: **对用户请求的url中的部分中的指定的参数的值作hash计算,并由服务器总权重相除以后派发至某挑出的服务器.
hdr(): The HTTP headerwill be looked up in each HTTP request.指定的http首部将会被取出做hash计算,并由服务器总权重相除以后派发至某挑出的服务器;没有有效值的会被轮询调度.
maxconn
stats admin { if | unless }
Enable statistics admin level if/unless a condition is matched
stats realm
stats auth
stats uri
stats refresh
stats hide-version: 设置隐藏haproxy版本号
stats enable: 可在defaults,frontend,listen,backend中使用,在缺少其他参数配置时会默认如下
- stats uri : /haproxy?stats
- stats realm : "HAProxy Statistics"
- stats auth : no authentication
- stats scope : no restriction
示例如下:
# public access (limited to this backend only)
backend public_www
server srv1 192.168.0.1:80
stats enable
stats hide-version
stats scope .
stats uri /admin?stats
stats realm Haproxy\ Statistics
stats auth admin1:AdMiN123
stats auth admin2:AdMiN321
# internal monitoring access (unlimited)
backend private_monitoring
stats enable
stats uri /admin?stats
stats refresh 5s
server
addr
: 健康状态检测的专用地址
backup
check: 执行健康状态检测.默认为传输层检测.需要执行应用层检测需要"httpchk","smtpchk", "mysql-check", "pgsql-check" and "ssl-hello-chk"
inter: 时间间隔,默认为2秒
rise: 判定为"健康"状态需要检测的次数,默认2次.
fall: 判定为"不健康"状态需要检测的次数,默认为3次.
port:健康状态检测时使用的端口.
注意:默认为传输层检测,即探测端口是否能响应;需要执行应用层检测,则需要httpchk, smtpchk, mysql-check, pgsql-check, ssl-hello-chk;
cookie: 为当前server指定其cookie值,此值会在收到请求报文时进行检测,其功能在于实现基于cookie会话保持.
disabled:将些server标记为不可用,进入维护模式.
id: 为此server设置保持id(正数且唯一),当调度算法first为根据这个数值较小的id先进行调度
maxconn: 当前server的最大并发连接数.
maxqueue: 当前server的等待队列的最大长度.
redir: 将发往当前server的所有请求会被重定向到别的主机(给出 scheme://host即可)如下示例:
server srv1 192.168.1.1:80 redir http://image1.mydomain.com check
weight: 当前server的权重.
option httpchk: uri默认为主页
option httpchk
option httpchk
option httpchk
以上在defaults,listen,backend可用,开启HTTP协议,检查服务器健康状态.
# Relay HTTPS traffic to Apache instance and check service availability
# using HTTP request "OPTIONS * HTTP/1.1" on port 80.
backend https_relay
mode tcp
option httpchk OPTIONS * HTTP/1.1\r\nHost:\ www
server apache1 192.168.1.1:443 check port 80
http-check expect [!]
match为status或string
示例: http-check expect status 200
cookie
可在defaults,listen,backend使用,启用基于cookie的会话绑定,需要结合server参数的cookie参数一起实现
rewrite: 这个关键字表明 这个将由server提供的cookie以及haproxy将会修改这个cookie,如何修改呢?将server的id放入. 当由"Set-cookie"与"Cache-control"组成的复杂的首部离开应用程序时这个模式会便于管理.
示例1:
cookie JSESSIONID prefix
cookie SRV insert indirect nocache
cookie SRV insert postonly indirect
cookie SRV insert indirect nocache maxidle 30m maxlife 8h
示例2(结合server的cookie参数),效果如下截图,会把server发给client的cookie添加一个键值对:
cookie WEBSRV insert indirect nocache
server web1 10.1.1.78:80 check weight 2 maxconn 5000 cookie WEB1
server web2 10.1.1.79:80 check weight 1 maxconn 3000 cookie WEB2
default_backend
与日志相关的
log global
log
no log
为frontend或backend定义日志记录机制
Tq: 等待客户端发送一个完整的HTTP请求总共花费的时间(毫秒),但不计算数据,-1表示未连接
Tw: 在等待各队列时所花费的总时间(毫秒) It can be "-1" if the connection was aborted before reaching the queue.
Tc: 等待与最终服务器创建连接所需要的总时间(毫秒) 包含重试的It can be "-1" if the request was aborted before a connection could be established.
Tr:等待服务器发送一个完整的HTTP响应总共花费的时间(毫秒),但不计算数据
Tt
capture request header
capture response header
示例:
capture response header Content-length len 9
capture response header Location len 15
错误页面自定义相关参数
errorfile
:Return a file contents instead of errors generated by HAProxy,可定义在defaults,frontend,listen,backend中,返回一个自定义文件内容以替代HAProxy生成的错误,示例如下
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
errorloc302
:Return an HTTP redirection to a URL instead of errors generated by HAProxy,可用在defaults,frontend,listen,backend中,返回一个HTTP重定向而不是由HAProxy生成的错误页面.
示例 errorloc 503 http://10.1.1.77:8090/errorpagetest.html
与修改请求或响应报文相关
option forwardfor [ except
Enable insertion of the X-Forwarded-For header to requests sent to servers允许插入一个X-Forwarded-For请求首部到server.X-Forwarded-For代表HTTP 请求端真实 IP X-Forwarded-For: client, proxy1, proxy2
rspadd rspadd X-Via:\ Haproxy
Add a header at the end of the HTTP response
reqadd
Add a header at the end of the HTTP request
reqdel
reqidel
Delete all headers matching a regular expression in an HTTP request
rspdel
rspidel
Delete all headers matching a regular expression in an HTTP response
示例: rspidel Server.*
删除以Server开头的响应报头.
超时时长相关参数
timeout client
Set the maximum inactivity time on the client side.单位是毫秒
timeout server
Set the maximum inactivity time on the server side.
timeout connect
Set the maximum time to wait for a connection attempt to a server to succeed.
timeout http-keep-alive
Set the maximum allowed time to wait for a new HTTP request to appear面向客户端一侧开启保持连接功能
timeout client-fin
Set the inactivity timeout on the client side for half-closed connections.设置客户端一侧半关闭连接时超时时长
timeout server-fin
Set the inactivity timeout on the server side for half-closed connections.
timeout http-request
Set the maximum allowed time to wait for a complete HTTP request
timeout http-keep-alive
Set the maximum allowed time to wait for a new HTTP request to appear
ACL相关的参数
Haproxy 完全能够胜任从客户端或服务器的请求与响应流中提取数据
Access Control Lists (ACL)提供了一个灵活的解决方案去执行内容转换以及根据从请求或响应或者环境状态做出决策.原理很简单:
- 从数据流,表或环境中提取数据样本
- 有选择性地对这些数据样本做格式转换
- 根据样例生成一个或多个匹配模式
- 只有当样本与匹配模式匹配时才对其执行相应动作
语法格式:acl[flags] [operator] [ ] ...
boolean
integer or integer range
IP address / network
string (exact, substring, suffix, prefix, subdir, domain)
regular expression
hex block
-i : 被模式匹配时忽略字母大小写
-f : 从文件加载模式
-m : use a specific pattern matching method,使用特定的模式匹配方法
-n : forbid the DNS resolutions
-M : load the file pointed by -f like a map file.
-u : force the unique id of the ACL
-- : force end of flags. Useful when a string looks like one of the flags.
operator类型:
数值
eq : true if the tested value equals at least one value
ge : true if the tested value is greater than or equal to at least one value
gt : true if the tested value is greater than at least one value
le : true if the tested value is less than or equal to at least one value
lt : true if the tested value is less than at least one value
字符串
- exact match (-m str) : 精确匹配
- substring match (-m sub) :子串匹配
- prefix match (-m beg) :前缀匹配
- suffix match (-m end) : 后缀匹配
- subdir match (-m dir) : 子目录匹配
- domain match (-m dom) : 域名子串匹配(以.分隔)
条件的逻辑连接
- AND (implicit)
- OR (explicit with the "or" keyword or the "||" operator)
- Negation with the exclamation mark ("!")
根据(源与目标的)IP与端口来设置ACL:
dst : ip
dst_port : integer
src : ip
src_port : integer
示例:
acl myhost src 10.1.0.200
acl myport dst_port 8080
block if !myhost myport
ACL 7(应用)层检查机制用法:
path(路径检查) : string
This extracts the request's URL path, which starts at the first slash and ends before the question mark (without the host part).
ACL derivatives :
path : exact string match
path_beg : prefix match
path_dir : subdir match
path_dom : domain match
path_end : suffix match
path_len : length match
path_reg : regex match
path_sub : substring match
示例:
acl text_file path_end -i .txt
block if text_file
请求行首部检查 :
req.hdr([
This extracts the last occurrence of header
hdr([
[, ]]) : exact string match
hdr_beg([[, ]]) : prefix match
hdr_dir([[, ]]) : subdir match
hdr_dom([[, ]]) : domain match
hdr_end([[, ]]) : suffix match
hdr_len([[, ]]) : length match
hdr_reg([[, ]]) : regex match
hdr_sub([
示例:
acl firefox hdr_reg(User-Agent) -i .*firefox.*
block if firefox
响应行首部检查
res.hdr([
This extracts the last occurrence of header
shdr([
[, ]]) : exact string match
shdr_beg([[, ]]) : prefix match
shdr_dir([[, ]]) : subdir match
shdr_dom([[, ]]) : domain match
shdr_end([[, ]]) : suffix match
shdr_len([[, ]]) : length match
shdr_reg([[, ]]) : regex match
shdr_sub([[, ]]) : substring match
url检查
url : string
This extracts the request's URL as presented in the request.
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
请求方法检查
method : integer + string
acl valid_method method GET HEAD
http-request deny if ! valid_method
注意:HAProxy有众多内建的ACLs,这些ACLs可直接调用,例如LOCALHOST,TRUE,HTTP;
HTTP层访问控制相关的参数:
block { if | unless }
Block a layer 7 request if/unless a condition is matched
阻止符合指定acl的访问请求;
http-request { allow | deny | tarpit | auth [realm
http-response { allow | deny | add-header
示例1:
acl myhost src 10.1.0.67
http-request deny if url_admin !myhost
示例2
acl nagios src 192.168.129.3
acl local_net src 192.168.0.0/16
acl auth_ok http_auth(L1)
http-request allow if nagios
http-request allow if local_net auth_ok
http-request auth realm Gimme if local_net auth_ok
http-request deny
TCP层访问控制相关的参数:
tcp-request connection
Perform an action on an incoming connection depending on a layer 4 condition
示例
tcp-request connection accept if { src -f /etc/haproxy/whitelist.lst } # 这里的花括号部分即是一个acl
tcp-request connection reject if { src_conn_rate gt 10 }
tcp-request connection track-sc0 src
tcp-request content
Perform an action on a new session depending on a layer 4-7 condition
示例:
后端主机调用:
use_backend
Switch to a specific backend if/unless an ACL-based condition is matched.