【问题标题】:Shutting down nodejs microservice gracefully when using Docker Swarm使用 Docker Swarm 时优雅地关闭 nodejs 微服务
【发布时间】:2017-09-21 18:06:33
【问题描述】:

我有多个用Nodejs Koa 编写的微服务在Docker Swarm 中运行。

由于 Kubernetes 或 Swarm 等容器编排工具可以即时扩展和缩减服务,我有一个问题是优雅地关闭 Nodejs 服务以防止未完成的运行过程。

下面是我能想到的流程:

  1. 向每个工作进程发送一个 SIGNINT 信号,docker swarm 缩减服务时向工作人员发送SIGNINT?
  2. 工人负责捕捉信号,清理或释放任何 使用资源并完成其进程,如何停止新的 api 请求,等待任何正在运行的进程完成后再关闭 下来了吗?

    以下部分代码来自参考:

    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)
    })
    

【问题讨论】:

  • 我相信 Docker Swarm 会发送一个 SIGTERM,然后是一个 SIGKILL,所以您可能希望将您的代码移到 process.on('SIGTERM', () => {})

标签: node.js docker-swarm koa2


【解决方案1】:

我创建了一个库 (https://github.com/sebhildebrandt/http-graceful-shutdown),可以按照您的描述处理正常关闭。适用于 Express 和 Koa。

这个包还允许你创建函数(应该返回一个承诺)来额外清理数据库的东西,......这里有一些示例代码如何使用它:

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 秒)。希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2013-06-27
    • 2019-02-13
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    相关资源
    最近更新 更多