HAProxy 是一套快速以及靈活的load balance套件,透過haproxy可以快速達到server分流、判斷存活、連線數量等功能。當流量達到一定的程度後load balance是一大重點,如何讓各server平均去負擔流量是相當重要的,透過haproxy可以簡單快速的達成load balance。
準備
架構

安裝
1 2 3 4 | tar -xvf haproxy-1.3.15.7.tar.gz cd haproxy-1.3.15.7 make TARGET=linux26 cp haproxy /usr/local/sbin/ |
設定檔
/etc/haproxy.conf
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | global
# maximum number of simultaneous active connections from an upstream web server
maxconn 4096
# 運行haproxy使用者及群組
user nobody
group nobody
# 存放運行haproxy的process id 檔案
pidfile /var/run/haproxy.pid
# 在背後運行haproxy
daemon
defaults
#Define the load balancing algorithm to be used in a backend
balance roundrobin
#Set the running mode or protocol of the instance
mode http
#重試次數
retries 3
#Enable or disable session redistribution in case of connection failure
option redispatch
#Enable or disable passive HTTP connection closing
option httpclose
# Enable or disable forced persistence on down servers
option persist
#Enable insertion of the X-Forwarded-For header to requests sent to servers
option forwardfor
#Set the maximum time to wait for a connection attempt to a server to succeed.
contimeout 5000
#Set the maximum inactivity time on the client side.
clitimeout 50000
#Set the maximum inactivity time on the server side.
srvtimeout 50000
# Enable the statistics page
stats enable
stats auth user:password
stats uri /haproxy?stats
stats realm Haproxy\ Statistics
stats auth haproxy:stats
listen 192.168.1.203 :80
server 192.168.1.200 192.168.1.200 cookie sv1 check
server 192.168.1.201 192.168.1.201 cookie sv2 check
server 192.168.1.202 192.168.1.202 cookie sv3 check |
檢查設定檔
1 2 | haproxy -c -f /etc/haproxy.conf Configuration file is valid : haproxy.conf # <= 表示設定檔無錯誤 |
啟動
1 | haproxy -f /etc/haproxy.conf |
壓力測試
1 | ab -n 10000 -c 250 http://jquery.shian.tw/index.php?m=main |
Statistics
注意
啟動前必須先檢查80 port 是否有在使用
結論
經過上面的壓力測試後再觀察haproxy Statistics,發現真的有把連線數平均分散到其它三台server上,而且當某一台server連線數過高後則會停止分配到這台server,這點還蠻不錯的。另外haproxy可以直接在網頁上觀看目前各server狀態、連線數等資料,相當的方便。
參考資料
- http://haproxy.1wt.eu/
- http://wiki.railsmachine.com/HAProxy
- http://plog.longwin.com.tw/my_note-unix/2009/03/23/haproxy-ha-load-balance-2009

this article let me learn more , thanks