监控与状态页
约 532 字大约 2 分钟
布欧-Lewyon
2026-05-15
首页 › Nginx › 运维与安全(在新窗口打开) › 监控与状态页
stub_status 模块
编译安装时需要包含 --with-http_stub_status_module,主流发行版默认包含。
server {
listen 80;
server_name status.example.com;
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1; # 仅允许本机访问
allow 10.0.0.0/8; # 内网访问
deny all; # 拒绝其他
}
}# 访问状态页
curl http://127.0.0.1/nginx_status
# Active connections: 5
# server accepts handled requests
# 12345 12345 67890
# Reading: 0 Writing: 1 Waiting: 4| 指标 | 说明 |
|---|---|
Active connections | 当前活跃连接数 |
accepts | 已接受的连接总数 |
handled | 已成功处理的连接总数 |
requests | 总请求数 |
Reading | 正在读取请求头的连接数 |
Writing | 正在写响应的连接数 |
Waiting | 空闲 keepalive 连接数 |
监控告警指标
# 计算关键指标
# 连接成功率 = handled / accepts(应接近 1)
# QPS 可以从 requests 差值计算
# Waiting 高说明 keepalive 连接多Prometheus + nginx_exporter
将 stub_status 数据暴露为 Prometheus 格式:
# 安装 nginx_exporter
wget https://github.com/nginxinc/nginx-prometheus-exporter/releases/download/v1.3.0/nginx-prometheus-exporter_1.3.0_linux_amd64.tar.gz
# 启动(指向 stub_status 地址)
./nginx-prometheus-exporter --nginx.scrape-uri=http://127.0.0.1/nginx_status
# Prometheus 配置
# - job_name: 'nginx'
# static_configs:
# - targets: ['localhost:9113']日志监控
实时查看
# 实时查看访问日志
tail -f /var/log/nginx/access.log
# 实时查看错误日志
tail -f /var/log/nginx/error.log
# 统计 HTTP 状态码
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn
# 统计请求最多的 IP
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -10
# 统计最慢的请求
awk '{print $NF, $0}' /var/log/nginx/access.log | sort -rn | head -10GoAccess 实时分析
# 安装
sudo apt install goaccess
# 实时分析
goaccess /var/log/nginx/access.log -o /var/www/html/report.html --log-format=COMBINEDNginx 内置变量监控
# 在响应头中返回调试信息(仅开发环境)
server {
listen 80;
location / {
add_header X-Nginx-Host $hostname;
add_header X-Upstream-Addr $upstream_addr;
add_header X-Upstream-Status $upstream_status;
add_header X-Upstream-Response-Time $upstream_response_time;
add_header X-Request-Time $request_time;
proxy_pass http://backend;
}
}小结
stub_status提供基础连接统计:活跃连接、请求总数、读写等待。- stub_status 页面应限制访问 IP(
allow/deny)。 nginx-prometheus-exporter+ Prometheus + Grafana 是生产级监控方案。- 日志分析命令(
awk/tail)和 GoAccess 可快速排查问题。 - 在响应头返回
$upstream_addr和$upstream_response_time方便调试。
