Haproxy是既可以工作在7层也能工作在4层的反代工具.
Haproxy的功能:

  1. 路由HTTP请求到后端服务器,基于cookie作会话绑定.

  2. 能够将多个请求反代至后端主机完成负载均衡的效果.

  3. 主服务器失败时能自动切换到备服务器上.

  4. 接受特殊的端口连接完成服务监控

  5. 拒绝新连接时不会关闭已经连接的请求.

  6. 在两个方向上添加、修改和删除HTTP首部

  7. 根据特定匹配条件阻止相应请求.

  8. 通过一个URI接口web应用程序为通过身份验证的用户提供报告详细状态.

  9. 虽然主要提供http反代,但也能反代几乎所有基于tcp的协议

  10. 有强大的后端主机健康检测功能.

  11. 支持 单一进程模型,事件驱动,弹性二叉树;

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 <name>:  为frontend, backend以及listen提供默认配置;
--- frontend <name>:  相当于nginx的server段,即一个虚拟主机负责接收客户端的请求
--- backend <name>: 相当于nginx的upstream段,
--- listen <name>: 它既是前端(frontend)又是后端(backend),它们是一对一的关系.换句话说就是它既有自己的前端也有自己专用的后端.

Haproxy简单体验

1240

简单修改/etc/haproxy/haproxy.cfg将http请求负载均衡到两台后端主机ibm1 ibm2上

1240

因为后端主机未开启web服务,此时访问haproxy主机会有错误


启动ibm1 ibm2上的httpd服务后再次访问

1240

1240

Haproxy详细配置

golbal配置参数

进程及安全配置相关的参数
性能调整相关的参数
Debug相关的参数
1.启用日志
log <address> [len <length>] <facility> [max level [min level]]:定义日志系统相关属性

<address>:日志服务器地址;
[len <length>]:每行日志记录的最大长度;

<facility>: 设备
[max level [min level]]: 记录日志级别
ca-base <dir>:
   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 <dir>:
   Assigns a default directory to fetch SSL certificates from when a relative path is used with "crtfile" directives.

编辑/etc/rsyslog.conf文件

1240

开启UDP日志接收

1240

增加一行内容

重启rsyslog服务:systemctl restart rsyslog.service
再次访问haproxy就能在指定日志文件记录日志了,如下图.

1240


2. 性能调整(大都不需要自己调整,系统默认最优化)
nbproc <number>这项可以配置haproxy进程数,默认为1.
ulimit-n <number>则表示每个进程可以打开的文件数量
maxconn <number>: 每个haproxy进程的最大连接数
maxconnrate <number>:每个haproxy进程最大连接速率(可以指定,当大量连接涌进,可以限制速度)
maxcomprate <number>: 每秒进站的数据压缩率
maxcompcpuusage <number>: 压缩时所能占用的CPU比例
maxsslconn <number>: 每个haproxy进程所能创建最大的ssl并发连接数
maxsslrate <number>
noepoll: 这个不能开启
spread-checks <0..50, in percent>:
tune.rcvbuf.client <number>
tune.rcvbuf.server <number>
tune.sndbuf.client <number>
tune.sndbuf.server <number>
tune.ssl.lifetime <timeout>: ssl会话有效时长,默认300秒
3. 用户列表
userlist <listname>:定义用户组及列表,示例如下代码框.
group <groupname> [users <user>,<user>,(...)]
user <username> [password|insecure-password <password>] [groups <group>,<group>,(...)]

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 <peersect>
disabled
enable
peer <peername> <ip>:<port>
示例:

peers mypeers
    peer haproxy1 192.168.0.1:1024
    peer haproxy2 192.168.0.2:1024
    peer haproxy3 10.2.0.1:1024backend 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 [<address>]:<port_range> [, ...] [param]
*
bind* /<path> [, ...] [param]  : 可使用在frontend    listen中.指定监听地址与端口,示例如下:

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-proxylisten http_https_proxy    bind :80
    bind :443 ssl crt /etc/haproxy/site.pemlisten http_https_proxy_explicit    bind ipv6@:80
    bind ipv4@public_ssl:443 ssl crt /etc/haproxy/site.pem    bind unix@ssl-frontend.sock user root mode 600 accept-proxylisten external_bind_app1    bind fd@${FD_APP1}

