一、開啟NginxStatus
NginxStatus是Nginx自帶的狀態模塊,提供了實時的HTTP請求統計和服務器狀態監控。NginxStatus默認是關閉的,需要在nginx.conf配置文件中開啟。
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
allow localhost;
deny all;
}
以上配置代碼可以在http段或server段中配置,建議在server段中配置。
其中,location /nginx_status配置了NginxStatus的訪問地址,stub_status on開啟了狀態模塊,access_log off關閉了訪問日誌記錄,allow 127.0.0.1; allow localhost;允許本地IP訪問,deny all;拒絕其他IP訪問。
二、查看NginxStatus信息
配置好NginxStatus後,可以通過http://IP地址/nginx_status來訪問狀態信息。
NginxStatus提供了如下信息:
- Active connections:當前活躍的連接數。
- server accepts handled requests:nginx處理連接成功的數量數目,處理請求的數量、和總的請求數。
- Reading:nginx正在讀取請求頭。
- Writing:nginx正在將響應寫回客戶端。
- Waiting:nginx正在等待另一個請求。
示例:
Active connections: 1 server accepts handled requests 1 1 2 Reading: 0 Writing: 1 Waiting: 0
三、使用NginxStatus統計及監控
1. 統計網站流量和請求情況
NginxStatus提供了requests和bytes兩個信息,可以通過腳本定時獲取並統計,實現對網站流量和請求情況的監控。
以下是獲取requests和bytes信息的python腳本:
import urllib.request
import re
import time
url = 'http://localhost/nginx_status'
while True:
response = urllib.request.urlopen(url)
html = response.read().decode('utf-8')
status = re.findall(r'Requests\s+(\d+)', html)[0] # requests信息
traffic = re.findall(r'(\d+)\skB', html)[0] # bytes信息
print('Requests:{} | Traffic:{}kB'.format(status, traffic))
time.sleep(5) # 每5秒更新一次
2. 監控服務器負載情況
NginxStatus提供了Active connections、Reading、Writing和Waiting四個信息,可以用來監控服務器的負載情況。
以下是根據Active connections信息,通過腳本實現自動熱備的例子:
#!/bin/bash
# 配置備用服務器地址
backup_server=192.168.1.2
while true
do
# 獲取Active連接數
active_conn=$(curl -s http://localhost/nginx_status | grep 'Active' | awk '{print $3}')
# 當Active連接數大於100時,自動將流量切到備用服務器
if [ $active_conn -gt 100 ]
then
sed -i 's/server\ 192\.168\.1\.1/server\ 192\.168\.1\.2/g' /etc/nginx/nginx.conf
nginx -s reload
fi
# 當Active連接數小於50時,自動將流量切回主服務器
if [ $active_conn -lt 50 ]
then
sed -i 's/server\ 192\.168\.1\.2/server\ 192\.168\.1\.1/g' /etc/nginx/nginx.conf
nginx -s reload
fi
sleep 10 # 每10秒檢查一次
done
3. 檢測Nginx服務狀態
NginxStatus提供了server accepts handled requests信息,可以用來監控服務器的服務狀態。
以下是檢測Nginx服務狀態的python腳本:
import urllib.request
import re
import time
import subprocess
url = 'http://localhost/nginx_status'
while True:
response = urllib.request.urlopen(url)
html = response.read().decode('utf-8')
handled = re.findall(r'Handled\s+(\d+)', html)[0]
status = subprocess.Popen('service nginx status', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = status.communicate()[0].decode('utf-8')
if 'active (running)' not in output or int(handled) == 0:
subprocess.Popen('service nginx restart', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
time.sleep(30) # 等待30秒後再次檢測
time.sleep(5) # 每5秒檢查一次
四、總結
NginxStatus是一個實用的狀態模塊,可以用來監控服務器的狀態、統計網站流量和請求情況、自動熱備和檢測Nginx服務狀態。
開啟NginxStatus只需要簡單的配置,即可實現以上功能。希望本文能對大家有所幫助。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/304127.html
微信掃一掃
支付寶掃一掃