优雅启动/关闭

优雅停止

为了允许进程优雅地重启/重新加载/停止,请确保您拦截了 SIGINT 信号并在应用程序退出之前清除了所有需要的内容(如数据库连接、处理作业…)。

process.on('SIGINT', function() {
   db.stop(function(err) {
     process.exit(err ? 1 : 0)
   })
})

现在 pm2 reload 将变为 gracefulReload。

配置终止超时

通过 CLI,这会将超时时间延长至 3000 毫秒

pm2 start app.js --kill-timeout 3000

通过 应用程序声明 使用 kill_timeout 属性

module.exports = {
  apps : [{
    name: 'app',
    script: './app.js',
    kill_timeout : 3000
  }]
}

优雅启动

有时,您可能需要等待应用程序与数据库/缓存/工作进程/任何内容建立连接。PM2 需要等待,然后才能将您的应用程序视为 online(在线)。为此,您需要向 CLI 提供 --wait-ready 或在进程文件中提供 wait_ready: true。这将使 PM2 侦听该事件。在您的应用程序中,当您希望应用程序被视为已准备好时,需要添加 process.send('ready');

var http = require('http')

var app = http.createServer(function(req, res) {
  res.writeHead(200)
  res.end('hey')
})

var listener = app.listen(0, function() {
  console.log('Listening on port ' + listener.address().port)
  // Here we send the ready signal to PM2
  process.send('ready')
})

然后启动应用程序

pm2 start app.js --wait-ready

配置就绪超时

默认情况下,PM2 会等待 3000 毫秒以接收 ready 信号。

通过 CLI,这会将超时时间延长至 10000 毫秒

pm2 start app.js --wait-ready --listen-timeout 10000

通过 应用程序声明 使用 listen_timeoutwait_ready 属性

module.exports = {
  apps : [{
    name: 'app',
    script: './app.js',
    wait_ready: true,
    listen_timeout: 10000
  }]
}

使用 http.Server.listen 进行优雅启动

仍然存在默认系统,该系统会挂接到 http.Server.listen 方法。当您的 http 服务器接受连接时,它会自动将您的应用程序状态设置为就绪。您可以使用与 --wait-ready 优雅启动相同的变量来增加 PM2 等待侦听的时间:进程文件中的 listen_timeout 条目或通过 CLI 使用 --listen-timeout=XXXX

说明:信号流

当 PM2 停止/重启进程时,系统会按给定顺序向您的进程发送一些系统信号。

首先,会向您的进程发送 SIGINT 信号,您可以捕获该信号以了解您的进程将要停止。如果您的应用程序在 1.6 秒内没有自行退出可自定义,它将收到 SIGKILL 信号以强制进程退出。

可以通过设置环境变量 PM2_KILL_SIGNALSIGINT 信号替换为任何其他信号(例如 SIGTERM)。

Windows 优雅停止

当信号不可用时,您的进程将被终止。在这种情况下,您必须通过 CLI 使用 --shutdown-with-message 或在生态系统文件中使用 shutdown_with_message,并侦听 shutdown 事件。

通过 CLI

pm2 start app.js --shutdown-with-message

通过 应用程序声明 使用 shutdown_with_message 属性

module.exports = {
  apps : [{
    name: 'app',
    script: './app.js',
    shutdown_with_message: true
  }]
}

侦听 shutdown 事件

process.on('message', function(msg) {
  if (msg == 'shutdown') {
    console.log('Closing all connections...')
    setTimeout(function() {
      console.log('Finished closing connections')
      process.exit(0)
    }, 1500)
  }
})
为此页面做出贡献