haproxy入門(mac)

轉自:http://www.cnblogs.com/yjmyzz/p/haproxy.html

apache、nginx之類的反向代理(轉發)功能,通常只能用於http協議,其它協議就不好使了(注:nginx據說商業版的,支持tcp協議了)。

haproxy可以彌補這方面的不足,haproxy支持http/tcp多種協議,可以當做rpc(thrift/gRPC/avro)框架前端的負載均衡轉發中間件,下面介紹基本使用:

以下環境均爲mac OSX。

一、安裝

brew install haproxy 

默認安裝的是1.6.0版本,注:沒安裝 brew的,請先訪問http://brew.sh/ 安裝

安裝後的路徑爲:

/usr/local/Cellar/haproxy/1.6.0

或者,也可以直接上官網http://www.haproxy.org/#down 下載

安裝完成後,輸入

haproxy -version 如果能看到類似下面的輸出:

HA-Proxy version 1.6.0 2015/10/13
Copyright 2000-2015 Willy Tarreau <[email protected]>

表示安裝成功

 

二、http轉發配置

隨便找個目錄(比如:~/work/cfg/),創建haproxy.cfg文件(文件名隨意),參考內容如下:

複製代碼
global
    daemon
    maxconn 256

defaults
    mode http
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms

listen http-in
    bind *:9000
    server server1 127.0.0.1:8081 maxconn 32
複製代碼

主要是最後三行,表示將本機9000端口的http訪問,轉發到127.0.0.1:8081端口,即訪問: http://127.0.0.1:9000 相當於訪問http://127.0.0.1:8081

 

三、啓動

haproxy -f ~/work/cfg/haproxy.cfg -d 

正常的話,會輸出下面這些:

Available polling systems :
kqueue : pref=300, test result OK
poll : pref=200, test result OK
select : pref=150, test result OK
Total: 3 (3 usable), will use kqueue.
Using kqueue() as the polling mechanism.

 

此時,訪問http://localhost:9000/ 應該有結果 ,同時終端會有相關的信息輸出

注:如果啓動時,提示bind某端口失敗之類的,先檢查端口是否被佔用

命令 lsof -i tcp:port  (port替換成端口號,比如9000)可以查看該端口被什麼程序佔用,並顯示pid,方便kill進程

如果端口也未佔用,嘗試換成一個高一些的端口,我在mac本機嘗試時,剛開始使用80或81端口,始終起不來,用上述命令查端口占用,也沒被佔用,換成一個高位端口後,才正常啓動,不知道是不是個別現象。

 

四、http負載均衡示例

複製代碼
global
    daemon
    maxconn 256

defaults
    mode http
    stats enable
    stats uri /haproxy-stats
    stats refresh 10s
    monitor-uri /haproxy-test
    balance roundrobin
    option httpclose
    option forwardfor
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms

listen my-web-cluster1
    bind *:9000
    server server1 127.0.0.1:80
    server server2 192.168.1.14:80
複製代碼

上面的配置表示,訪問http://localhost:9000/時,會轉發到127.0.0.1:80或192.168.1.14:80中的一臺

另外,訪問 http://localhost:9000/haproxy-stats 還能看到一個統計頁面, http://localhost:9000/haproxy-test 用於測試haproxy工作是否正常

 

五、tcp負載均衡配置示例

複製代碼
 1 global
 2     daemon
 3     nbproc 1
 4     pidfile /Users/yjmyzz/work/pid/haproxy.pid
 5 
 6 defaults
 7     mode tcp
 8     retries 3
 9     option redispatch
10     option abortonclose
11     maxconn 4096
12     timeout connect 5000ms
13     timeout client 30000ms
14     timeout server 30000ms
15     log 127.0.0.1 local0 notice err
16 
17 listen thrift-cluster
18     bind *:33210
19     mode tcp
20     balance roundrobin
21     server server1 localhost:33208
22     server server2 localhost:33209
複製代碼

注意下:8,9這二行,這表示如果某個節點掛了,重試3次以後,會轉發到其它節點,即單點故障遷移

 

參考文章:

http://cbonte.github.io/haproxy-dconv/configuration-1.6.html

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