本文写于 2014 年。
Haproxy 是主流的负载均衡方案,常用于四层负载。

运行环境

CentOS 7 64bit
HAProxy 1.6.9

需求说明

安装 HAProxy,对外提供 TCP 反向代理服务

安装过程

1.下载安装包

wget http://www.haproxy.org/download/1.6/src/haproxy-1.6.9.tar.gz

2.解压缩

tar -zxvf haproxy-1.6.9.tar.gz

3.编译安装

cd haproxy-1.6.9
make TARGET=linux2628 PRFIX=/work/admin/haprpxy ##根据内核版本选择TARGET
make install PREFIX=/work/admin/haproxy

4.初始化配置

目录初始化

cd /work/admin/haproxy
mkdir logs
mkdir conf

配置文件初始化

cd conf
vim haproxy.cfg
global

daemon
nbproc 2
maxconn 65535
pidfile /work/admin/haproxy/logs/haproxy.pid

defaults

mode tcp
maxconn 65535
retries 3
balance roundrobin
option redispatch
option abortonclose
timeout connect 3000ms
timeout client 50000ms
timeout server 50000ms

listen server
bind 0.0.0.0:8080
balance roundrobin
mode tcp
server server1 192.168.1.1:8080 weight 1 maxconn 10240 check inter 10s

listen status
bind 0.0.0.0:8888
mode http
stats enable
stats uri /status
stats auth admin:password
stats realm (Haproxy\ statistic)

5.命令

启动

/work/admin/haproxy/sbin/haproxy -f /work/admin/haproxy/conf/haproxy.cfg

重启

/work/admin/haproxy/sbin/haproxy -f /work/admin/haproxy/conf/haproxy.cfg -st `cat /work/admin/haproxy/logs/haproxy.pid`

平滑重启

/work/admin/haproxy/sbin/haproxy -f /work/admin/haproxy/conf/haproxy.cfg -sf `cat /work/admin/haproxy/logs/haproxy.pid`

关闭

killall haproxy
重启参数-st
-st <pidlist>
Send TERMINATE signal to the pids in pidlist after startup. The processes which receive this signal will wait immediately terminate, closing all active sessions. This option must be specified last, followed by any number of PIDs. Technically speaking, SIGTTOU and SIGTERM are sent.
平滑重启参数-sf
-sf <pidlist>
Send FINISH signal to the pids in pidlist after startup. The processes which receive this signal will wait for all sessions to finish before exiting. This option must be specified last, followed by any number of PIDs. Technically speaking, SIGTTOU and SIGUSR1 are sent.

6.端口耗尽问题

可参考:http://blog.sina.com.cn/s/blog_704836f40101jv9h.html(未验证)

7.开启rsyslog日志

haproxy增加配置

global
log 127.0.0.1 local0
......
defaults
log global

修改rsyslog配置

vim /etc/rsyslog.conf
# Provides UDP syslog reception
$ModLoad imudp
$UDPServerRun 514

local0.* /work/admin/haproxy/logs/haproxy.log

重启rsyslog服务

service rsyslog restart

重启haproxy服务

日志输出到/work/admin/harpxy/logs/haproxy.log