在 CentOS 系统中排查 Node.js 故障可以通过以下几个步骤进行:
journalctl
命令查看系统日志,特别是与 Node.js 服务相关的日志。journalctl -u your-nodejs-service-name -t
cat logs/app.log
less logs/app.log
tail -f logs/app.log
ps
、top
和 systemctl
等工具检查 Node.js 进程的状态和资源使用情况。ps aux | grep node
top -p <pid>
systemctl status your-nodejs-service
ping
、traceroute
和 netstat
等工具检查网络连接和端口状态。ping google.com
netstat -an | grep <port>
top
、free
和 df
等工具检查 CPU、内存和磁盘空间使用情况。free -m
df -h
top
debugger;
语句,然后使用 node inspect your_script.js
命令运行脚本。process
模块获取进程信息,如 CPU 使用率和内存使用情况。const os = require('os');
const cpuUsage = process.cpuUsage();
console.log(`CPU 使用率: ${cpuUsage.user} ${cpuUsage.system}%`);
const totalMemory = os.totalmem();
const freeMemory = os.freemem();
console.log(`内存使用情况: ${(totalMemory - freeMemory) / totalMemory * 100}%`);
express-status-monitor
提供实时的服务器性能指标和健康检查。const express = require('express');
const statusMonitor = require('express-status-monitor');
const app = express();
app.use(statusMonitor());
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
heapdump
模块导出内存快照,然后在 Chrome DevTools 中进行分析。const heapdump = require('heapdump');
heapdump.writeSnapshot('/tmp/heapdump.heapsnapshot');
通过以上步骤,可以系统地排查 CentOS 系统中 Node.js 应用程序的故障,从日志分析、进程状态检查到性能监控和内存泄漏排查,确保应用程序的稳定运行。