方案:
利用keepalived+nginx实现官网web的高可用性
两台服务器一台为主,一台为备机,使两台机器公用一个虚拟IP,当主服务器宕机,106.3.32.6这个IP会自动切换到备机上,前端机恢复之后再自动切换回主服务机
然后,主服务机和备机利用rsync实现实时同步数据,
rsync的安装配置可以参照我之前的一篇文章:http://cuimk.blog.51cto.com/6649029/1322241
环境:
CentOS 6.4
nginx-1.2.1
keepalived-1.2.2
一、安装
主和辅都需要安装keepalived,安装方法相同
yum -y install kernel-develyum install openssl-* -ywget http://www.keepalived.org/software/keepalived-1.2.2.tar.gztar xzf keepalived-1.2.2.tar.gzcd keepalived-1.2.2./configure --prefix=/usr/local/keepalivedmake && make installln -s /usr/src/kernels/2.6.18-238.el5-i686/ /usr/src/linuxcp /usr/local/keepalived/etc/rc.d/init.d/keepalived /etc/init.d/cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/mkdir -pv /etc/keepalivedcp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/ln -s /usr/local/keepalived/sbin/keepalived /sbin/
加入开机启动:chkconfigkeepalived on
二、配置
主和辅配置的差别只在stateMASTER和priority 100
vi /etc/keepalived/keepalived.conf
! Configuration File for keepalivedglobal_defs {# notification_email { ####此处定义发生替换会邮件通知# cuimingkun@yinwuweiye.com# }# notification_email_from keepalived@domain.com# smtp_server 127.0.0.1# smtp_connect_timeout 30 router_id LVS_DEVEL}vrrp_script chk_http_port { script "/root/shell/nginx_pid.sh" ##监控脚本位置 interval 2 weight 2}track_script { chk_http_port }vrrp_instance VI_1 { state MASTER #####备机为BACKUP interface em1 virtual_router_id 51 priority 100 #####备机要小于主 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 106.3.32.6 ####虚拟IP }}
三、分别在主和辅服务器上建立nginx的监控脚本
Keepalived管理虚IP是通过组播和优先级实现的,优先级高的会拥有虚IP的管理权,所以要实现IP自动切换,只需要建立一个监控脚本,让keepalived进行调用,一旦发现nginx出现故障就kill掉keepalived的进程,让其他keepalived管理此IP
vi /root/shell/nginx_pid.sh
#!/bin/bashA=`ps -C nginx --no-header |wc -l` if [ $A -eq 0 ];then /usr/local/nginx/sbin/nginx sleep 3 if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then killall keepalived fifi
注意给脚本添加执行权限:chmod+x /root/shell/nginx_pid.sh
两台机器启动keepalived:service keepalived start
四、测试
#ip a查看IP
查看主的IP,目前虚IP在主这里
Kill掉主的keepalived,再查看,虚IP消失
查看辅的这边,可以看到虚IP
再启动主的keepalived,虚IP又回到主的这边
五、总结
此方案没有做负载均衡,只是做了一个故障自动切换的处理,适用于PV不是很高的环境(当然Nginx做好调优其负载能力也是很强的),不过可以以同样的原理举一反三,把他做在高并发的负载均衡器上,来实现高必发的容灾方案!