haproxy详细介绍
Haproxy是既可以工作在7層也能工作在4層的反代工具.
Haproxy的功能:
路由HTTP請求到后端服務(wù)器,基于cookie作會話綁定.
能夠?qū)⒍鄠€請求反代至后端主機(jī)完成負(fù)載均衡的效果.
主服務(wù)器失敗時能自動切換到備服務(wù)器上.
接受特殊的端口連接完成服務(wù)監(jiān)控
拒絕新連接時不會關(guān)閉已經(jīng)連接的請求.
在兩個方向上添加、修改和刪除HTTP首部
根據(jù)特定匹配條件阻止相應(yīng)請求.
通過一個URI接口web應(yīng)用程序為通過身份驗證的用戶提供報告詳細(xì)狀態(tài).
雖然主要提供http反代,但也能反代幾乎所有基于tcp的協(xié)議
有強(qiáng)大的后端主機(jī)健康檢測功能.
支持 單一進(jìn)程模型,事件驅(qū)動,彈性二叉樹;
Haproxy程序環(huán)境(目前有這四個版本: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
網(wǎng)段計算輔助文件: /usr/bin/iprange
內(nèi)建的錯誤頁文件:
/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以及l(fā)isten提供默認(rèn)配置;
--- frontend <name>: ?相當(dāng)于nginx的server段,即一個虛擬主機(jī)負(fù)責(zé)接收客戶端的請求
--- backend <name>: 相當(dāng)于nginx的upstream段,
--- listen <name>: 它既是前端(frontend)又是后端(backend),它們是一對一的關(guān)系.換句話說就是它既有自己的前端也有自己專用的后端.
Haproxy簡單體驗
簡單修改/etc/haproxy/haproxy.cfg將http請求負(fù)載均衡到兩臺后端主機(jī)ibm1 ibm2上
因為后端主機(jī)未開啟web服務(wù),此時訪問haproxy主機(jī)會有錯誤
啟動ibm1 ibm2上的httpd服務(wù)后再次訪問
Haproxy詳細(xì)配置
golbal配置參數(shù)
進(jìn)程及安全配置相關(guān)的參數(shù)
性能調(diào)整相關(guān)的參數(shù)
Debug相關(guān)的參數(shù)
1.啟用日志
log <address> [len <length>] <facility> [max level [min level]]:定義日志系統(tǒng)相關(guān)屬性
<address>:日志服務(wù)器地址;
[len <length>]:每行日志記錄的最大長度;
<facility>: 設(shè)備
[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文件
開啟UDP日志接收
增加一行內(nèi)容
重啟rsyslog服務(wù):systemctl restart rsyslog.service
再次訪問haproxy就能在指定日志文件記錄日志了,如下圖.
2. 性能調(diào)整(大都不需要自己調(diào)整,系統(tǒng)默認(rèn)最優(yōu)化)
nbproc <number>這項可以配置haproxy進(jìn)程數(shù),默認(rèn)為1.
ulimit-n <number>則表示每個進(jìn)程可以打開的文件數(shù)量
maxconn <number>: 每個haproxy進(jìn)程的最大連接數(shù)
maxconnrate <number>:每個haproxy進(jìn)程最大連接速率(可以指定,當(dāng)大量連接涌進(jìn),可以限制速度)
maxcomprate <number>: 每秒進(jìn)站的數(shù)據(jù)壓縮率
maxcompcpuusage <number>: 壓縮時所能占用的CPU比例
maxsslconn <number>: 每個haproxy進(jìn)程所能創(chuàng)建最大的ssl并發(fā)連接數(shù)
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會話有效時長,默認(rèn)300秒
3. 用戶列表
userlist <listname>:定義用戶組及列表,示例如下代碼框.
group <groupname> [users <user>,<user>,(...)]
user <username> [password|insecure-password <password>] [groups <group>,<group>,(...)]
...
4.haproxy同步集群
peers <peersect>
disabled
enable
peer <peername> <ip>:<port>
示例:
部分代理配置參數(shù)(關(guān)鍵字)說明
mode { tcp|http|health }: defaults ? ?frontend ? ?listen ? ?backend都可用.設(shè)置haproxy工作的模式(共3種),到底是工作在應(yīng)用層還是傳輸層. ?health指工作為健康狀態(tài)檢查響應(yīng)模式,當(dāng)請求到達(dá)時僅回應(yīng)“OK”即斷開連接;
bind [<address>]:<port_range> [, ...] [param]
*bind* /<path> [, ...] [param] ?: 可使用在frontend ? ?listen中.指定監(jiān)聽地址與端口,示例如下:
acl <aclname> <criterion> [flags] [operator] <value> ...:可用在frontend ? ?listen backend中,聲明或完成一個訪問列表.
balance <algorithm> [ <arguments> ]
balance url_param <param> [check_post]: 可用在defaults,listen,backend中,定義一個在后端使用的負(fù)載平均算法.
算法中的概念:
動態(tài)-->權(quán)重運行時調(diào)整 支持慢啟動
hash-type
map-based:哈希表是一個包含了所有的可活動的主機(jī)列表
consistent: 一致性哈希,其數(shù)據(jù)結(jié)構(gòu)是"樹"
算法:
roundrobin: 動態(tài),加權(quán)輪詢,權(quán)重默認(rèn)為1.其對最多能維持4095后端活動主機(jī).
static-rr: 靜態(tài)算法,不支持權(quán)重的運行時調(diào)整,但后端主機(jī)數(shù)量無限制.
leastconn: 動態(tài)算法,擁有最少連接數(shù)的后端接受請求.
first: 忽略權(quán)重,后端服務(wù)器名稱標(biāo)識符最短的優(yōu)先
source:動態(tài)算法或靜態(tài)算法 ?原地址哈希,是否動態(tài)取決于hash-type
uri: 根據(jù)uri請求路徑(下面uri格式中黑體部分)進(jìn)行調(diào)度,適合后端主機(jī)是緩存服務(wù)器,是否動態(tài)取決于hash-type
uri格式:scheme://user:pwd@host:port/uri;params?query#fragment
url_param: 對用戶請求的url中的<param>部分中的指定的參數(shù)的值作hash計算,并由服務(wù)器總權(quán)重相除以后派發(fā)至某挑出的服務(wù)器.
hdr(<name>):The HTTP header <name> will be looked up in each HTTP ?request.指定的http首部將會被取出做hash計算,并由服務(wù)器總權(quán)重相除以后派發(fā)至某挑出的服務(wù)器;沒有有效值的會被輪詢調(diào)度.
maxconn <conns>:可用在defaults ? ?frontend ? ?listen中, 設(shè)定frontend最大的并發(fā)連接請求數(shù).1G的ram大致可以維持20000-25000個連接,默認(rèn)值為2000.
stats admin { if | unless } <cond>: 僅在滿足某些條件時才啟用管理, 盡量少啟用因為不安全
Enable statistics admin level if/unless a condition is matched
stats realm <realm>: 認(rèn)證時彈框的提示內(nèi)容.
stats auth <user>:<passwd>:可在defaults,frontend,listen,backend中使用,允許指定的認(rèn)證和授權(quán)的帳戶訪問.
stats uri <prefix>: 狀態(tài)頁面訪問uri
stats refresh <delay>: 設(shè)置刷新間隔時間.
stats hide-version: 設(shè)置隱藏haproxy版本號
stats enable: 可在defaults,frontend,listen,backend中使用,在缺少其他參數(shù)配置時會默認(rèn)如下
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?5sserver <name> <address>[:[port]] [param*]:可用在listen,backend中定義一個后端主機(jī),其中部分可選params如下:
addr <ipv4|ipv6>: 健康狀態(tài)檢測的專用地址
backup
check: 執(zhí)行健康狀態(tài)檢測.默認(rèn)為傳輸層檢測.需要執(zhí)行應(yīng)用層檢測需要"httpchk","smtpchk", "mysql-check", "pgsql-check" and "ssl-hello-chk"
inter <delay>: 時間間隔,默認(rèn)為2秒
rise <count>: 判定為"健康"狀態(tài)需要檢測的次數(shù),默認(rèn)2次.
fall <count>: 判定為"不健康"狀態(tài)需要檢測的次數(shù),默認(rèn)為3次.
port <port>:健康狀態(tài)檢測時使用的端口.
注意:默認(rèn)為傳輸層檢測,即探測端口是否能響應(yīng);需要執(zhí)行應(yīng)用層檢測,則需要httpchk, smtpchk, mysql-check, pgsql-check, ssl-hello-chk;
cookie <value>: 為當(dāng)前server指定其cookie值,此值會在收到請求報文時進(jìn)行檢測,其功能在于實現(xiàn)基于cookie會話保持.
disabled:將些server標(biāo)記為不可用,進(jìn)入維護(hù)模式.
id <value>: 為此server設(shè)置保持id(正數(shù)且唯一),當(dāng)調(diào)度算法first為根據(jù)這個數(shù)值較小的id先進(jìn)行調(diào)度
maxconn <maxconn>: 當(dāng)前server的最大并發(fā)連接數(shù).
maxqueue <maxqueue>: 當(dāng)前server的等待隊列的最大長度.
redir <prefix>: 將發(fā)往當(dāng)前server的所有請求會被重定向到別的主機(jī)(給出 scheme://host即可)如下示例:
server srv1 192.168.1.1:80 redir http://p_w_picpath1.mydomain.com check
weight <weight>: 當(dāng)前server的權(quán)重.
option httpchk: uri默認(rèn)為主頁
option httpchk <uri>
option httpchk <method> <uri>
option httpchk <method> <uri> <version>
以上在defaults,listen,backend可用,開啟HTTP協(xié)議,檢查服務(wù)器健康狀態(tài).
http-check expect [!] <match> <pattern>:在defaults ? ?,listen,backend中可用期望在做健康狀態(tài)檢測時返回的內(nèi)容
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的會話綁定,需要結(jié)合server參數(shù)的cookie參數(shù)一起實現(xiàn)
rewrite: 這個關(guān)鍵字表明 這個將由server提供的cookie以及haproxy將會修改這個cookie,如何修改呢?將server的id放入. 當(dāng)由"Set-cookie"與"Cache-control"組成的復(fù)雜的首部離開應(yīng)用程序時這個模式會便于管理.
示例1:
cookie?JSESSIONID?prefix cookie?SRV?insert?indirect?nocache cookie?SRV?insert?postonly?indirect cookie?SRV?insert?indirect?nocache?maxidle?30m?maxlife?8h示例2(結(jié)合server的cookie參數(shù)),效果如下截圖,會把server發(fā)給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?WEB2Paste_Image.png
default_backend <backend>:設(shè)定默認(rèn)的backend,當(dāng)沒有 "use_backend" 規(guī)則被匹配時.
與日志相關(guān)的
log global
log <address> [len <length>] <facility> [<level> [<minlevel>]]
no log
為frontend或backend定義日志記錄機(jī)制
示例說明
Tq: 等待客戶端發(fā)送一個完整的HTTP請求總共花費的時間(毫秒),但不計算數(shù)據(jù),-1表示未連接
Tw: 在等待各隊列時所花費的總時間(毫秒) ?It can be "-1" if the connection was aborted before reaching the queue.
Tc: 等待與最終服務(wù)器創(chuàng)建連接所需要的總時間(毫秒) 包含重試的It can be "-1" if the request was aborted before a connection could be established.
Tr:等待服務(wù)器發(fā)送一個完整的HTTP響應(yīng)總共花費的時間(毫秒),但不計算數(shù)據(jù)
Tt
capture request header <name> len <length>:捕獲并記錄于日志 最近指定的請求首部.
capture response header <name> len <length>:
示例:
錯誤頁面自定義相關(guān)參數(shù)
errorfile ?<code> <file>:Return a file contents instead of errors generated by HAProxy,可定義在defaults,frontend,listen,backend中,返回一個自定義文件內(nèi)容以替代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.httperrorloc <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
與修改請求或響應(yīng)報文相關(guān)
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開頭的響應(yīng)報頭.
超時時長相關(guān)參數(shù)
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面向客戶端一側(cè)開啟保持連接功能
timeout client-fin <timeout>
Set the inactivity timeout on the client side for half-closed connections.設(shè)置客戶端一側(cè)半關(guān)閉連接時超時時長
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相關(guān)的參數(shù)
Haproxy 完全能夠勝任從客戶端或服務(wù)器的請求與響應(yīng)流中提取數(shù)據(jù)
Access Control Lists (ACL)提供了一個靈活的解決方案去執(zhí)行內(nèi)容轉(zhuǎn)換以及根據(jù)從請求或響應(yīng)或者環(huán)境狀態(tài)做出決策.原理很簡單:
從數(shù)據(jù)流,表或環(huán)境中提取數(shù)據(jù)樣本
有選擇性地對這些數(shù)據(jù)樣本做格式轉(zhuǎn)換
根據(jù)樣例生成一個或多個匹配模式
只有當(dāng)樣本與匹配模式匹配時才對其執(zhí)行相應(yīng)動作
語法格式: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類型:
數(shù)值
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>
根據(jù)(源與目標(biāo)的)IP與端口來設(shè)置ACL:
? ?dst : ip
? ?dst_port : integer
? ?src : ip
? ?src_port : integer
示例:
ACL 7(應(yīng)用)層檢查機(jī)制用法:
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
? ?示例:
請求行首部檢查 ? ?:
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
示例:
響應(yīng)行首部檢查
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
注意:HAProxy有眾多內(nèi)建的ACLs,這些ACLs可直接調(diào)用,例如LOCALHOST,TRUE,HTTP;
HTTP層訪問控制相關(guān)的參數(shù):
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?denyTCP層訪問控制相關(guān)的參數(shù):
tcp-request connection <action> [{if | unless} <condition>]
Perform an action on an incoming connection depending on a layer 4 condition
示例
tcp-request content <action> [{if | unless} <condition>]
Perform an action on a new session depending on a layer 4-7 condition
示例:
?后端主機(jī)調(diào)用:
? ? ? ? ? ?use_backend <backend> [{if | unless} <condition>]
? ? ? ? ? ? ? ?Switch to a specific backend if/unless an ACL-based condition is matched.
轉(zhuǎn)載于:https://blog.51cto.com/11886896/1883662
總結(jié)
以上是生活随笔為你收集整理的haproxy详细介绍的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: write() vs. writev()
- 下一篇: 产品经理面试题目转载