【发布时间】:2021-01-08 21:56:56
【问题描述】:
我在我的 nodejs 应用程序中使用 nodemon 来在应用更改时自动重启。但是当我在ubuntu环境中使用'Ctrl + C'停止nodemon时,不会停止nodejs。我必须搜索从端口运行的进程,并且必须使用 kill -9 手动终止。我该如何解决这个问题?
【问题讨论】:
标签: node.js ubuntu-16.04
我在我的 nodejs 应用程序中使用 nodemon 来在应用更改时自动重启。但是当我在ubuntu环境中使用'Ctrl + C'停止nodemon时,不会停止nodejs。我必须搜索从端口运行的进程,并且必须使用 kill -9 手动终止。我该如何解决这个问题?
【问题讨论】:
标签: node.js ubuntu-16.04
快速而肮脏的解决方案
process.on('SIGTERM', stopHandler);
process.on('SIGINT', stopHandler);
process.on('SIGHUP', stopHandler);
function stopHandler() {
console.log('Stopped forcefully');
process.exit(0);
}
正确的解决方案
实施Graceful Shutdown 是最佳实践。在这个例子中,我应该只停止服务器。如果服务器停止的时间超过 2 秒,则进程将以退出代码 1 终止。
process.on('SIGTERM', stopHandler);
process.on('SIGINT', stopHandler);
process.on('SIGHUP', stopHandler);
async function stopHandler() {
console.log('Stopping...');
const timeoutId = setTimeout(() => {
process.exit(1);
console.error('Stopped forcefully, not all connection was closed');
}, 2000);
try {
await server.stop();
clearTimeout(timeoutId);
} catch (error) {
console.error(error, 'Error during stop.');
process.exit(1);
}
}
【讨论】:
netstat -ltnp | grep -w ':PORT' 然后kill -9 ProcessID [1]:*.com/users/4850916/galkin