基于 Haproxy 构建负载均衡集群
案例环境:
主机 操作系统 IP地址 主要的软件
----------------------------------------------------------------------------
Haproxy CentOS6.6 x86_64 192.168.200.101 haproxy-1.4.24.tar.gz
Nginx1 CentOS6.6 x86_64 192.168.200.103 nginx-1.6.2.tar.gz
Nginx2 CentOS6.6 x86_64 192.168.200.104 nginx-1.6.2.tar.gz
配置负载均衡服务器
1.安装Haproxy依赖包及源码包编译安装
yum -y install gcc gcc-c++ make pcre-devel bzip2-devel
2.将准备好的软件包解压
tar xf haproxy-1.4.24.tar.gz -C /usr/src/
3.编译安装
cd /usr/src/haproxy-1.4.24/
make TARGET=linux26 && make install
4.建立haproxy的配置目录及文件
mkdir /etc/haproxy
cp examples/haproxy.cfg /etc/haproxy/
5.haproxy 配置文件修改
vim /etc/haproxy/haproxy.cfg
# this config needs haproxy-1.1.28 or haproxy-1.2.1
global
# log 127.0.0.1 local0
# log 127.0.0.1 local1 notice
log
/dev/log
local0 info
log
/dev/log
local0 notice
maxconn 4096
uid 99
gid 99
daemon
defaults
log global
mode http
option httplog
retries 3
maxconn 4096
contimeout 5000
clitimeout 50000
srvtimeout 50000
listen webcluster 0.0.0.0:80
option httpchk GET
/index
.html
balance roundrobin
server inst1 192.168.200.113:80 check inter 2000 fall 3
server inst1 192.168.200.114:80 check inter 2000 fall 3
listen admin_stats
bind 0.0.0.0:8000
mode http
option httplog
maxconn 100
stats refresh 30s
stats uri
/stats
stats realm Crushlinux\ Haproxy
stats auth admin:admin
stats hide-version
ln -s /usr/local/sbin/haproxy /usr/sbin/haproxy
chmod +x /etc/init.d/haproxy
/etc/init.d/haproxy start
netstat -anpt |grep :80
killall -s HUP nginx 重新加载服务
killall -s QUIT nginx 退出服务
测试环境:
用浏览器打开 http://192.168.200.111
打开一个新的浏览器再次访问 http://192.168.200.111
可以验证两次访问到的结果分别为:
server 192.168.200.113
server 192.168.200.114
Haproxy 日志文件:
1.添加日志文件
vim /etc/haproxy/haproxy
# this config needs haproxy-1.1.28 or haproxy-1.2.1
global
#log 127.0.0.1 local0
#log 127.0.0.1 local1 notice
log
/dev/log
local0 info
log
/dev/log
local0 notice
if
($programname ==
'haproxy'
and $syslogserverity-text ==
'info'
)
then
-
/var/log/haproxy/haproxy-info
.log
&~
if
($programname ==
'haproxy'
and $syslogserverity-text ==
'notice'
)
then
-
/var/log/haproxy/haproxy-notice
.log
&~