nginx status配置及参数配置小结

来自:网络
时间:2024-06-08
阅读:

今天简单介绍下如何监控Nginx的状态。

其实要监控Nginx的状态非常简单,它内建了一个状态页,只需修改Nginx配置启用Status即可,对于想了解nginx的状态以及监控nginx非常有帮助。

1. 启用nginx status配置

大概Nginx配置文件,在默认主机里面加上location或者你希望能访问到的主机里面加上如下配置。

   #NGINX 状态监控 ,需要确认是否安装监控模块 http_stub_status_module,如果已经安装该模块,可以为 NGINX 启用状态监控:
   server {
	    listen 91;
	    
	    location /status {            
	      stub_status on;            
	      access_log off;            
	    }
    }    

2. 重启nginx

操作命令比较简单,请依照你的环境重启你的nginx即可。

3. 打开status页面

在浏览器中输入nginx的地址:http://192.168.2.109:91/status,即可查看nginx的状态信息

nginx status配置及参数配置小结

4. nginx status详解

  • Active connections – 活跃的连接数量
  • server accepts handled requests — 总共处理了93个连接 , 成功创建93次握手, 总共处理了152个请求。
  • reading — 读取客户端的连接数。
  • writing — 响应数据到客户端的数量。
  • waiting — 开启 keep-alive 的情况下,这个值等于 active – (reading+writing), 意思就是 Nginx 已经处理完正在等候下一次请求指令的驻留连接。

5、使用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 connectionsReadingWritingWaiting四个信息,可以用来监控服务器的负载情况。

以下是根据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秒检查一次

6、总结

返回顶部
顶部