在CentOS系统上解决Node.js内存溢出问题,可以采取以下几种方法:
增加Node.js的内存限制:
NODE_OPTIONS 来增加内存限制。例如,将Node.js的最大内存限制设置为4GB的命令如下:export NODE_OPTIONS="--max_old_space_size=4096"
你可以根据需要调整这个值。使用64位版本的Node.js:
优化代码:
npm install heapdump
const heapdump = require('heapdump');
// 在需要时生成堆快照
heapdump.writeSnapshot('/path/to/snapshot.heapsnapshot');
npm install memwatch-next
const memwatch = require('memwatch-next');
memwatch.on('leak', (info) => {
console.error('Memory leak detected:', info);
});
使用集群模式:
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
// Workers can share any TCP connection
// In this case it is an HTTP server
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world
');
}).listen(8000);
console.log(Worker ${process.pid} started);
}
```
使用PM2管理Node.js进程:
npm install pm2 -g
pm2 start app.js --max-memory-restart 4G
这个命令会启动你的Node.js应用,并在内存使用超过4GB时自动重启进程。检查系统资源:
free -h
df -h
如果物理内存不足,可以考虑增加交换空间:sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
然后编辑 /etc/fstab 文件,添加以下行以确保交换空间在重启后仍然有效:/swapfile swap swap defaults 0 0
通过以上方法,你应该能够在CentOS上有效地解决Node.js内存溢出问题。