在 CentOS 上监控 Node.js 应用,通常从 系统级 + 应用级 + 日志 + 性能分析 几个层面来做。下面按常见场景给你一套实用方案。
top
htop # 推荐(需安装)
free -h
df -h
查看 Node.js 进程:
ps -ef | grep node
查看某个 Node 进程资源占用:
top -p $(pgrep -f "node")
vmstat 1
iostat -x 1
sar -u 1 5
process 模块(代码级)setInterval(() => {
const mem = process.memoryUsage();
console.log({
rss: mem.rss / 1024 / 1024 + 'MB',
heapUsed: mem.heapUsed / 1024 / 1024 + 'MB',
heapTotal: mem.heapTotal / 1024 / 1024 + 'MB'
});
}, 5000);
prom-client(推荐,生产级)适合配合 Prometheus + Grafana
npm install prom-client
示例:
const client = require('prom-client');
const collectDefaultMetrics = client.collectDefaultMetrics;
collectDefaultMetrics({ timeout: 5000 });
app.get('/metrics', async (req, res) => {
res.set('Content-Type', client.register.contentType);
res.end(await client.register.metrics());
});
npm install -g pm2
pm2 start app.js
pm2 monit
pm2 list
查看 CPU / 内存:
pm2 monit
生成监控面板:
pm2 dashboard
node-inspect / ndb用于性能分析、内存泄漏排查
node --inspect app.js
浏览器打开:
chrome://inspect
clinic(性能分析神器)npm install -g clinic
clinic doctor -- node app.js
clinic flame -- node app.js
winstonpino(高性能)npm install pino
配合:
pm2 logs
journalctl -u your-node-service
| 场景 | 推荐 |
|---|---|
| 进程管理 | PM2 |
| 性能分析 | clinic / node --inspect |
| 指标监控 | prom-client + Prometheus + Grafana |
| 日志 | pino + PM2 logs |
| 系统资源 | top / htop / sar |
Node.js
↓
PM2
↓
prom-client (/metrics)
↓
Prometheus
↓
Grafana
如果你愿意,可以告诉我:
我可以给你一套 定制监控方案 + Grafana 面板配置。