ngixn负载均衡高可用-主备切换keepalived实现

1.环境
  • 操作系统

    CentOS release 6.10 (Final)

  • 主机规划

    IP 用途
    192.168.47.110 nginx + keepalived master(主)
    192.168.47.21 nginx + keepalived backup(备)
    192.168.47.20 vip,对外提供服务访问IP
  • 访问流程
    ngixn负载均衡高可用-主备切换keepalived实现_第1张图片

2.安装keepalived
  • 主和备机都需要安装好nginx,具体安装步骤可参考博文:
    https://blog.csdn.net/cen50958/article/details/89645100
  • 主机和备机都需要安装keeplive

    yum install keepalived -y

3.1 keepalived监控nginx存活脚本
#!/bin/bash
counter=$(ps -C nginx --no-heading|wc -l)
if [ "${counter}" = "0" ]; then
    /usr/local/nginx/sbin/nginx
    sleep 2
    counter=$(ps -C nginx --no-heading|wc -l)
    if [ "${counter}" = "0" ]; then
        /etc/init.d/keepalived stop
    fi
fi
3.2 主keepalived配置文件

vim /etc/keepalived/keepalived.conf

! Configuration File for keepalived

global_defs {
   notification_email {
     [email protected]
   }
   notification_email_from [email protected]
   smtp_server 192.168.200.1
   smtp_connect_timeout 30
   router_id LVS_DEVEL
}

vrrp_script chk_nginx {      
    script "/server/scripts/chk_nginx.sh"  
    interval 2                 
    weight -5                 
    fall 2                  
    rise 1           
}

vrrp_instance VI_1 {
    state MASTER
    interface eth0
    virtual_router_id 51
    priority 200
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.47.20
    }
    track_script {                     
       chk_nginx             
    }
}
3.3 备keepalived配置文件
! Configuration File for keepalived

global_defs {
   notification_email {
     [email protected]
   }
   notification_email_from [email protected]
   smtp_server 192.168.200.1
   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.47.20
    }
} 
3.4 keepalived开机启动
echo "/etc/init.d/keepalived start" >> /etc/rc.local

在这里插入图片描述

4.启动keepalived
/etc/init.d/keepalived start
  • 查看主服务器IP
    ngixn负载均衡高可用-主备切换keepalived实现_第2张图片

  • 查看备服务器IP
    ngixn负载均衡高可用-主备切换keepalived实现_第3张图片

  • 测试:关闭主服务器nginx
    ngixn负载均衡高可用-主备切换keepalived实现_第4张图片

你可能感兴趣的:(Nginx)