haproxy 命令配置实例

一:Global parameters
* Process management and security
- chroot 改变当前工作目录
- daemon 运行方式为后台工作
- user - group 工作用户和组
-log <address> <facility>日志输出设备
- nbproc 创建工作的进程数目
-pidfile pid文件位置
- ulimit-n 设置每个进程的可用的最大文件描述符
- stats 创建监控所用的套接字目录
- node 创建另外一个节点名字共用一个IP地址,用来识别哪个节点在处理流量
- description 描述实例的名称
maxconn <number> 每个进程可用的最大连接数
maxpipes <number>  每个进程可用的最大管道数
nokqueue  nopoll  nosepoll nosplice  禁用这些功能
spread-checks <0..50, in percent>  health check 的时间间隔
tune.bufsize <number>
tune.maxaccept <number>
tune.maxpollevents <number>
tune.maxrewrite <number>
tune.rcvbuf.client <number>
tune.rcvbuf.server <number>
tune.sndbuf.client <number>
tune.sndbuf.server <number>
以上凭字面理解吧
debug  调试模式,输出启动信息到标准输出
quiet   安装模式,启动时无输出

二:defaults 块
作用于其后紧跟的listen块,直至下一个defaults 块,下一个default 将替换上一个块作用于以后的listen
frontend 块,接受请求的端口组
backend块,后端处理的server 组
listen块,frontend和backend 块的结合

三:常用配置命令

balance <algorithm> [ <arguments> ]
balance url_param <param> [check_post [<max_wait>]]   负载均衡模块设置

Examples :
balance roundrobin
balance url_param userid
balance url_param session_id check_post 64
balance hdr(User-Agent)
balance hdr(host)
balance hdr(Host) use_domain_only

block { if | unless } <condition>  在7层阻止访问
Example:
acl invalid_src src 0.0.0.0/7 224.0.0.0/3  acl定义和squid 很像
acl invalid_src src_port 0:1023
acl local_dst hdr(host) -i localhost
block if invalid_src || local_dst

capture cookie <name> len <length>  在请求和回应包中捕捉记录指定长度的cookie,name 为cookie的开头几个字母

Example:
capture cookie ASPSESSION len 32

capture request header <name> len <length>
capture response header <name> len <length> 同上

clitimeout <timeout> (deprecated)
contimeout <timeout> (deprecated)  客户端超时时间,不赞成设置

cookie <name> [ rewrite | insert | prefix ] [ indirect ] [ nocache ] [ postonly ] [ domain <domain> ]*   允许持续的基于cookie 的后端连接

default_backend <backend> 默认应用的后端

Example :
use_backend dynamic if url_dyn
use_backend static if url_css url_img extension_img
default_backend dynamic    当没有匹配时就用dynamic

errorfile <code> <file> 定义出现错误的代码的返回页
Example :
errorfile 400 /etc/haproxy/errorfiles/400badreq.http
errorfile 403 /etc/haproxy/errorfiles/403forbid.http
errorfile 503 /etc/haproxy/errorfiles/503sorry.http

errorloc <code> <url> errorloc302 <code> <url>   出错重定向到指定url
force-persist { if | unless } <condition>  在特定条件下,强制继续连接down 掉的服务器后端
fullconn <conns>  定义后端组的最大连接数
grace <time>  haproxy停止后,再持续多长时间用于处理连接
http-check disable-on-404  如果后端检测返回404,将不再把后端计入负载均衡
http-check send-state 允许haproxy 发送 X-Haproxy-Server-State
http-request { allow | deny | http-auth [realm <realm>] } [ { if | unless } <condition> ]   七层访问控制
Example:
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

Example:
acl auth_ok http_auth_group(L1) G1

http-request auth unless auth_ok

mode { tcp|http|health }   设定启动的实例的协议类型
monitor fail { if | unless } <condition>  监控失败条件设置

