插件窝 干货文章 Nginx监控实时状态配置,实时查看网站运行

Nginx监控实时状态配置,实时查看网站运行

Nginx 状态 监控 配置 649    来源:    2025-04-16

Nginx实时状态监控配置指南

1. 启用Nginx状态模块

Nginx自带一个状态模块ngx_http_stub_status_module,可以显示基本的实时状态信息。

配置步骤:

  1. 首先确认你的Nginx编译时包含了该模块:

    nginx -V 2>&1 | grep -o with-http_stub_status_module
    
  2. 在Nginx配置文件中添加状态监控位置(通常在/etc/nginx/nginx.conf或站点配置文件中):

    server {
       listen 80;
       server_name yourdomain.com;
    
       location /nginx_status {
           stub_status on;
           access_log off;
           allow 127.0.0.1;    # 只允许本地访问
           allow 192.168.1.0/24; # 或者允许你的内网IP段
           deny all;          # 拒绝其他所有IP
       }
    }
    
  3. 重新加载Nginx配置:

    nginx -s reload
    

2. 访问状态页面

访问http://yourdomain.com/nginx_status,你会看到类似如下的输出:

Active connections: 291 
server accepts handled requests
 16630948 16630948 31070465 
Reading: 6 Writing: 179 Waiting: 106 

3. 状态信息解释

  • Active connections: 当前活跃连接数
  • server accepts: 已接受的客户端连接总数
  • handled: 已处理的连接总数
  • requests: 客户端请求总数
  • Reading: Nginx正在读取请求头的连接数
  • Writing: Nginx正在向客户端写入响应的连接数
  • Waiting: 保持活跃的连接数(等于Active - (Reading + Writing))

4. 高级监控方案

4.1 使用Prometheus + Grafana

  1. 安装Nginx Prometheus exporter:

    docker run -d -p 9113:9113 nginx/nginx-prometheus-exporter -nginx.scrape-uri=http://<nginx-ip>/nginx_status
    
  2. 配置Prometheus抓取exporter数据

  3. 在Grafana中导入Nginx仪表板(如ID 12708)

4.2 使用GoAccess实时分析

goaccess /var/log/nginx/access.log -o /var/www/html/report.html --real-time-html --log-format=COMBINED

4.3 使用Netdata

Netdata提供开箱即用的Nginx监控:

# 安装Netdata
bash <(curl -Ss https://my-netdata.io/kickstart.sh)

5. 安全注意事项

  1. 限制状态页面的访问IP
  2. 考虑添加HTTP基本认证
  3. 对于生产环境,建议通过VPN或SSH隧道访问

6. 扩展监控指标

如果需要更多指标,可以考虑编译Nginx时加入ngx_http_status_module或使用商业版的Nginx Plus,它提供了更丰富的监控指标和API。

通过以上配置,你可以实时监控Nginx的运行状态,及时发现性能瓶颈和异常情况。