haproxy詳細介紹

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 [email protected] 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://p_w_picpath1.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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章