准备4台机器
两台Haproxy 两台Hginx
1,在Nginx机上安装
yum -y install gcc gcc-c++ make pcre-devel zlib-devel
useradd -M -s /sbin/nologin nginx
tar xf nginx-1.6.2.tar.gz -C /usr/src
cd /usr/src/nginx-1.6.2
./configure --prefix=/usr/local/nginx --user=nginx --group=nginx && make && make install
cd /usr/local/nginx/html/
echo "server 192.168.200.103" > index.html
/usr/local/nginx/sbin/nginx
[netstat -anpt |grep nginxnginx
2,安装Haproxy在另外两台机器上
yum -y install gcc gcc-c++ make pcre-devel bzip2-devel
tar xf haproxy-1.4.24.tar.gz -C /usr/src/
cd /usr/src/haproxy-1.4.24/
make TARGET=linux26 && make install
3,创建一个Haproxy目录及文件
mkdir /etc/haproxy
cp examples/haproxy.cfg /etc/haproxy/
4,修改Haproxy主配置 /etc/haproxy/haproxy.cfg
------------------------------------------------修改Ip 指向另外两台nginx机ip
# 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 loghost local0 info
maxconn 4096
#chroot /usr/share/haproxy
uid 99
gid 99
daemon
#debug
#quiet
defaults
log global
mode http
option httplog
option dontlognull
retries 3
#redispatch
maxconn 2000
contimeout 5000
clitimeout 50000
srvtimeout 50000
listen web-cluster 0.0.0.0:80
option httpchk GET /index.html
balance roundrobin
server inst1 192.168.200.103:80 check inter 2000 fall 3
server inst2 192.168.200.104:80 check inter 2000 fall 3
---------------------------------------------------------------------------------------------
5,在haproxy 机 上分别安装keepalived
yum -y install keepalived
6, 编辑Keepalived 主配置文件 /etc/keepalived/keepalived.conf
修改红色字地方--------------------------------------------------------------------
! Configuration File for keepalived
vrrp_script chk_http_port {
script "/etc/keepalived/check_haproxy.sh" // 加上脚本
interval 2
weight 2
global_defs {
router_id LVS_DEVEL
}
vrrp_instance VI_1 {
state MASTER(BACKUP)
interface eth0 (..)
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
chk_http_port //指定脚本
}
virtual_ipaddress {
192.168.200.254 //虚拟网IP (访问的网)
}
}
}
-------------------------------------------------------------------------------
第二台keepalived 同上
修改权重为上面蓝字
7,创建对应的脚本 (两台keepalived)
vim /etc/keepalived/check_haproxy.sh
#!/bin/bash
num=`ps -C haproxy --no-header |wc -l`
if [ $num -eq 0 ]
then
/usr/local/haproxy/sbin/haproxy -f /usr/local/haproxy/conf/haproxy.cfg
sleep 3
if [ `ps -C haproxy --no-header |wc -l` -eq 0 ]
then
/etc/init.d/keepalived stop
fi
fi
8,给脚本相应的权限
chmod +x /etc/keepalived/check_haroxy.sh
systemctl start keepalived // 启动
service keepalived start // 另一种方法启动
9,进行测试即可
在浏览器上输入 IP
可以模拟一台keepalived 机 出错,看看vip 会不会转向另一台haproxy 机