在生产环境中运行Express应用程序时,我希望在服务器进程终止时(即发送SIGTERM
或SIGINT
)正常关闭服务器.
以下是我的代码的简化版本:
const express = require('express');
const app = express();
app.get('/', (req, res) => res.json({ ping: true }));
const server = app.listen(3000, () => console.log('Running…'));
setInterval(() => server.getConnections(
(err, connections) => console.log(`${connections} connections currently open`)
), 1000);
process.on('SIGTERM', shutDown);
process.on('SIGINT', shutDown);
function shutDown() {
console.log('Received kill signal, shutting down gracefully');
server.close(() => {
console.log('Closed out remaining connections');
process.exit(0);
});
setTimeout(() => {
console.error('Could not close connections in time, forcefully shutting down');
process.exit(1);
}, 10000);
}
当我运行它并调用URL时http://localhost:3000/在浏览器中,setInterval函数中的log语句将一直打印"1连接当前打开",直到我真正关闭浏览器窗口.很明显,即使关闭标签也会保持连接打开.
因此,当我点击Ctrl+C终止服务器时,它将进入超时状态,并在10秒后打印"无法关闭连接",同时继续打印"1连接打开".
只有在终止进程之前关闭浏览器窗口,我才会收到"关闭剩余连接"消息.
What am I missing here? What is the proper way to shut down an Express server gracefully?