haproxy 新手上路

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 <willy@haproxy.org>

表示安装成功

 

二、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

posted @ 2015-11-05 14:32  菩提树下的杨过  阅读(6734)  评论(2编辑  收藏  举报