acl <aclname> <criterion> [flags] [operator] <value> ...:可用在frontend    listen backend中,声明或完成一个访问列表.
balance <algorithm> [ <arguments> ]
balance url_param <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中的<param>部分中的指定的参数的值作hash计算,并由服务器总权重相除以后派发至某挑出的服务器.
hdr(<name>):The HTTP header <name> will be looked up in each HTTP  request.指定的http首部将会被取出做hash计算,并由服务器总权重相除以后派发至某挑出的服务器;没有有效值的会被轮询调度.

maxconn <conns>:可用在defaults    frontend    listen中, 设定frontend最大的并发连接请求数.1G的ram大致可以维持20000-25000个连接,默认值为2000.

stats admin { if | unless } <cond>: 仅在满足某些条件时才启用管理, 尽量少启用因为不安全
Enable statistics admin level if/unless a condition is matched
stats realm <realm>: 认证时弹框的提示内容.
stats auth <user>:<passwd>:可在defaults,frontend,listen,backend中使用,允许指定的认证和授权的帐户访问.
stats uri <prefix>: 状态页面访问uri
stats refresh <delay>: 设置刷新间隔时间.
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 <name> <address>[:[port]] [param*]:可用在listen,backend中定义一个后端主机,其中部分可选params如下:

addr <ipv4|ipv6>: 健康状态检测的专用地址
backup
check: 执行健康状态检测.默认为传输层检测.需要执行应用层检测需要"httpchk","smtpchk", "mysql-check", "pgsql-check" and "ssl-hello-chk"
inter <delay>: 时间间隔,默认为2秒
rise <count>: 判定为"健康"状态需要检测的次数,默认2次.
fall <count>: 判定为"不健康"状态需要检测的次数,默认为3次.
port <port>:健康状态检测时使用的端口.
注意:默认为传输层检测,即探测端口是否能响应;需要执行应用层检测,则需要httpchk, smtpchk, mysql-check, pgsql-check, ssl-hello-chk;
cookie <value>: 为当前server指定其cookie值,此值会在收到请求报文时进行检测,其功能在于实现基于cookie会话保持.
disabled:将些server标记为不可用,进入维护模式.
id <value>: 为此server设置保持id(正数且唯一),当调度算法first为根据这个数值较小的id先进行调度
maxconn <maxconn>: 当前server的最大并发连接数.
maxqueue <maxqueue>: 当前server的等待队列的最大长度.
redir <prefix>: 将发往当前server的所有请求会被重定向到别的主机(给出 scheme://host即可)如下示例:
server srv1 192.168.1.1:80 redir http://image1.mydomain.com check
weight <weight>: 当前server的权重.

option httpchk: uri默认为主页
option httpchk <uri>
option httpchk <method> <uri>
option httpchk <method> <uri> <version>
以上在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> <pattern>:在defaults    ,listen,backend中可用期望在做健康状态检测时返回的内容
match为status或string
示例: http-check expect status 200

cookie <name> [ rewrite | insert | prefix ] [ indirect ] [ nocache ] [ postonly ] [ preserve ] [ httponly ] [ secure ] [ domain <domain> ]* [ maxidle <idle> ] [ maxlife <life> ]
可在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

1240

Paste_Image.png

default_backend <backend>:设定默认的backend,当没有 "use_backend" 规则被匹配时.


与日志相关的
log global
log <address> [len <length>] <facility> [<level> [<minlevel>]]
no log
为frontend或backend定义日志记录机制

1240

示例说明


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 <name> len <length>:捕获并记录于日志 最近指定的请求首部.
capture response header <name> len <length>:
示例:

capture response header Content-length len 9capture response header Location len 15

错误页面自定义相关参数

errorfile  <code> <file>: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 bugerrorfile 403 /etc/haproxy/errorfiles/403forbid.http
errorfile 503 /etc/haproxy/errorfiles/503sorry.http

errorloc <code> <url>
errorloc302 <code> <url>: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 <network> ] [ header <name> ] [ if-none ]:
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 <string> [{if | unless} <cond>]: 示例rspadd  X-Via:\ Haproxy
Add a header at the end of the HTTP response
reqadd <string> [{if | unless} <cond>]
Add a header at the end of the HTTP request
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.* 删除以Server开头的响应报头.


