-
LB Cluster:
- 四層:lvs, nginx(stream),haproxy(mode tcp)
- 七層:http: nginx(http, ngx_http_upstream_module), haproxy(mode http), httpd, ats, perlbal, pound…
HAProxy
-
程序環境:
- 主程序:/usr/sbin/haproxy
- 主配置文件:/etc/haproxy/haproxy.cfg
- Unit file:/usr/lib/systemd/system/haproxy.service
-
配置段:
-
global:全局配置段
-
進程及安全配置相關的參數
性能調整相關參數
Debug參數
-
進程及安全配置相關的參數
-
proxies:代理配置段
-
defaults:為frontend, listen, backend提供默認配置;
fronted:前端,相當于nginx, server {}
backend:后端,相當于nginx, upstream {}
listen:同時擁前端和后端
配置示例:(負載均衡集群,一般主頁頁面是相同的;只是此處的主頁頁面不同,) frontend web bind *:80 default_backend websrvs backend websrvs balance roundrobin server srv1 172.16.100.6:80 check server srv2 172.16.100.7:80 check
-
defaults:為frontend, listen, backend提供默認配置;
-
global:全局配置段
global配置參數:
-
進程及安全管理:chroot, deamon,user, group, uid, gid
-
log:定義全局的syslog服務器;最多可以定義兩個;
log <address> [len <length>] <facility> [max level [min level]]`
- 用戶可以自定義的facility:local0–>local7
- 級別有: emerg alert crit err warning notice info debug
-
nbproc :要啟動的haproxy的進程數量;
Creates processes when going daemon. This requires the “daemon” mode. By default, only one process is created, which is the recommended mode of operation. For systems limited to small sets of file descriptors per process, it may be needed to fork multiple daemons. USING MULTIPLE PROCESSES IS HARDER TO DEBUG AND IS REALLY DISCOURAGED. See also “daemon”. -
ulimit-n :每個haproxy進程可打開的最大文件數;
Sets the maximum number of per-process file-descriptors to . By default, it is automatically computed, so it is recommended not to use this option.
-
-
性能調整:
- maxconn :設定每個haproxy進程所能接受的最大并發連接數;Sets the maximum per-process number of concurrent connections to .
- maxconnrate :Sets the maximum per-process number of connections per second to .每個進程每秒種所能創建的最大連接數量;
- maxsessrate :每秒鐘所能創建的會話數
- maxsslconn : Sets the maximum per-process number of concurrent SSL connections to .
-
spread-checks <0..50, in percent>.后端主機的健康狀態檢測
當后端主機的數量較多時,在某一時刻光對健康狀態檢測就占據較大帶寬,因此需要散開在不同的時間對后端主機進行健康狀態檢測。不可提前和延后整個周期的50%
代理配置段
- defaults
- frontend
- backend
-
listen
A "frontend" section describes a set of listening sockets accepting client connections. A "backend" section describes a set of servers to which the proxy will connect to forward incoming connections. A "listen" section defines a complete proxy with its frontend and backend parts combined in one section. It is generally useful for TCP-only traffic. <name>的規范使用:All proxy names must be formed from upper and lower case letters, digits, '-' (dash), '_' (underscore) , '.' (dot) and ':' (colon). 區分字符大小寫;
-
配置參數:
-
bind:Define one or several listening addresses and/or ports in a frontend.
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:后端服務器組內的服務器調度算法
balance [ ]
balance url_param [check_post]-
算法(algorithm):
-
roundrobin:Each server is used in turns, according to their weights.
server options: weight #
動態算法:支持權重的運行時調整,支持慢啟動;每個后端中最多支持4095個server; -
static-rr:
靜態算法:不支持權重的運行時調整及慢啟動;后端主機數量無上限; -
leastconn:
推薦使用在具有較長會話的場景中,例如MySQL、LDAP等; -
first:
根據服務器在列表中的位置,自上而下進行調度;前面服務器的連接數達到上限,新請求才會分配給下一臺服務; -
source:源地址hash;把來自于同一個IP地址的請求始終發往同一個后端主機。是根據源IP地址進行綁定。
除權取余法
一致性哈希 -
uri:
- 對URI的左半部分做hash計算,并由服務器總權重相除以后派發至某挑出的服務器;此時,hash-type使用consistent算法。
-
通常后端是基于web服務器的緩存時才應該使用uri,為了保證命中率足夠高,而且不會保證因為權重的變化而變化不夠劇烈,hash-type使用consistent。不同服務器請求同一資源將都調度到同一個后端服務器。
<scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<frag> 左半部分:/<path>;<params> 整個uri:/<path>;<params>?<query>#<frag>
-
url_param:對用戶請求的uri中部分中的參數的值作hash計算,并由服務器總權重相除以后派發至某挑出的服務器;通常用于追蹤用戶,以確保來自同一個用戶的請求始終發往同一個Backend Server;
-
hdr():對于每個http請求,此處由指定的http首部將會被取出做hash計算;并由服務器總權重相除以后派發至某挑出的服務器;沒有有效值的會被輪詢調度;
hdr(Cookie) -
rdp-cookie
rdp-cookie()
微軟的遠程桌面協議
-
roundrobin:Each server is used in turns, according to their weights.
-
-
hash-type:哈希算法
hash-type <method> <function> <modifier> map-based:除權取余法,哈希數據結構是靜態的數組; consistent:一致性哈希,哈希數據結構是一個樹; <function> is the hash function to be used : 哈希函數 sdbm djb2 wt6
-
default_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; 七層檢測:請求特定資源要求其回應碼是多少,或者回應的對應內容是什么 四層檢測:對方的端口只要能響應就表示OK 三層檢測:只要主機在線就行 注意:httpchk,"smtpchk", "mysql-check", "pgsql-check" and "ssl-hello-chk" 用于定義應用層檢測方法; cookie <value>:為當前server指定其cookie值,用于實現基于cookie的會話黏性; disabled:標記為不可用; redir <prefix>:將發往此server的所有GET和HEAD類的請求重定向至指定的URL; weight <weight>:權重,默認為1;
-
統計接口啟用相關的參數:
-
stats enable
啟用統計頁;基于默認的參數啟用stats page; - stats uri : /haproxy?stats - stats realm : "HAProxy Statistics" - stats auth : no authentication - stats scope : no restriction
-
stats auth :
認證時的賬號和密碼,可使用多次; -
stats realm
認證時的realm; -
stats uri
自定義stats page uri -
stats refresh
設定自動刷新時間間隔; -
stats admin { if | unless }
啟用stats page中的管理功能配置示例: listen stats bind :9099 stats enable stats uri /haproxy?stats stats realm HAPorxy\ Stats\ Page stats auth admin:admin stats admin if TRUE
-
stats enable
-
maxconn :為指定的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 ]
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”;
-
在由haproxy發往后端主機的請求報文中添加“X-Forwarded-For”首部,其值前端客戶端的地址;用于向后端主發送真實的客戶端IP;
-
errorfile <code> <file>
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. <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> errorfile 403 http://www.magedu.com/error_pages/403.html
-
req是作用在haproxy發送給后端服務器的請求報文的首部
rsp是作用在haproxy響應給客戶端的響應報文中的首部
i 代表不區分大小寫;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系統,如果全局中本身就調用了兩次,那就意味者,此次調用要向兩處發送日志,自己添加的別的log就不在起作用了。log global log <address> [len <length>] <facility> [<level> [<minlevel>]] no log 默認發往本機的日志服務器; (1) local2.* /var/log/local2.log (2) /etc/rsyslog.conf $ModLoad imudp $UDPServerRun 514
-
log-format <string>:可定義日志格式
-
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協議的健康狀態檢測:只適用于mode 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>
持久連接的持久時長;
代理服務器面向客戶端一側盡量不使用持久連接,但是不持久每一次的連接都需要重新建立連接,可以設置持久連接的時長盡量短。以實測為準。 -
timeout http-request <timeout>
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:22 check backup
-
-
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.-
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>的類型:
- boolean
- integer or integer range
- IP address / network
- string (exact, substring, suffix, prefix, subdir, domain)
- regular expression
- hex block
-
<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. 路徑子串匹配,以/分隔;/var/www/html --> www,html - 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. 域名子串匹配,以點號分隔;www.magedu.com --> magedu.com
-
-
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
-
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
-
請求報文:hdr([<name>[,<occ>]]) : string
This extracts the last occurrence of header 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.
-
-
原創文章,作者:s,如若轉載,請注明出處:http://www.www58058.com/79370