haproxy代理服務

HAProxy:
LB Cluster:
        四層:   lvs, nginx(stream),haproxy(mode tcp)
        七層:   http: nginx(http, ngx_http_upstream_module), haproxy(mode http), httpd, ats, perlbal, pound…
HAProxy:
             http://www.haproxy.org
             http://www.haproxy.com 
文檔參考:
            http://cbonte.github.io/haproxy-dconv/
HAProxy is a TCP/HTTP reverse proxy which is particularly suited for high availability environments. Indeed, it can:
 – route HTTP requests depending on statically assigned cookies
 – spread load among several servers while assuring server persistence
   through the use of HTTP cookies
 – switch to backup servers in the event a main server fails
 – accept connections to special ports dedicated to service monitoring
 – stop accepting connections without breaking existing ones
 – add, modify, and delete HTTP headers in both directions
 – block requests matching particular patterns
 – report detailed status to authenticated users from a URI intercepted by the application

程序環境:
主程序:/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                                      #監聽服務器上的80端口,可以監聽具體地址端口
default_backend     websrvs            #默認后端   websrvs

backend websrvs                            #定義后端名字,和前對定義的后端名字統一
balance roundrobin                          # 算法  動態輪詢
server srv1 172.16.100.6:80 check             #后端服務器地址和端口,check是做健康檢查
server srv2 172.16.100.7:80 check

global配置參數:
          進程及安全管理:chroot, deamon,user, group, uid, gid

log:定義全局的syslog服務器;最多可以定義兩個;
          log <address> [len <length>] <facility> [max level [min level]]

nbproc <number>:要啟動的haproxy的進程數量;
ulimit-n <number>:每個haproxy進程可打開的最大文件數;

性能調整:

maxconn <number>:設定每個haproxy進程所能接受的最大并發連接數;

                        Sets the maximum per-process number of concurrent connections to <number>.

maxconnrate <number>:Sets the maximum per-process number of connections per second to <number>. 

                        每個進程每秒種所能創建的最大連接數量;

maxsessrate <number>:
maxsslconn <number>: Sets the maximum per-process number of concurrent SSL connections to <number>.
spread-checks <0..50, in percent>

代理配置段:                               #后面的name都是隨便定義,和作用相關
– defaults <name>
– frontend <name>
– backend  <name>
– listen   <name>

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.

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 <algorithm> [ <arguments> ]
balance url_param <param> [check_post]

算法:
         roundrobin:Each server is used in turns, according to their weights.
                server options: weight #
                          動態算法:支持權重的運行時調整,支持慢啟動;每個后端中最多支持4095個server;
                static-rr:
                          靜態算法:不支持權重的運行時調整及慢啟動;后端主機數量無上限;

leastconn:
     推薦使用在具有較長會話的場景中,例如MySQL、LDAP等;

first:
     根據服務器在列表中的位置,自上而下進行調度;前面服務器的連接數達到上限,新請求才會分配給下一臺服務;

source:源地址hash;
           除權取余法:
           一致性哈希:

uri:
對URI的左半部分做hash計算,并由服務器總權重相除以后派發至某挑出的服務器;

<scheme>://<user>:<password>@<host>:<port>/<path>;<params>?<query>#<frag>
左半部分:/<path>;<params>
整個uri:/<path>;<params>?<query>#<frag>

url_param:對用戶請求的uri聽<params>部分中的參數的值作hash計算,并由服務器總權重相除以后派發至某挑出的服務器;通常用于追蹤用戶,以確保來自同一個用戶的請求始終發往同一個Backend Server;

hdr(<name>):對于每個http請求,此處由<name>指定的http首部將會被取出做hash計算; 并由服務器總權重相除以后派發至某挑出的服務器;沒有有效值的會被輪詢調度; 
hdr(Cookie)

rdp-cookie
rdp-cookie(<name>)

hash-type:哈希算法
         hash-type <method> <function> <modifier>
                    map-based:除權取余法,哈希數據結構是靜態的數組;
                    consistent:一致性哈希,哈希數據結構是一個樹;

<function> is the hash function to be used : 哈希函數
       sdbm
       djb2
       wt6

default_backend <backend>
         設定默認的backend,用于frontend中;

default-server [param*]
         為backend中的各server設定默認選項;

回顧:
tcp/http reverse proxy;
haproxy.cfg
global, proxies
proxies:
defaults
frontend
listen
backend

proxies:bind、balance、hash-type、default_backend、server
balance:
        roundrobin、static-rr、leastconn、first、source、uri、hdr(<HEADER>)、url_param、…

HAProxy(2)
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;

注意: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 <user>:<passwd>
認證時的賬號和密碼,可使用多次;

stats realm <realm>
認證時的realm;

stats uri <prefix>
自定義stats page uri

stats refresh <delay>
設定自動刷新時間間隔;

stats admin { if | unless } <cond>
啟用stats page中的管理功能

配置示例:
listen stats
bind :9099
stats enable
stats realm HAPorxy\ Stats\ Page
stats auth admin:admin
stats admin if TRUE

maxconn <conns>:為指定的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”;

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

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 <address> [len <length>] <facility> [<level> [<minlevel>]]
      no log

注意:
默認發往本機的日志服務器;
(1) local2.
     /var/log/local2.log 
(2) $ModLoad imudp
$UDPServerRun 514

log-format <string>:
課外實踐:參考文檔實現combined格式的記錄

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協議的健康狀態檢測:
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

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.
– 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.

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

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 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.

