通过keepalived搭建ningx集群,实现nginx高可用。
流程
keepalived作用
Keepalived是一个基于VRRP协议来实现的服务高可用方案,可以利用其来避免IP单点故障,
对外虚拟一个vip ip节点。vrrp协议可以百度到
nginx+keepalived搭建
- 准备工作
- linux虚拟机2台。master ip=192.168.112.97 slave ip=192.168.112.98 虚拟VIP ip=192.168.112.50
- 在两台服务器上面都安装nginx和keepalived
- 在slave节点绑定 虚拟静态ip ifconfig eth0:1 192.168.112.50 netmask 255.255.255.0 up
keepalived安装过程
- 安装命令:apt-get install keepalived
- 启动和停止命令:service keepalived start、 service keepalived stop
- keepalived 默认读取/etc/keepalived/keepalived.conf 下面的配置文件,我们可以cat /var/log/syslog 查看keepalived的启动日志
/etc/keepalived/keepalived.conf 配置文件:
vi keepalived.conf global_defs { notification_email { zhouxiao@example.com itsection@example.com } notification_email_from itsection@example.com smtp_server mail.example.com smtp_connect_timeout 30 router_id LVS_DEVEL } vrrp_script chk_nginx { script "/etc/keepalived/check_nginx.sh" interval 2 weight -5 fall 3 rise 2 } vrrp_instance VI_1 { #节点状态 state MASTER # 网卡 interface eth0 # 当前ip mcast_src_ip 192.168.112.97 # 虚拟节点id 必须一样 virtual_router_id 51 #优先级 priority 101 advert_int 2 authentication { auth_type PASS auth_pass 1111 } #虚拟节点ip virtual_ipaddress { 192.168.112.50 } # 监控脚本 track_script { chk_nginx } }
/etc/keepalived/check_nginx.sh
vi check_nginx.sh #!/bin/bash #这种方式会把ps的信息打印出来,显示的不准确 #num=`ps -ef|grep nginx|wc -l` num=$(ps -C nginx --no-heading|wc -l) if [ $num -le 0 ] then #启动ngingx /usr/local/nginx/sbin/nginx #休眠2秒 sleep 2 num=$(ps -C nginx --no-heading|wc -l) if [ $num -le 0 ];then service keepalived stop cd /etc/keepalived/ echo "no nginx start">>gao.txt fi fi
- 相关解释:
check_nginx.sh是用来检测 nginx是否正常运行的脚本,keepalived可以动态根据检测执行这个脚本 决定那台服务器的keepalived是vip节点。
master 的配置文件和 slave的keepalived.conf 文件区别在于 state MASTER -> state BACKUP,priority 101 -> priority 100,mcast_src_ip 192.168.112.97 -> mcast_src_ip 192.168.112.98即可
- 相关解释:
测试
启动nginx和keepalived,访问VIP ip 192.168.112.50 显示的是master的nginx内容。
stop master的keepalive的 再访问vip节点 显示的是slave的内容