Node.js 使用Docker Swarm时优雅地关闭nodejs微服务
我准备在Docker Swarm中运行多个用Nodejs Koa编写的微服务 由于像Kubernetes或Swarm这样的容器编排工具可以立即放大和缩小服务,所以我对优雅地关闭Nodejs服务以防止未完成的运行过程有一个疑问 以下是我能想到的流程:Node.js 使用Docker Swarm时优雅地关闭nodejs微服务,node.js,docker-swarm,koa2,Node.js,Docker Swarm,Koa2,我准备在Docker Swarm中运行多个用Nodejs Koa编写的微服务 由于像Kubernetes或Swarm这样的容器编排工具可以立即放大和缩小服务,所以我对优雅地关闭Nodejs服务以防止未完成的运行过程有一个疑问 以下是我能想到的流程: 向每个工作进程发送重要信号,docker会蜂拥而至吗 缩小服务规模时向员工发送签名 工人负责捕捉信号,清理或释放任何 已使用资源并完成its过程,如何停止新api 请求,等待任何正在运行的进程完成后再关闭 向下? 下面是一些参考代码: process
签名
process.on('SIGINT', () => {
const cleanUp = () => {
// How can I clean resources like DB connections using Sequelizer
}
server.close(() => {
cleanUp()
process.exit()
})
// Force close server after 5secs, `Should I do this?`
setTimeout((e) => {
cleanUp()
process.exit(1)
}, 5000)
})
const gracefulShutdown = require('http-graceful-shutdown');
...
server = app.listen(...);
...
// your personal cleanup function - this one takes one second to complete
function cleanup() {
return new Promise((resolve) => {
console.log('... in cleanup')
setTimeout(function() {
console.log('... cleanup finished');
resolve();
}, 1000)
});
}
// this enables the graceful shutdown with advanced options
gracefulShutdown(server,
{
signals: 'SIGINT SIGTERM',
timeout: 30000,
development: false,
onShutdown: cleanup,
finally: function() {
console.log('Server gracefulls shutted down.....')
}
}
);
我个人会将最终超时从5秒增加到更高的值(10-30秒)。希望能有所帮助。我创建了一个库(),它可以处理您描述的正常关机。与Express和膝关节炎手术效果良好。
这个包还允许您创建函数(应该返回一个承诺)来额外清理诸如DB之类的东西。。。下面是一些如何使用它的示例代码:
const gracefulShutdown = require('http-graceful-shutdown');
...
server = app.listen(...);
...
// your personal cleanup function - this one takes one second to complete
function cleanup() {
return new Promise((resolve) => {
console.log('... in cleanup')
setTimeout(function() {
console.log('... cleanup finished');
resolve();
}, 1000)
});
}
// this enables the graceful shutdown with advanced options
gracefulShutdown(server,
{
signals: 'SIGINT SIGTERM',
timeout: 30000,
development: false,
onShutdown: cleanup,
finally: function() {
console.log('Server gracefulls shutted down.....')
}
}
);
我个人会将最终超时从5秒增加到更高的值(10-30秒)。希望有帮助。我相信Docker Swarm先发送一个SIGTERM,然后发送一个SIGKILL,所以您可能希望将代码移出
进程。on('SIGTERM',()=>{})
我相信Docker Swarm先发送一个SIGTERM,然后发送一个SIGKILL,所以您可能希望将代码移出进程。on('SIGTERM',()=>{})