在Linux中监测Web应用性能需要结合系统资源监控、网络分析、应用层工具和日志分析等多种手段。以下是一套完整的解决方案:
top/htop
top -d 1 # 实时监控CPU、内存使用
htop # 交互式增强版top(需安装)
vmstat
vmstat 1 # 监控系统进程、内存、I/O等
dstat
dstat -cmny --disk-util --tcp 1 # 综合监控工具
iftop
iftop -i eth0 -n # 实时网络流量监控
nload
nload eth0 # 可视化网络带宽监控
TCP连接分析
ss -s # 查看TCP连接统计
netstat -anp | grep ESTABLISHED | wc -l # 统计活跃连接数
Nginx监控
# 启用stub_status模块后访问:
curl http://localhost/nginx_status
Apache监控
apachectl status # 需要启用mod_status
New Relic/DataDog
开源方案
# PHP应用
xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
# Java应用
jstack <pid> > thread_dump.txt # 线程转储分析
实时日志监控
tail -f /var/log/nginx/access.log | grep -v '200' # 监控非200请求
日志分析工具
# 使用GoAccess生成报告
goaccess /var/log/nginx/access.log --log-format=COMBINED -a -o report.html
Prometheus + Grafana
# 示例Prometheus配置
scrape_configs:
- job_name: 'node'
static_configs:
- targets: ['localhost:9100'] # node_exporter端口
ELK Stack
// 使用Navigation Timing API
console.log(
`DNS查询: ${performance.timing.domainLookupEnd - performance.timing.domainLookupStart}ms`
);
MySQL
SHOW PROCESSLIST;
SHOW STATUS LIKE 'Threads_connected';
PostgreSQL
SELECT * FROM pg_stat_activity;
#!/bin/bash
# 监控HTTP响应时间
while true; do
curl -o /dev/null -s -w \
"DNS: %{time_namelookup}s | Connect: %{time_connect}s | Total: %{time_total}s\n" \
https://yourdomain.com
sleep 5
done
建议组合使用多种工具,例如: - 基础设施监控:Prometheus + Grafana - 日志分析:ELK Stack - 实时性能:htop + iftop - 深度分析:APM工具
通过以上工具的组合使用,可以构建从基础设施到应用代码的全方位性能监控体系。