Keepalived+Nginx搭建主从高可用并带nginx检测
Keepalived+Nginx搭建主从高可用并带nginx检测
应用环境:部分时候,WEB访问量一般,或者测试使用,利用Keepalived给Nginx做高可用即可满足要求。
测试环境:
搭建步骤:
1. 安装软件
在Nginx-A和Nginx-B上:
~]# yum install keepalived nmap -y //nmap提供nmap命令,后面的Nginx检测脚本里会用到
2. 配置Nginx-A
[root@nginx-a ~]# vim /etc/keepalived/keepalived.conf //配置好的内容如下
! Configuration File for keepalived global_defs { router_id Nginx-A } vrrp_script chk_nginx { ## chk_nginx名字可以自定义,与下面的track_script段中的名字要一致 script "/opt/chk_nginx.sh" ## chk_nginx.sh的内容下面给出 interval 2 weight 2 } 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 { 138.138.82.222 } track_script { chk_nginx } }
保存,退出;
[root@nginx-a ~]# vim /opt/chk_nginx.sh //新建Nginx检测脚本,内容如下
[root@nginx-a ~]# chmod +x /opt/chk_nginx.sh //给脚本添加执行权限
#!/bin/sh # check nginx server status NGINX=/usr/sbin/nginx PORT=80 nmap localhost -p $PORT | grep "$PORT/tcp open" #echo $? if [ $? -ne 0 ];then $NGINX -s stop $NGINX sleep 3 nmap localhost -p $PORT | grep "$PORT/tcp open" [ $? -ne 0 ] && /etc/init.d/keepalived stop fi
说明:该脚本的意义就是先检测Nginx是否已经开启默认的80端口:
如果存在80端口,一切正常;
如果不存在80端口,就执行if段中的语句:先关一下Nginx,在启动Nginx,等待3秒,再次检测80端口,如果还不存在,则杀死keepalived,
这样一来,访问就走另外一台安装keepalived的上WEB端。(如果两台都出问题,那只能呵呵了)
[root@nginx-a ~]# service keepalived start //启动keepalived
[root@nginx-a ~]# chkconfig keepalived on //加入开机启动
3. 配置Nginx-B
[root@nginx-b ~]# vim /etc/keepalived/keepalived.conf //配置好的内容如下
! Configuration File for keepalived global_defs { router_id Nginx-B } vrrp_script chk_nginx { ## 同Nginx-A script "/opt/chk_nginx.sh" interval 2 weight 2 } vrrp_instance VI_1 { state BACKUP interface eth0 virtual_router_id 51 priority 80 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 138.138.82.222 } track_script { chk_nginx } }
保存,退出;
[root@nginx-b ~]# vim /opt/chk_nginx.sh // 脚本内容同Nginx-A ,见上面
[root@nginx-b ~]# chmod +x /opt/chk_nginx.sh //给脚本添加执行权限
[root@nginx-b ~]# service keepalived start //启动keepalived
[root@nginx-b ~]# chkconfig keepalived on //加入开机启动
4. 测试
找一台客户端执行命令:
~]# while true; do curl 138.138.82.222 ;sleep 1;done
测试成功,达到了两台nginx高可用,并能够健康检测nginx(这里实际检测80端口,实际意义可作一样)。
结束.
附上另一种检测脚本:
#!/bin/bash if [ "$(ps -ef | grep "nginx: master process"| grep -v grep )" == "" ] then /usr/local/nginx/sbin/nginx sleep 5 if [ "$(ps -ef | grep "nginx: master process"| grep -v grep )" == "" ] then killall keepalived fi fi