HAProxy 是一款提供高可用性、负载均衡以及基于TCP(第四层)和HTTP(第七层)应用的代理软件。
相较与 Nginx,HAProxy 更专注与反向代理,因此它可以支持更多的选项,更精细的控制,更多的健康状态检测机制和负载均衡算法。
四层和七层负载均衡的区别:
四层:
- 通过分析IP层及TCP/UDP层的流量实现的基于“IP+端口”的负载均衡。
七层:
-
可以根据报内容,再配合负载均衡算法来选择后端服务器,不但可以根据“ip+端口”方式进行负载分流,还可以根据网站的URL,访问域名,浏览器类别,语言等决定负载均衡的策略。
-
七层负载均衡模式下,负载均衡与客户端及后端的服务器会分别建立一次TCP连接,而在四层负载均衡模式下,仅建立一次TCP连接;七层负载均衡对负载均衡设备的要求更高,处理能力也低于四层负载均衡。
程序环境:
- 主程序:/usr/sbin/haproxy
- 主配置文件:/etc/haproxy/haproxy.cfg
- Unit file:/usr/lib/systemd/system/haproxy.service
配置文件:/etc/haproxy/haproxy.cfg
配置段:
global:全局配置段
进程管理及安全配置相关的参数
性能调整相关参数
Debug参数
proxies:代理配置段
defaults:为frontend, listen, backend提供默认配置;
fronted:前端,相当于nginx, server {}
backend:后端,相当于nginx, upstream {}
listen:同时拥前端和后端
注意:所有代理的名称只能使用大写字母、小写字母、数字、-(中线)、_(下划线)、.(点号)和:(冒号)。此外,ACL名称会区分字母大小写
global:全局配置段
* 进程管理及安全配置相关的参数
– chroot <jail dir>:修改haproxy的工作目录至指定的目录并在放弃权限之前执行chroot()操作,可以提升haproxy的安全级别,不过需要注意的是要确保指定的目录为空目录且任何用户均不能有写权限; – daemon:让haproxy以守护进程的方式工作于后台,其等同于“-D”选项的功能,当然,也可以在命令行中以“-db”选项将其禁用; – gid <number>:以指定的GID运行haproxy,建议使用专用于运行haproxy的GID,以免因权限问题带来风险; – group <group name>:同gid,不过指定的组名; – log <address> <facility> [max level [min level]]:定义全局的syslog服务器,最多可以定义两个; – log-send-hostname [<string>]:在syslog信息的首部添加当前主机名,可以为“string”指定的名称,也可以缺省使用当前主机名; – nbproc <number>:指定启动的haproxy进程的个数,只能用于守护进程模式的haproxy;默认只启动一个进程,鉴于调试困难等多方面的原因,一般只在单进程仅能打开少数文件描述符的场景中才使用多进程模式; – pidfile: – uid:以指定的UID身份运行haproxy进程; – ulimit-n:设定每进程所能够打开的最大文件描述符数目,默认情况下其会自动进行计算,因此不推荐修改此选项;Linux默认单进程打开文件数为1024个 – user:同uid,但使用的是用户名; – stats:用户访问统计数据的接口 – node:定义当前节点的名称,用于HA场景中多haproxy进程共享同一个IP地址时; – description:当前实例的描述信息;
* 性能调整相关的参数
– maxconn <number>:设定每个haproxy进程所接受的最大并发连接数,其等同于命令行选项“-n”;“ulimit -n”自动计算的结果正是参照此参数设定的; – maxpipes <number>:haproxy使用pipe完成基于内核的tcp报文重组,此选项则用于设定每进程所允许使用的最大pipe个数;每个pipe会打开两个文件描述符,因此,“ulimit -n”自动计算时会根据需要调大此值;默认为maxconn/4,其通常会显得过大; – noepoll:在Linux系统上禁用epoll机制; – nokqueue:在BSE系统上禁用kqueue机制; – nopoll:禁用poll机制; – nosepoll:在Linux禁用启发式epoll机制; – nosplice:禁止在Linux套接字上使用内核tcp重组,这会导致更多的recv/send系统调用;不过,在Linux 2.6.25-28系列的内核上,tcp重组功能有bug存在; – spread-checks <0..50, in percent>:在haproxy后端有着众多服务器的场景中,在精确的时间间隔后统一对众服务器进行健康状况检查可能会带来意外问题;此选项用于将其检查的时间间隔长度上增加或减小一定的随机时长; – tune.bufsize <number>:设定buffer的大小,同样的内存条件小,较小的值可以让haproxy有能力接受更多的并发连接,较大的值可以让某些应用程序使用较大的cookie信息;默认为16384,其可以在编译时修改,不过强烈建议使用默认值; – tune.chksize <number>:设定检查缓冲区的大小,单位为字节;更大的值有助于在较大的页面中完成基于字符串或模式的文本查找,但也会占用更多的系统资源;不建议修改; – tune.maxaccept <number>:设定haproxy进程内核调度运行时一次性可以接受的连接的个数,较大的值可以带来较大的吞吐率,默认在单进程模式下为100,多进程模式下为8,设定为-1可以禁止此限制;一般不建议修改; – tune.maxpollevents <number>:设定一次系统调用可以处理的事件最大数,默认值取决于OS;其值小于200时可节约带宽,但会略微增大网络延迟,而大于200时会降低延迟,但会稍稍增加网络带宽的占用量; – tune.maxrewrite <number>:设定为首部重写或追加而预留的缓冲空间,建议使用1024左右的大小;在需要使用更大的空间时,haproxy会自动增加其值; – tune.rcvbuf.client <number>: – tune.rcvbuf.server <number>:设定内核套接字中服务端或客户端接收缓冲的大小,单位为字节;强烈推荐使用默认值; – tune.sndbuf.client: – tune.sndbuf.server:
proxies:代理配置段
- defaults段为frontend, listen, backend提供默认配置;
- frontend段用于定义一系列监听的套接字,这些套接字可接受客户端请求并与之建立连接。
- backend段用于定义一系列“后端”服务器,代理将会将对应客户端的请求转发至这些服务器。
- listen段通过关联“frontend”和“backend”定义了一个完整的代理,通常只对TCP流量有用
bind:定义一个或几个监听的套接字,绑定ip及端口
bind [<address>]:<port_range> [, …] [param*]
例:
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
balance: 定义负载均衡调度算法,可用于“defaults”、“listen”和“backend”组
balance <algorithm> [ <arguments> ]
balance url_param <param> [check_post]
HAProxy 负载均衡调度算法:
roundrobin轮询 server options: weight # 动态算法:支持权重的运行时调整,支持慢启动;每个后端中最多支持4095个server; static-rr: 静态算法:不支持权重的运行时调整及慢启动;后端主机数量无上限;不支持平滑切换; leastconn: 最少链接算法,推荐使用在具有较长会话的场景中,例如MySQL、LDAP等 ;不适用与http; first: 根据服务器在列表中的位置,自上而下进行调度;前面服务器的连接数达到上限,新请求才会分配给下一台服务; source:基于源IP的绑定,源地址hash; 除权取余法: 一致性哈希: uri: 对URI的左半部分做hash计算,并由服务器总权重相除以后派发至某匹配的服务器;使得对同一个URI的请求总是被派发至某特定的服务器,除非服务器的权重总数发生了变化;此算法常用于代理缓存或反病毒代理以提高缓存的命中率;需要注意的是,此算法仅应用于HTTP后端服务器场景;其默认为静态算法,不过也可以使用hash-type修改此特性。 <scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<frag> 左半部分:/<path>;<params> 整个uri:/<path>;<params>?<query>#<frag> url_param:对用户请求的uri听<params>部分中的参数的值作hash计算,并由服务器总权重相除以后派发至某匹配的服务器;通常用于追踪用户,以确保来自同一个用户的请求始终发往同一个Backend Server; hdr(<name>):对于每个http请求,此处由<name>指定的http首部将会被取出做hash计算; 并由服务器总权重相除以后派发至某匹配的服务器;没有有效值的会被轮询调度; hdr(Cookie) rdp-cookie rdp-cookie(<name>) 查询每个进来的TCP请求并hash,该机制用于退化的持久连接,hash方式取决于hash_type; hash-type:哈希算法 定义用于将hash码映射至后端服务器的方法;其不能用于frontend区段;可用方法有map-based和consistent,在大多数场景下推荐使用默认的map-based方法。 hash-type <method> <function> <modifier> map-based:除权取余法,哈希数据结构是静态的数组; consistent:一致性哈希,哈希数据结构是一个树; <function> is the hash function to be used : 哈希函数 sdbm djb2 wt6
指定后端主机
use_backend <backend> [{if | unless} <condition>]
当符合指定的条件时使用特定的backend;
default_backend <backend>
定义一个名为<backend>前端部分。将对于此处的请求转发给后端
设定默认的backend,用于frontend中;
default-server [param*]
为backend中的各server设定默认选项;
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; 注意:httpchk,"smtpchk", "mysql-check", "pgsql-check" and "ssl-hello-chk" 用于定义应用层检测方法;
统计接口启用相关的参数:
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中的管理功能
配置示例:
listen stats
bind :9099
stats enable
stats realm HAPorxy\ Stats\ Page
stats auth admin:admin
stats admin if TRUE
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”后即断开连接;
示例:
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
option forwardfor
[ except <network> ] [ header <name> ] [ if-none ]
允许在发往服务器的请求首部中插入“X-Forwarded-For”首部
Enable insertion of the X-Forwarded-For header to requests sent to servers
在由haproxy发往后端主机的请求报文中添加“X-Forwarded-For”首部,其值前端客户端的地址;用于向后端主发送真实的客户端IP;
[ except <network> ]:请求报请来自此处指定的网络时不予添加此首部;
[ header <name> ]:使用自定义的首部名称,而非“X-Forwarded-For”;
errorfile <code> <file>
在用户请求不存在的页面时,返回一个页面文件给客户端而非由haproxy生成的错误代码;可用于所有段中。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.指定对HTTP的哪些状态码返回指定的页面
<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>
请求错误时,返回一个HTTP重定向至某URL的信息;可用于所有配置段中。
errorfile 403 http://www.magedu.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
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.*
日志系统:
log:
为每个实例启用事件和流量日志,因此可用于所有区段
log global
log <address> [len <length>] <facility> [<level> [<minlevel>]]
no log
注意:
默认发往本机的日志服务器;
(1) local2.* /var/log/local2.log
(2) $ModLoad imudp
$UDPServerRun 514
log-format <string>:
课外实践:参考文档实现combined格式的记录
capture cookie <name> len <length>
Capture and log a cookie in the request and in the response.
capture request header <name> len <length>
Capture and log the last occurrence of the specified request header.
capture request header X-Forwarded-For len 15
capture response header <name> len <length>
Capture and log the last occurrence of the specified response header.
capture response header Content-length len 9
capture response header Location len 15
为指定的MIME类型启用压缩传输功能
compression algo <algorithm> ...:启用http协议的压缩机制,指明压缩算法gzip, deflate;
compression type <mime type> ...:指明压缩的MIMI类型;
对后端服务器做http协议的健康状态检测:
option httpchk
option httpchk <uri>
option httpchk <method> <uri>
option httpchk <method> <uri> <version>
定义基于http协议的7层健康状态检测机制;
http-check expect [!] <match> <pattern>
Make HTTP health checks consider response contents or specific status codes.
连接超时时长:
timeout client <timeout> #客户端超时
Set the maximum inactivity time on the client side. 默认单位是毫秒;
timeout server <timeout> #服务器端超时
Set the maximum inactivity time on the server side.
timeout http-keep-alive <timeout>
#设置http-keep-alive的超时时间
持久连接的持久时长;
timeout http-request <timeout>
#http请求超时时间
Set the maximum allowed time to wait for a complete HTTP request
timeout connect <timeout>
#连接超时
Set the maximum time to wait for a connection attempt to a server to succeed.
timeout client-fin <timeout>
设置客户端的不活动超时,半关闭连接
Set the inactivity timeout on the client side for half-closed connections.
timeout server-fin <timeout>
设置服务器超时连接,半关闭连接
Set the inactivity timeout on the server side for half-closed connections.
use_backend <backend> [{if | unless} <condition>]
Switch to a specific backend if/unless an ACL-based condition is matched.
当符合指定的条件时使用特定的backend;
block { if | unless } <condition>
Block a layer 7 request if/unless a condition is matched
acl invalid_src src 172.16.200.2
block if invalid_src
errorfile 403 /etc/fstab #错误页面显示
errorloc 403 http://www.baidu.com #跳转机制
http-request { allow | deny } [ { if | unless } <condition> ]
Access control for Layer 7 requests
tcp-request connection {accept|reject} [{if | unless} <condition>]
Perform an action on an incoming connection depending on a layer 4 condition
示例:
listen ssh
bind :22022
balance leastconn
acl invalid_src src 172.16.200.2
tcp-request connection reject if invalid_src
mode tcp
server sshsrv1 172.16.100.6:22 check
server sshsrv2 172.16.100.7:
acl
acl:
The use of Access Control Lists (ACL) provides a flexible solution to perform content switching and generally to take decisions based on content extracted from the request, the response or any environmental status.
haproxy的ACL用于实现基于请求报文的首部、响应报文的内容或其它的环境状态信息来做出转发决策,这大大增强了其配置弹性。其配置法则通常分为两步,首先去定义ACL,即定义一个测试条件,而后在条件得到满足时执行某特定的动作,如阻止请求或转发至某特定的后端。定义ACL的语法格式如下。
acl <aclname> <criterion> [flags] [operator] [<value>] ...
<aclname>:ACL names must be formed from upper and lower case letters, digits, '-' (dash), '_' (underscore) , '.' (dot) and ':' (colon).ACL names are case-sensitive.
<value>的类型:acl测试条件支持的值有以下四类:
- boolean
- integer or integer range
- IP address / network
- string (exact, substring, suffix, prefix, subdir, domain)
- regular expression
- hex block 16进制
<flags>
-i : 不区分中模式字符的大小写;
ignore case during matching of all subsequent patterns.
-m : use a specific pattern matching method
-n : forbid the DNS resolutions
-u : force the unique id of the ACL
-- : 标志符的强制结束标记,在模式中的字符串像标记符时使用;
force end of flags. Useful when a string looks like one of the flags.
[operator]
匹配整数值:eq、ge、gt、le、lt
匹配字符串:
- exact match (-m str) : the extracted string must exactly match the patterns ;
- substring match (-m sub) : the patterns are looked up inside the extracted string, and the ACL matches if any of them is found inside ;
- prefix match (-m beg) : the patterns are compared with the beginning of the extracted string, and the ACL matches if any of them matches.
- suffix match (-m end) : the patterns are compared with the end of the extracted string, and the ACL matches if any of them matches.
- subdir match (-m dir) : the patterns are looked up inside the extracted string, delimited with slashes ("/"), and the ACL matches if any of them matches.
- domain match (-m dom) : the patterns are looked up inside the extracted string, delimited with dots ("."), and the ACL matches if any of them matches.
acl作为条件时的逻辑关系:
- AND (implicit)
- OR (explicit with the "or" keyword or the "||" operator)
- Negation with the exclamation mark ("!")
if invalid_src invalid_port
if invalid_src || invalid_port
if ! invalid_src invalid_port
<criterion> :
dst : ip
dst_port : integer
src : ip
src_port : integer
acl invalid_src src 172.16.200.2 #拒绝该IP访问
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).
/path;<params>
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
url : string
This extracts the request's URL as presented in the request. A typical use is with prefetch-capable caches, and with portals which need to aggregate multiple information from databases and keep them in caches.
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
req.hdr([<name>[,<occ>]]) : string
This extracts the last occurrence of header <name> in an HTTP request.
hdr([<name>[,<occ>]]) : exact string match
hdr_beg([<name>[,<occ>]]) : prefix match
hdr_dir([<name>[,<occ>]]) : subdir match
hdr_dom([<name>[,<occ>]]) : domain match
hdr_end([<name>[,<occ>]]) : suffix match
hdr_len([<name>[,<occ>]]) : length match
hdr_reg([<name>[,<occ>]]) : regex match
hdr_sub([<name>[,<occ>]]) : substring match
示例:
acl bad_curl hdr_sub(User-Agent) -i curl
block if bad_curl
status : integer
Returns an integer containing the HTTP status code in the HTTP response.
Pre-defined ACLs
ACL name Equivalent to Usage
FALSE always_false never match
HTTP req_proto_http match if protocol is valid HTTP
HTTP_1.0 req_ver 1.0 match HTTP version 1.0
HTTP_1.1 req_ver 1.1 match HTTP version 1.1
HTTP_CONTENT hdr_val(content-length) gt 0 match an existing content-length
HTTP_URL_ABS url_reg ^[^/:]*:// match absolute URL with scheme
HTTP_URL_SLASH url_beg / match URL beginning with "/"
HTTP_URL_STAR url * match URL equal to "*"
LOCALHOST src 127.0.0.1/8 match connection from local host
METH_CONNECT method CONNECT match HTTP CONNECT method
METH_GET method GET HEAD match HTTP GET or HEAD method
METH_HEAD method HEAD match HTTP HEAD method
METH_OPTIONS method OPTIONS match HTTP OPTIONS method
METH_POST method POST match HTTP POST method
METH_TRACE method TRACE match HTTP TRACE method
RDP_COOKIE req_rdp_cookie_cnt gt 0 match presence of an RDP cookie
REQ_CONTENT req_len gt 0 match data in the request buffer
TRUE always_true always match
WAIT_END wait_end wait for end of content analysis
HAProxy:global, proxies(fronted, backend, listen, defaults)
balance:
roundrobin, static-rr
leastconn
first
source
hdr(<name>)
uri (hash-type)
url_param
Nginx调度算法:ip_hash, hash, leastconn,
lvs调度算法:
rr/wrr/sh/dh, lc/wlc/sed/nq/lblc/lblcr
****基于ACL的动静分离示例:****
frontend web *:80 (静态到指定,动态默认)
acl url_static path_beg -i /static /images /javascript /stylesheets
acl url_static path_end -i .jpg .gif .png .css .js .html .txt .htm
use_backend staticsrvs if url_static
default_backend appsrvs
backend staticsrvs
balance roundrobin
server stcsrv1 172.16.100.6:80 check
backend appsrvs
balance roundrobin
server app1 172.16.100.7:80 check
server app1 172.16.100.7:8080 check
listen stats
bind :9091
stats enable
stats auth admin:admin
stats admin if TRUE
配置HAProxy支持https协议:
1 支持ssl会话;
bind *:443 ssl crt /PATH/TO/SOME_PEM_FILE
crt后的证书文件要求PEM格式,且同时包含证书和与之匹配的所有私钥;
cat demo.crt demo.key > demo.pem
2 把80端口的请求重向定443;
bind *:80
redirect scheme https if !{ ssl_fc }
3 如何向后端传递用户请求的协议和端口
http_request set-header X-Forwarded-Port %[dst_port]
http_request add-header X-Forwared-Proto https if { ssl_fc }
haproxy配置文档路径:http://cbonte.github.io/haproxy-dconv/
原创文章,作者:Mr-Xiao,如若转载,请注明出处:http://www.178linux.com/76124

