查看 Nginx 的运行状态是监控和调优服务的关键步骤。以下是 多种方法 和 详细操作指南,涵盖基础状态、实时监控、日志分析及第三方工具集成:
1. 使用 Nginx 内置状态模块 (ngx_http_stub_status_module
)
(1) 启用状态页
在 Nginx 配置中添加:
server {
listen 80;
server_name localhost;
location /nginx_status {
stub_status on; # 启用状态页
access_log off; # 关闭日志记录
allow 127.0.0.1; # 仅允许本地访问
deny all; # 禁止其他IP
}
}
(2) 访问状态页
curl http://127.0.0.1/nginx_status
输出示例:
Active connections: 291
server accepts handled requests
16630948 16630948 31070465
Reading: 6 Writing: 179 Waiting: 106
字段解释:
- Active connections:当前活跃连接数(含
Reading
+Writing
+Waiting
)。 - accepts:总接受的客户端连接数。
- handled:成功处理的连接数(通常等于
accepts
,除非达到worker_connections
限制)。 - requests:总处理的客户端请求数。
- Reading:正在读取请求头的连接数。
- Writing:正在发送响应的连接数。
- Waiting:空闲的持久连接数(开启 keepalive 时出现)。
2. 查看进程状态
(1) 检查 Nginx 进程
ps aux | grep nginx
输出示例:
root 1234 0.0 0.1 12345 6789 ? Ss May10 0:00 nginx: master process
www-data 5678 0.0 0.2 23456 9876 ? S May10 0:12 nginx: worker process
- Master 进程:负责管理 Worker 进程。
- Worker 进程:实际处理请求(数量由
worker_processes
决定)。
(2) 实时监控资源占用
top -p $(pgrep -d ',' nginx) # 监控所有Nginx进程的CPU/内存
3. 分析日志
(1) 实时查看访问日志
tail -f /var/log/nginx/access.log
关键字段:
127.0.0.1 - - [01/Jan/2023:12:00:00 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.68.0"
$remote_addr
:客户端 IP。$status
:HTTP 状态码(如 200、404)。$request_time
:请求处理时间(秒)。
(2) 统计高频访问 IP
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10
(3) 监控错误日志
tail -f /var/log/nginx/error.log
常见错误:
connect() failed (111: Connection refused)
:后端服务不可达。upstream timed out
:代理超时。
4. 使用第三方工具
(1) Nginx Amplify(商业监控)
- 提供可视化面板、告警和性能分析。
- 官网:https://amplify.nginx.com
(2) Prometheus + Grafana
- 安装 Nginx Prometheus Exporter:
docker run -d -p 9113:9113 nginx/nginx-prometheus-exporter -nginx.scrape-uri=http://nginx_status
- Grafana 仪表盘:导入 Nginx 模板。
(3) GoAccess(实时日志分析)
goaccess /var/log/nginx/access.log --log-format=COMBINED --real-time-html
- 生成交互式 HTML 报告。
5. 系统级监控
(1) 查看 TCP 连接状态
ss -ant | grep ':80' | awk '{print $1}' | sort | uniq -c
- 统计 HTTP 端口的连接状态(如
ESTAB
、TIME-WAIT
)。
(2) 检查文件描述符使用
cat /proc/$(cat /run/nginx.pid)/limits | grep 'Max open files'
6. 高级状态查看(Nginx Plus 专属)
商业版 Nginx Plus 提供更丰富的 API:
location /api {
api write=on; # 启用控制API
}
API 端点示例:
http://localhost/api/version
:查看版本。http://localhost/api/connections
:连接详情。
常见问题排查
- 状态页返回 404
- 确认
stub_status
已启用且路径匹配。
- 确认
- 高
Waiting
连接数- 检查
keepalive_timeout
是否过长。
- 检查
- Worker 进程高 CPU
- 使用
strace
跟踪耗时操作:strace -p $(pgrep -n nginx) -c
- 使用
总结
方法 | 适用场景 | 命令/配置 |
---|---|---|
内置状态页 | 快速查看基础指标 | stub_status on; + curl |
进程监控 | 检查 Worker/Master 状态 | ps aux | grep nginx |
日志分析 | 定位异常请求或错误 | tail -f error.log + awk |
Prometheus + Grafana | 长期监控和可视化 | 需部署 Exporter 和 Grafana |
系统工具 | 分析 TCP 连接和资源限制 | ss 、top 、cat /proc/$(pid)/limits |
通过组合这些方法,可以全面掌握 Nginx 的运行状态,及时发现性能瓶颈或异常问题。
- - - - - - - 剩余部分未读 - - - - - - -
扫描关注微信公众号获取验证码,阅读全文
你也可以查看我的公众号文章,阅读全文
你还可以登录,阅读全文
原文出处:
内容由AI生成仅供参考,请勿使用于商业用途。如若转载请注明原文及出处。
出处地址:http://www.07sucai.com/tech/974.html
版权声明:本文来源地址若非本站均为转载,若侵害到您的权利,请及时联系我们,我们会在第一时间进行处理。