设为首页 收藏本站
查看: 1268|回复: 0

[经验分享] haproxy详细介绍

[复制链接]

尚未签到

发表于 2019-1-1 10:20:26 | 显示全部楼层 |阅读模式
  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提供默认配置;
--- frontend :  相当于nginx的server段,即一个虚拟主机负责接收客户端的请求
--- backend : 相当于nginx的upstream段,
--- listen : 它既是前端(frontend)又是后端(backend),它们是一对一的关系.换句话说就是它既有自己的前端也有自己专用的后端.
Haproxy简单体验
DSC0000.jpg

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

  因为后端主机未开启web服务,此时访问haproxy主机会有错误
  
启动ibm1 ibm2上的httpd服务后再次访问

DSC0002.jpg

DSC0003.jpg

Haproxy详细配置
golbal配置参数
  进程及安全配置相关的参数
性能调整相关的参数
Debug相关的参数
1.启用日志
log  [len ]  [max level [min level]]:定义日志系统相关属性
  日志服务器地址;
[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文件

DSC0004.jpg

  开启UDP日志接收
DSC0005.jpg

  增加一行内容
  重启rsyslog服务:systemctl restart rsyslog.service
再次访问haproxy就能在指定日志文件记录日志了,如下图.
DSC0006.jpg

  
2. 性能调整(大都不需要自己调整,系统默认最优化)
nbproc 这项可以配置haproxy进程数,默认为1.
ulimit-n 则表示每个进程可以打开的文件数量
maxconn : 每个haproxy进程的最大连接数
maxconnrate :每个haproxy进程最大连接速率(可以指定,当大量连接涌进,可以限制速度)
maxcomprate : 每秒进站的数据压缩率
maxcompcpuusage : 压缩时所能占用的CPU比例
maxsslconn : 每个haproxy进程所能创建最大的ssl并发连接数
maxsslrate
noepoll: 这个不能开启
spread-checks :
tune.rcvbuf.client
tune.rcvbuf.server
tune.sndbuf.client
tune.sndbuf.server
tune.ssl.lifetime : ssl会话有效时长,默认300秒
3. 用户列表
userlist :定义用户组及列表,示例如下代码框.
group  [users ,,(...)]
user  [password|insecure-password ] [groups ,,(...)]
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: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 []: [, ...] [param]
*
bind* / [, ...] [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   [flags] [operator]  ...:可用在frontend    listen backend中,声明或完成一个访问列表.
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 header  will be looked up in each HTTP  request.指定的http首部将会被取出做hash计算,并由服务器总权重相除以后派发至某挑出的服务器;没有有效值的会被轮询调度.
  maxconn :可用在defaults    frontend    listen中, 设定frontend最大的并发连接请求数.1G的ram大致可以维持20000-25000个连接,默认值为2000.
  stats admin { if | unless } : 仅在满足某些条件时才启用管理, 尽量少启用因为不安全
Enable statistics admin level if/unless a condition is matched
stats realm : 认证时弹框的提示内容.
stats auth ::可在defaults,frontend,listen,backend中使用,允许指定的认证和授权的帐户访问.
stats uri : 状态页面访问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  [:[port]] [param*]:可用在listen,backend中定义一个后端主机,其中部分可选params如下:
  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 [!]  :在defaults    ,listen,backend中可用期望在做健康状态检测时返回的内容
match为status或string
示例: http-check expect status 200
  cookie  [ rewrite | insert | prefix ] [ indirect ] [ nocache ] [ postonly ] [ preserve ] [ httponly ] [ secure ] [ domain  ]* [ maxidle  ] [ maxlife  ]
可在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
DSC0007.jpg

  Paste_Image.png
  default_backend :设定默认的backend,当没有 "use_backend" 规则被匹配时.
  与日志相关的
log global
log  [len ]  [ []]
no log
为frontend或backend定义日志记录机制
DSC0008.jpg

  示例说明
  
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  len :捕获并记录于日志 最近指定的请求首部.
capture response header  len :
示例:
capture response header Content-length len 9capture 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 bugerrorfile 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  ] [ header  ] [ 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  [{if | unless} ]: 示例rspadd  X-Via:\ Haproxy
Add a header at the end of the HTTP response
reqadd  [{if | unless} ]
Add a header at the end of the HTTP request
reqdel  [{if | unless} ]
reqidel  [{if | unless} ] (ignore case)
Delete all headers matching a regular expression in an HTTP request
rspdel  [{if | unless} ]
rspidel  [{if | unless} ] (ignore case)
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.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([[,]]) : string
This extracts the last occurrence of header  in an HTTP request.
  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([[,]]) : substring match
示例:
acl firefox hdr_reg(User-Agent) -i  .*firefox.*   
block if firefox
  响应行首部检查
res.hdr([[,]]) : string
This extracts the last occurrence of header  in an HTTP response, or of the last header if no  is specified.
  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 ] | redirect  | add-header   | set-header   | del-header  | set-nice  | set-log-level  | replace-header    | replace-value    | set-tos  | set-mark  | add-acl()  | del-acl()  | del-map()  | set-map()   } [ { if | unless }  ]
http-response { allow | deny | add-header   | set-nice  | set-header   | del-header  | replace-header    | replace-value    | set-log-level  | set-mark  | set-tos  | add-acl()  | del-acl()  | del-map()  | set-map()   } [ { if | unless }  ]:
  示例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  [{if | unless} ]
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  [{if | unless} ]
Perform an action on a new session depending on a layer 4-7 condition
示例:
后端主机调用:
            use_backend  [{if | unless} ]
                Switch to a specific backend if/unless an ACL-based condition is matched.





运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-658177-1-1.html 上篇帖子: haproxy之深度详解 下篇帖子: 海量运维常用技术之
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表