option abortonclose 丢弃由于客户端等待时间过长而关闭连接但仍在haproxy等待队列中的请求
option accept-invalid-http-request  接受无效的http请求,建议关闭(开启可能有安全隐患)
option accept-invalid-http-response 接受无效的response ,建议关闭
option allbackups  应该是后备服务器,如果正常的后端无法使用,就使用这些后备的设备,balance方式还是用原来的,没有优先的选择,常用来提供错误的页面
option checkcache    分析后端response,阻止可缓存的cookie,它对response 进行严格检查,包括"Cache-control", "Pragma" and "Set-cookie" ,查看在客户端代理那边保存是否有风险,如果这个允许的话,符全以下条件 的response 将被允许,其它的将被阻止。
- all those without "Set-Cookie" header ;
- all those with a return code other than 200, 203, 206, 300, 301, 410,
provided that the server has not set a "Cache-control: public" header ;
- all those that come from a POST request, provided that the server has not
set a 'Cache-Control: public' header ;
- those with a 'Pragma: no-cache' header
- those with a 'Cache-control: private' header
- those with a 'Cache-control: no-store' header
- those with a 'Cache-control: max-age=0' header
- those with a 'Cache-control: s-maxage=0' header
- those with a 'Cache-control: no-cache' header
- those with a 'Cache-control: no-cache="set-cookie"' header
- those with a 'Cache-control: no-cache="set-cookie,' header
(allowing other fields after set-cookie)

option clitcpka   是否允许客户端发送tcp keepalive 包,这个和http 的keepalive 没有关系
option contstats   允许连续的流量统计更新
option dontlog-normal   开启正常连接的日志
option dontlognull   记录空连接
option forceclose  允许关闭session 在后端把response 发送后
option forwardfor [ except <network> ] [ header <name> ]        允许在request 中加入X-Forwarded-For header 发往server
option http-pretend-keepalive    定义是否haproxy要宣布同server keepalive
option http-server-close   是否开启在server 端 connection closing
option http-use-proxy-header    用non-standard Proxy-Connection 替换 connection

option httpchk <method> <uri> <version>  允许用http协议检查server 的健康
Examples :
# 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

option httplog [ clf ] 定制日志格式
option http_proxy  开启http 代理模式,只有最基本的代理功能
option ignore-persist { if | unless } <condition> 在某条件下拒绝持续连接,适用于对静态文件的负载均衡
option independant-streams  启用双向超时处理,如socket 的read 和write
option log-health-checks   记录健康检查日志
option log-separate-errors   对非完全成功的连接改变日志记录等级
option logasap   大传输大文件时可以提前记录日志
option mysql-check   mysql 健康检查
option nolinger  清除肮脏连接后开成的tcp 状态及占用的资源,不过并不是强列要求你用这个选项,当然如果你有thousands of FIN_WAIT1 sessions on your system ,那肯定得用了
option originalto [ except <network> ] [ header <name> ]   允许在requests中加入X-Original-To header 发往server
option persist     强制将http请求发往已经down 掉的server
option redispatch   是否允许重新分配在session 失败后
option smtpchk   smtp 检查
option socket-stats  允许对单个socket进行统计
option srvtcpka  是否允许向server 发送keepalive
option tcpka 是否允许向server和client发送keepalive
option tcplog  允许记录tcp 连接的状态和时间
option transparent   允许客户端透明代理
rate-limit sessions <rate> 设置frontend 每秒处理的连接的上限,如果到达上限就停止建立新的connection

redirect location <to> [code <code>] <option> [{if | unless} <condition>]
redirect prefix   <to> [code <code>] <option> [{if | unless} <condition>] 重定向,相当于rewrite

Example: move the login URL only to HTTPS.
acl clear      dst_port  80
acl secure     dst_port  8080
acl login_page url_beg   /login
acl logout     url_beg   /logout
acl uid_given  url_reg   /login?userid=[^&]+
acl cookie_set hdr_sub(cookie) SEEN=1

