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目錄下,給予權限即可。)
出現如下頁面表示腳本運行正常:
宕掉一臺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 ]
用Tengine(Nginx的分支)模塊nginx_upstream_check_module,提供主動式後端服務器節點健康檢查。可參考http://blog.51cto.com/13707680/2107391
Nginx負載節點狀態監測腳本