当我使用PM2运行多个进程(即群集模式)并且其中一个进程遇到未被捕获的错误时,PM2不会重新启动该进程。
为什么呢?
如何使其以群集模式重新启动工作程序?
示例代码
// index.js
let counter = 0;
setInterval(function(){
if(counter >= 5) {
throw new Error('Worker crash. Why no restart?');
}
counter++;
console.log('Worker alive: ' + Date.now() );
},500);
在cmd行上运行
pm2 start index.js -i 4
pm2 log
最终所有工人都崩溃了,再也没有重新开始 如果它只能在一个进程上完成,那么重启的重点是什么。
pm2日志(合并为单个文件)
Worker alive: 1522937847186
Worker alive: 1522937847231
Worker alive: 1522937847276
Worker alive: 1522937847324
Worker alive: 1522937847691
Worker alive: 1522937847736
Worker alive: 1522937847781
Worker alive: 1522937847830
Worker alive: 1522937848193
Worker alive: 1522937848238
Worker alive: 1522937848283
Worker alive: 1522937848332
Worker alive: 1522937848693
Worker alive: 1522937848738
Worker alive: 1522937848783
Worker alive: 1522937848832
Worker alive: 1522937849194
Worker alive: 1522937849238
Worker alive: 1522937849284
Worker alive: 1522937849333
Error: Worker crash. Why no restart?
at Timeout._onTimeout (/home/usrname/docs/Projects_NodeJS/project/app/index.js:49:11)
at ontimeout (timers.js:466:11)
at tryOnTimeout (timers.js:304:5)
at Timer.listOnTimeout (timers.js:267:5)
Error: Worker crash. Why no restart?
at Timeout._onTimeout (/home/usrname/docs/Projects_NodeJS/project/app/index.js:49:11)
at ontimeout (timers.js:466:11)
at tryOnTimeout (timers.js:304:5)
at Timer.listOnTimeout (timers.js:267:5)
Error: Worker crash. Why no restart?
at Timeout._onTimeout (/home/usrname/docs/Projects_NodeJS/project/app/index.js:49:11)
at ontimeout (timers.js:466:11)
at tryOnTimeout (timers.js:304:5)
at Timer.listOnTimeout (timers.js:267:5)
Error: Worker crash. Why no restart?
at Timeout._onTimeout (/home/usrname/docs/Projects_NodeJS/project/app/index.js:49:11)
at ontimeout (timers.js:466:11)
at tryOnTimeout (timers.js:304:5)
at Timer.listOnTimeout (timers.js:267:5)
答案 0 :(得分:0)
您可以尝试以下代码。如果有帮助,请告诉我。
const cluster = require('cluster');
const numOfCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numOfCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log('worker %d died (%s). restarting...',
worker.process.pid, signal || code);
cluster.fork();
});
}
答案 1 :(得分:0)
降级到Node版本8 LTS似乎解决了这个问题。
我安装了Node版本9,并且在Windows和Ubuntu上都出现了问题,但是当我降级到版本8时,一切正常。