redirect prefix   https://mysite.com set-cookie SEEN=1 if !cookie_set
redirect prefix   https://mysite.com           if login_page !secure
redirect prefix   http://mysite.com drop-query if login_page !uid_given
redirect location http://mysite.com/           if !login_page secure
redirect location / clear-cookie USERID=       if logout

Example: send redirects for request for articles without a '/'.
acl missing_slash path_reg ^/article/[^/]*$
redirect code 301 prefix / drop-query append-slash if missing_slash
redisp (deprecated)
redispatch (deprecated) 开启session 重新分配在connection连接失败后,不赞成启用
reqadd  <string> [{if | unless} <cond>] 在http请示的末尾加上string

Example : add "X-Proto: SSL" to requests coming via port 81
acl is-ssl  dst_port       81
reqadd      X-Proto:\ SSL  if is-ssl

reqallow  <search> [{if | unless} <cond>]
reqiallow <search> [{if | unless} <cond>] (ignore case)    request 请求访问控制

Example :
# allow www.* but refuse *.local
reqiallow ^Host:\ www\.
reqideny  ^Host:\ .*\.local

reqdel  <search> [{if | unless} <cond>]
reqidel <search> [{if | unless} <cond>]  (ignore case) 删除请求的head 中的内容

Example :
# remove X-Forwarded-For header and SERVER cookie
reqidel ^X-Forwarded-For:.*
reqidel ^Cookie:.*SERVER=

reqdeny  <search> [{if | unless} <cond>]
reqideny <search> [{if | unless} <cond>]  (ignore case) 拒绝访问

reqrep  <search> <string> [{if | unless} <cond>]
reqirep <search> <string> [{if | unless} <cond>]   (ignore case)  request 请求替换
Example :
# replace "/static/" with "/" at the beginning of any request path.
reqrep ^([^\ ]*)\ /static/(.*)     \1\ /\2
# replace "www.mydomain.com" with "www" in the host name.
reqirep ^Host:\ www.mydomain.com   Host:\ www

reqtarpit  <search> [{if | unless} <cond>]
reqitarpit <search> [{if | unless} <cond>]  (ignore case) 阻止http请求中的某些信息

Examples :
# ignore user-agents reporting any flavour of "Mozilla" or "MSIE", but
# block all others.
reqipass   ^User-Agent:\.*(Mozilla|MSIE)
reqitarpit ^User-Agent:

# block bad guys
acl badguys src 10.1.0.3 172.16.13.20/28
reqitarpit . if badguys

retries <value> 当对server的connection失败后,重试的次数
rspadd <string> [{if | unless} <cond>] response 增加信息
rspdel  <search> [{if | unless} <cond>]
rspidel <search> [{if | unless} <cond>]  (ignore case)
rspdeny  <search> [{if | unless} <cond>]
rspideny <search> [{if | unless} <cond>]  (ignore case)
rsprep  <search> <string> [{if | unless} <cond>]
rspirep <search> <string> [{if | unless} <cond>]  (ignore case)
以上和request 的差不多

source <addr>[:<port>] [usesrc { <addr2>[:<port2>] | client | clientip } ] 定义从代理出去的连接的对象,用于限定地址可以访问server

一些timeout

srvtimeout <timeout> server 处理超时,不赞成设置
timeout check                             X          -         X         X
timeout client                            X          X         X         -
timeout clitimeout          (deprecated)  X          X         X         -
timeout connect                           X          -         X         X
timeout contimeout          (deprecated)  X          -         X         X
timeout http-keep-alive                   X          X         X         X
timeout http-request                      X          X         X         X
timeout queue                             X          -         X         X
timeout server                            X          -         X         X
timeout srvtimeout          (deprecated)  X          -         X         X
timeout tarpit                            X          X         X         X

stats auth <user>:<passwd> 监控统计的帐号和密码
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

还有很多参数,以上能用到的也没有几个,只要满足当前需求就好,对于性能要求高的话,建议把不需要的功能 都关了吧

发表评论