上一篇讲了nginx+tomcat搭建了反向代理和负载均衡
那么如果nginx挂掉了 即使两个tomcat都没有挂也是无法访问的
所以这个时候需要一个主备管理 如果主nginx挂了立即由备用nginx来接管
那么我们需要现搭建一个备用的nginx配置方式和主nginx完全相同
此时 主服务器和备服务器是两个不同的IP 我们必须将两个IP映射出一个相同的虚拟IP
目前两个nginx 的IP 分别为
主 192.168.80.141
备 192.168.80.142
我们将虚拟IP配置为 192.168.80.161
1 将 两个nginx的虚拟IP配置成 192.168.80.161
# cd /etc/init.d
# vi realserver
打开编辑器后 编辑以下脚本
SNS_VIP=192.168.80.161
. /etc/rc.d/init.d/functions
case "$1" in
start)
ifconfig lo:0 $SNS_VIP netmask 255.255.255.255 broadcast $SNS_VIP
/sbin/route add -host $SNS_VIP dev lo:0
echo "1" >/proc/sys/net/ipv4/conf/lo/arp_ignore
echo "2" >/proc/sys/net/ipv4/conf/lo/arp_announce
echo "1" >/proc/sys/net/ipv4/conf/all/arp_ignore
echo "2" >/proc/sys/net/ipv4/conf/all/arp_announce
sysctl -p >/dev/null 2>&1
echo "RealServer Start OK"
;;
stop)
ifconfig lo:0 down
route del $SNS_VIP >/dev/null 2>&1
echo "0" >/proc/sys/net/ipv4/conf/lo/arp_ignore
echo "0" >/proc/sys/net/ipv4/conf/lo/arp_announce
echo "0" >/proc/sys/net/ipv4/conf/all/arp_ignore
echo "0" >/proc/sys/net/ipv4/conf/all/arp_announce
echo "RealServer Stoped"
;;
*)
echo "Usage: $0 {start|stop}"
exit 1
esac
exit 0
2 编辑后 保存退出 改变该文件的权限 # chmod 750 realserver
3 启动 # service realserver start
安装keepalived
1 # yum -y install keepalived
2 更改配置 # vi /etc/keepalived/keepalived.conf
主:
global_defs {
# notification_email {
# admin@toxingwang.com
# }
# notification_email_from master@toxingwang.com
# smtp_server smtp.exmail.qq.com
# smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_instance VI_1 {
state MASTER //此处如果是备用则
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.80.161
}
}
virtual_server 192.168.80.161 80 {
delay_loop 6
lb_algo wrr
lb_kind DR
nat_mask 255.255.255.0
persistence_timeout 0
protocol TCP
real_server 192.168.80.141 80 {
weight 1
TCP_CHECK {
connect_timeout 10
nb_get_retry 3
delay_before_retry 3
connect_port 80
}
}
}
备:
global_defs {
# notification_email {
# admin@toxingwang.com
# }
# notification_email_from master@toxingwang.com
# smtp_server smtp.exmail.qq.com
# smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_instance VI_1 {
state BACKUP
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.80.161
}
}
virtual_server 192.168.80.161 80 {
delay_loop 6
lb_algo wrr
lb_kind DR
nat_mask 255.255.255.0
persistence_timeout 0
protocol TCP
real_server 192.168.80.142 80 {
weight 1
TCP_CHECK {
connect_timeout 10
nb_get_retry 3
delay_before_retry 3
connect_port 80
}
}
}
配置虚拟IP和对应的真实服务器地址
3 启动keepalived # service keepalived start
此时tomcat访问地址为 http://192.168.80.161/
即使nginx1挂掉了 也可以访问到了