Nginx+keepalived主从双机热备自动切换解决方案
??
?
这篇文章简单介绍利用keepalived软件,实现对nginx服务器的高可用,即实现故障自动切换。假设你已经安装好nginx,下面介绍keepalived的安装和使用。
keepalived安装- yum install openssl-devel
- cd /tmp
- wget http://www.keepalived.org/software/keepalived-1.2.2.tar.gz
- tar xzf keepalived-1.2.2.tar.gz
- cd keepalived-1.2.2
- ./configure
- make && make install
- cp /usr/local/etc/rc.d/init.d/keepalived /etc/init.d/
- cp /usr/local/etc/sysconfig/keepalived /etc/sysconfig/
- chmod +x /etc/init.d/keepalived
- chkconfig --add keepalived
- chkconfig keepalived on
- mkdir /etc/keepalived
- ln -s /usr/local/sbin/keepalived /usr/sbin/
keepalived的配置
更详细的keepalived配置文件说明可以执行man keepalived.conf查看。
我们假设主服务器IP:192.168.1.103,从服务器ip:192.168.1.101 虚拟ip:192.168.1.110
下面对主服务器的keepalived进行配置:
- vi /etc/keepalived/keepalived.conf
- global_defs {
- ?? notification_email {
- ?? ? admin@centos.bz
- ?? }
- ?? 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 "/opt/nginx_pid.sh"
- ?? ? ? ? ? ? ? ?interval 2
- ?? ? ? ? ? ? ? ?weight 2
- }
- vrrp_instance VI_1 {
- ?? ?state MASTER? ? ? ? ############ 辅机为 BACKUP
- ?? ?interface eth0
- ?? ?virtual_router_id 51
- ?? ?mcast_src_ip 192.168.1.103
- ?? ?priority 102? ? ? ? ? ? ? ? ? ########### 权值要比 back 高
- ?? ?advert_int 1
- ?? ?authentication {
- ?? ? ? ?auth_type PASS
- ?? ? ? ?auth_pass 1111
- ?? ?}
- track_script {?
- ?? ? ? ?chk_http_port ### 执行监控的服务?
- ?? ? ? ?}
- ?? ?virtual_ipaddress {
- ?? ? ? 192.168.1.110
- ?? ?}
- }
从服务器:
- global_defs {
- ?? notification_email {
- ?? ? admin@centos.bz
- ?? }
- ?? 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 "/opt/nginx_pid.sh"
- ?? ? ? ? ? ? ? ?interval 2
- ?? ? ? ? ? ? ? ?weight 2
- }
- vrrp_instance VI_1 {
- ?? ?state BACKUP
- ?? ?interface eth0
- ?? ?virtual_router_id 51
- ?? ?mcast_src_ip 192.168.1.101
- ?? ?priority 101? ? ? ? ? ? ? ##########权值 要比 master 低。。
- ?? ?advert_int 1
- ?? ?authentication {
- ?? ? ? ?auth_type PASS
- ?? ? ? ?auth_pass 1111
- ?? ?}
- track_script {?
- ?? ? ? ?chk_http_port ### 执行监控的服务?
- ?? ? ? ?}
- ?? ?virtual_ipaddress {
- ?? ? ? 192.168.1.110
- ?? ?}
- }
之后分别在主从服务器建立nginx的监控脚本:
- vi /opt/nginx_pid.sh
- #!/bin/bash
- A=`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
- ?? ? ? ? ? ? ? ?fi
- fi
然后分别启动主从服务器的keepalived:
- service keepalived start
我们在主服务器上执行命令ip a,显示如下:
证明主服务器已经绑定了虚拟ip 192.168.1.110
在从服务器上执行命令ip a,显示如下:
显示表明从服务器上没有绑定vip 192.168.1.110,只有本机真实ip192.168.1.101
下面我们停止主服务器的nginx进程,再看看ip绑定情况:
主服务器的情况:
从服务器的情况:
由此可见vip已经指向了从服务器。