Pre-defined ACLs
ACL name Equivalent to Usage
FALSE always_false never match
HTTP req_proto_http match if protocol is valid HTTP
HTTP_1.0 req_ver 1.0 match HTTP version 1.0
HTTP_1.1 req_ver 1.1 match HTTP version 1.1
HTTP_CONTENT hdr_val(content-length) gt 0 match an existing content-length
HTTP_URL_ABS url_reg ^[^/:]*:// match absolute URL with scheme
HTTP_URL_SLASH url_beg / match URL beginning with “/”
HTTP_URL_STAR url * match URL equal to “*”
LOCALHOST src 127.0.0.1/8 match connection from local host
METH_CONNECT method CONNECT match HTTP CONNECT method
METH_GET method GET HEAD match HTTP GET or HEAD method
METH_HEAD method HEAD match HTTP HEAD method
METH_OPTIONS method OPTIONS match HTTP OPTIONS method
METH_POST method POST match HTTP POST method
METH_TRACE method TRACE match HTTP TRACE method
RDP_COOKIE req_rdp_cookie_cnt gt 0 match presence of an RDP cookie
REQ_CONTENT req_len gt 0 match data in the request buffer
TRUE always_true always match
WAIT_END wait_end wait for end of content analysis

HAProxy:global, proxies(fronted, backend, listen, defaults)
balance:
roundrobin, static-rr
leastconn
first
source
hdr(<name>)
uri (hash-type)
url_param

Nginx調度算法: ip_hash, hash, leastconn, 
lvs調度算法:     rr/wrr/sh/dh, lc/wlc/sed/nq/lblc/lblcr

基于ACL的動靜分離示例:
frontend  web *:80
acl url_static       path_beg       -i  /static /images /javascript /stylesheets
acl url_static       path_end       -i  .jpg .gif .png .css .js .html .txt .htm

use_backend staticsrvs          if url_static
default_backend             appsrvs

backend staticsrvs
balance     roundrobin
server      stcsrv1 172.16.100.6:80 check

backend appsrvs
balance     roundrobin
server  app1 172.16.100.7:80 check
server  app1 172.16.100.7:8080 check

listen stats
bind :9091
stats enable
stats auth admin:admin
stats admin if TRUE

配置HAProxy支持https協議: 
1 支持ssl會話;
bind *:443 ssl crt /PATH/TO/SOME_PEM_FILE

crt后的證書文件要求PEM格式,且同時包含證書和與之匹配的所有私鑰;

cat  demo.crt demo.key > demo.pem 

2 把80端口的請求重向定443;
bind *:80
redirect scheme https if !{ ssl_fc }

3 如何向后端傳遞用戶請求的協議和端口
http_request set-header X-Forwarded-Port %[dst_port]
http_request add-header X-Forwared-Proto https if { ssl_fc }

原創文章,作者:shewei,如若轉載,請注明出處:http://www.www58058.com/76089

(1)
sheweishewei
上一篇 2017-05-17
下一篇 2017-05-17

相關推薦

  • N26-第五周

    1、顯示當前系統上root、fedora或user1用戶的默認shell;[root@localhost ~]# grep -E ‘^(root|fedora|user1)\>’ /etc/passwdroot:x:0:0:root:/root:/bin/bashfedora:x:4002:4002:Fedora Core:/h…

    Linux干貨 2017-03-13
  • Linux發展史

    Linux發展史 操作系統出現前:   1946年第一臺計算機誕生–20世紀50年代中期,還未出現操作系統,計算機工作采用手工操作方式。程序員將對應于程序和數據的已穿孔的紙帶(或卡片)裝入輸入機,然后啟動輸入機把程序和數據輸入計算機內存,接著通過控制臺開關啟動程序針對數據運行;計算完畢,打印機輸出計算結果;用戶取走結果并卸下紙帶(或卡片…

    Linux干貨 2016-10-14
  • CentOS 更改改網卡名稱

    1 查看你的CentOS7網卡名字叫什么(通常第一個網卡叫做eno16777736) ip addr 2 編輯配置文件 vi /etc/sysconfig/network-scripts/ifcfg-eno16777736 把配置文件里面所有eno16777736改為eth0 3 把網卡配置文件名字也修改一下 cd?/etc/sysconfig/networ…

    2018-01-18
  • rpm包管理

    rpm包管理 rpm(RedHat Package Manager) 是RedHat公司發展的一種將軟件安裝到Linux系統的管理機制,也是一種數據庫記錄方法。 Linux系統上軟件的安裝主要分兩種方式,從廠商發布的tarball通過編譯來安裝;或者使用廠商已經在相應平臺上編譯好的二進制文件。 從源碼編譯安裝的程序,在漏洞修補以及軟件功能升級時太過麻煩,并且…

    Linux干貨 2016-11-18
  • Linux基礎目錄名稱及功用

    FHS目錄規則 Filesystem Hierarchy Standard(文件系統目錄標準)的縮寫,多數Linux版本采用這種文件組織形式,類似于Windows操作系統中c盤的文件目錄,FHS采用樹形結構組織文件。FHS定義了系統中每個區域的用途、所需要的最小構成的文件和目錄,同時還給出了例外處理與矛盾處理。   FHS定義了兩層規范,第一層是,…

    Linux干貨 2016-10-30
  • linux網絡管理(基礎-IP、MAC、TCP)

    linux網絡管理 計算機網絡 MACMAC(Media Access Control或者Medium Access Control)地址,意譯為媒體訪問控制、介質訪問控制,或稱為物理地址、硬件地址,用來定義網絡設備的位置。在OSI模型中,第三層網絡層負責IP地址,第二層數據鏈路層則負責MAC地址。因此一個主機會有一個MAC地址,而每個網絡位置會有一個專屬于…

    Linux干貨 2016-09-09
欧美性久久久久