Debian上Nginx性能监控的常用方法与工具
Nginx自带的stub_status
模块可提供核心性能指标,适合快速查看服务器状态。
配置步骤:
/etc/nginx/sites-available/default
)的server
块中添加:location /stub_status {
stub_status on;
access_log off;
allow 127.0.0.1; # 仅允许本地访问
deny all;
}
sudo nginx -t
,确认无误后重载Nginx:sudo systemctl reload nginx
。http://localhost/stub_status
,输出示例如下:Active connections: 291
server accepts handled requests
16630948 16630948 31070465
Reading: 6 Writing: 179 Waiting: 106
指标说明:
Active connections
:当前活跃连接数(含Reading
/Writing
/Waiting
);accepts/handled/requests
:总接受连接数、总处理连接数、总请求数(用于计算请求吞吐量);Reading/Writing/Waiting
:正在读取请求头、写入响应、等待的连接数(反映并发处理能力)。Nginx的访问日志(默认路径:/var/log/nginx/access.log
)和错误日志(默认路径:/var/log/nginx/error.log
)是性能排查的重要依据。
1. 访问日志优化与分析
nginx.conf
的http
块中定义包含关键指标的格式(如响应时间、上游响应时间):log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time';
access_log /var/log/nginx/access.log main;
其中,$request_time
(请求处理时间)、$upstream_response_time
(上游服务响应时间)是核心性能指标。grep -c ' 200 ' /var/log/nginx/access.log
、grep -c ' 500 ' /var/log/nginx/access.log
;awk '{sum+=$11} END {print sum/NR}' /var/log/nginx/access.log
($11
对应$request_time
);awk '$11 > 1 {print $0}' /var/log/nginx/access.log
。nginx.conf
的http
块中设置error_log /var/log/nginx/error.log warn;
(生产环境推荐warn
或error
,避免debug
产生大量日志);tail -f /var/log/nginx/error.log
实时查看错误(如upstream timed out
表示上游服务超时,no live upstreams
表示上游服务器不可用)。此方案适合需要自定义指标、长期存储、可视化的场景,是当前最流行的开源监控组合。
1. 安装Nginx Exporter
Nginx Exporter是Prometheus与Nginx之间的桥梁,负责采集Nginx指标并转换为Prometheus可识别的格式。
wget https://github.com/nginxinc/nginx-prometheus-exporter/releases/download/v0.11.0/nginx-prometheus-exporter_0.11.0_linux_amd64.tar.gz
tar -zxvf nginx-prometheus-exporter_0.11.0_linux_amd64.tar.gz
cd nginx-prometheus-exporter
./nginx-prometheus-exporter -nginx.scrape-uri=http://localhost/stub_status
(若Nginx运行在Docker容器中,需将localhost
替换为容器IP或端口映射地址)。/etc/prometheus/prometheus.yml
),添加Nginx抓取任务:scrape_configs:
- job_name: 'nginx'
scrape_interval: 15s # 采集间隔(秒)
static_configs:
- targets: ['localhost:9113'] # Exporter默认监听端口
重启Prometheus使配置生效:sudo systemctl restart prometheus
。
3. 使用Grafana可视化
sudo apt install grafana
,启动服务并设置开机自启;http://localhost:3000
,账号admin
),进入“Configuration”→“Data Sources”,选择“Prometheus”并填写URL(http://localhost:9090
);12708
(Nginx官方仪表板),即可查看请求量、响应时间、错误率、连接数等可视化图表。Nginx Amplify是Nginx官方推出的SaaS监控工具,适合新手快速上手,无需复杂配置。
配置步骤:
curl -sS -L https://github.com/nginxinc/nginx-amplify-agent/raw/master/packages/install.sh | sh -s -- -a YOUR_API_KEY
通过Debian系统自带的工具,可监控Nginx对CPU、内存、磁盘I/O等系统资源的使用情况。
常用命令:
top
/htop
:实时查看Nginx进程的CPU、内存占用(按P
键按CPU排序,M
键按内存排序);iostat -c -m 1
:查看磁盘I/O使用率(需安装sysstat
包:sudo apt install sysstat
);ss -lntp | grep nginx
:查看Nginx的网络连接状态(如监听端口、连接数)。