Nginx负载节点状态监测脚本

 1)脚本需求:开通一个通过web界面展示监控Nginx负载节点的状态。当节点宕机时,以红色展示,当节点正常时以绿色展示。


 2)脚本解答:

[root@localhost scripts]# cat monitor.sh 

#!/bin/bash

#this scripts is created by ywxi at 2018-05-11

RIPS=(                    #定义监测节点池

  192.168.1.22

  192.168.1.33

  192.168.1.30

 )


file_location=/usr/share/nginx/html/test.html                  #默认yum安装nginx的站点目录路径

[ -e "$file_location" ]||mkdir -p `dirname $file_location`    #判断目录是否存在


function web_result {                                                         #定义curl请求状态值

  rs=`curl -I -s $1|awk 'NR==1{print $2}'`

  return $rs

}


function new_row {                                                           #定义web框架

  cat >> $file_location <<eof

  <tr>

  <td bgcolor="$4">$1</td>

  <td bgcolor="$4">$2</td>

  <td bgcolor="$4">$3</td>

  </tr>

eof

}


function auto_html {                                                        #定义节点状态返回值显示的web界面

  web_result $2

  rs=$?

  if [ $rs -eq 200 ]

    then

      new_row $1 $2 up green

  else

      new_row $1 $2 down red

  fi

}


function main(){                                                                 #定义web框架

  while true

  do

  cat >> $file_location <<eof

  <h4>ywxi Nginx Service Status Of RS :</h4>

  <meta http-equiv="refresh" content="1">

  <table border="1">

  <tr>

  <th>NO:</th>

  <th>IP:</th>

  <th>Status:</th>

  </tr>

eof


  for ((i=0; i<${#RIPS[*]}; i++));do                                   #对节点做循环判断,并提供对应的html代码

    auto_html $i ${RIPS[$i]}

  done


  cat >> $file_location<<eof

  </table>

eof


  sleep 2

  > $file_location                                                           #清空文件内容

  done

}

main $*


3)脚本执行:

[root@localhost scripts]# sh monitor.sh 

浏览器访问http://192.168.1.22/test.html(前提是部署好了http服务,test.html放在对应的html目录下,给予权限即可。)

出现如下页面表示脚本运行正常:

image.png


  宕掉一台192.168.1.33节点,看下情况

[root@localhost scripts]# ifconfig  | sed -n 2p | awk '{print $2}'                    

addr:192.168.1.33

[root@localhost scripts]# /etc/init.d/nginx stop

Stopping nginx:    [  OK  ]

image.png


   用Tengine(Nginx的分支)模块nginx_upstream_check_module提供主动式后端服务器节点健康检查。可参考http://blog.51cto.com/13707680/2107391 

猜你喜欢

转载自blog.51cto.com/13707680/2115637