超时时长相关参数
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 connect <timeout>
Set the maximum time to wait for a connection attempt to a server to succeed.
timeout http-keep-alive <timeout>
Set the maximum allowed time to wait for a new HTTP request to appear面向客户端一侧开启保持连接功能
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.

timeout http-request <timeout>
Set the maximum allowed time to wait for a complete HTTP request

timeout http-keep-alive <timeout>
Set the maximum allowed time to wait for a new HTTP request to appear


ACL相关的参数
Haproxy 完全能够胜任从客户端或服务器的请求与响应流中提取数据
Access Control Lists (ACL)提供了一个灵活的解决方案去执行内容转换以及根据从请求或响应或者环境状态做出决策.原理很简单:

  • 从数据流,表或环境中提取数据样本

  • 有选择性地对这些数据样本做格式转换

  • 根据样例生成一个或多个匹配模式

  • 只有当样本与匹配模式匹配时才对其执行相应动作
    语法格式:acl <aclname> <criterion> [flags] [operator] [<value>] ...

<value>类型:

boolean
integer or integer range
IP address / network
string (exact, substring, suffix, prefix, subdir, domain)
regular expression
hex block

<flags>类型:

-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 ("!")

<criterion>

根据(源与目标的)IP与端口来设置ACL:
   dst : ip
   dst_port : integer
   src : ip
   src_port : integer
示例:

acl myhost src 10.1.0.200acl myport dst_port 8080block 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([<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 firefox hdr_reg(User-Agent) -i  .*firefox.*    
block if firefox

响应行首部检查
res.hdr([<name>[,<occ>]]) : string
This extracts the last occurrence of header <name> in an HTTP response, or of the last header if no <name> is specified.

shdr([<name>[,<occ>]])     : exact string match
shdr_beg([<name>[,<occ>]]) : prefix match
shdr_dir([<name>[,<occ>]]) : subdir match
shdr_dom([<name>[,<occ>]]) : domain match
shdr_end([<name>[,<occ>]]) : suffix match
shdr_len([<name>[,<occ>]]) : length match
shdr_reg([<name>[,<occ>]]) : regex match
shdr_sub([<name>[,<occ>]]) : 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 } <condition>
Block a layer 7 request if/unless a condition is matched
阻止符合指定acl的访问请求;
http-request { allow | deny | tarpit | auth [realm <realm>] | redirect <rule> | add-header <name> <fmt> | set-header <name> <fmt> | del-header <name> | set-nice <nice> | set-log-level <level> | replace-header <name> <match-regex> <replace-fmt> | replace-value <name> <match-regex> <replace-fmt> | set-tos <tos> | set-mark <mark> | add-acl(<file name>) <key fmt> | del-acl(<file name>) <key fmt> | del-map(<file name>) <key fmt> | set-map(<file name>) <key fmt> <value fmt> } [ { if | unless } <condition> ]
http-response { allow | deny | add-header <name> <fmt> | set-nice <nice> | set-header <name> <fmt> | del-header <name> | replace-header <name> <regex-match> <replace-fmt> | replace-value <name> <regex-match> <replace-fmt> | set-log-level <level> | set-mark <mark> | set-tos <tos> | add-acl(<file name>) <key fmt> | del-acl(<file name>) <key fmt> | del-map(<file name>) <key fmt> | set-map(<file name>) <key fmt> <value fmt> } [ { if | unless } <condition> ]:

示例1:

acl myhost          src             10.1.0.67http-request deny  if  url_admin  !myhost

示例2

acl nagios src 192.168.129.3acl local_net src 192.168.0.0/16acl 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 <action> [{if | unless} <condition>]
Perform an action on an incoming connection depending on a layer 4 condition
示例

tcp-request connection accept if { src -f /etc/haproxy/whitelist.lst }  # 这里的花括号部分即是一个acltcp-request connection reject if { src_conn_rate gt 10 }
tcp-request connection track-sc0 src

tcp-request content <action> [{if | unless} <condition>]
Perform an action on a new session depending on a layer 4-7 condition
示例:
 后端主机调用:
           use_backend <backend> [{if | unless} <condition>]
               Switch to a specific backend if/unless an ACL-based condition is matched.