lvs可以使用ipvsam -Ln 查看RS节点的情况,当RS宕机后剔除,当RS恢复后自动加入,nginx上面无法查看,需要安装插件或自己写脚本实现;
反向代理的配置如下:(server 去掉前面的空格,为了方便后面脚本使用sed做文本替换;)
[root@localhost vhosts]# cat upstream01.conf
upstream backend {
server 192.168.20.10:80 weight=5;
server 192.168.20.11:80 weight=5;
}
server {
listen 80;
server_name blog.yong.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
}
}检查nginx后端real server脚本,实现发现宕机剔除,恢复服务自动加入功能;
脚本解释:
使用守护进程的方式,每隔5秒执行一次脚本,判断后端RS服务是否是正常,发现有宕机的RS,则sed修改配置文件#号注释掉对应的RS,ip地址,并重启nginx服务;当发现服务恢复的时候,去掉#号,并重启nginx服务,加入到RS中;
[root@localhost vhosts]# cat check_nginx_RS.sh
#!/bin/bash
#written by mofansheng@2015-11-26
ip_array=($(grep "192.168.20" upstream01.conf |awk ‘{print $2}‘|awk -F":" ‘{print $1}‘))
while true
do
for((i=0;i<${#ip_array[*]};i++))
do
egrep "^#.*${ip_array[$i]}.*" upstream01.conf &>/dev/null
[ $? -eq 0 ] && continue
status=`curl -s -w "%{http_code}" -o /dev/null ${ip_array[$i]}`
if [ ${status} -ne 200 ]
then
sed -i "s/server ${ip_array[$i]}/#server ${ip_array[$i]}/g" upstream01.conf
/etc/init.d/nginx reload
fi
done
sleep 5
for((i=0;i<${#ip_array[*]};i++))
do
a=`curl -s -w "%{http_code}" -o /dev/null ${ip_array[$i]}`
if [ ${a} -eq 200 ];then
egrep "^#.*${ip_array[$i]}.*" upstream01.conf &>/dev/null
if [ $? -eq 0 ];then
sed -i -r "s/#(.*${ip_array[$i]}.*)/\1/g" upstream01.conf
/etc/init.d/nginx reload
fi
fi
done
done脚本执行结果如下图:
本文出自 “模范生的学习博客” 博客,请务必保留此出处http://mofansheng.blog.51cto.com/8792265/1717464
原文地址:http://mofansheng.blog.51cto.com/8792265/1717464