1.优雅的停止

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

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

现在pm2 reload会变成一个优雅的Reload。

1.2.配置终止超时

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

  1. pm2 start app.js --kill-timeout 3000

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

  1. module.exports = {
  2. apps : [{
  3. name: 'app',
  4. script: './app.js',
  5. kill_timeout : 3000
  6. }]
  7. }

2.优雅的开始

有时您可能需要等待您的应用程序与您的 DBs/caches/workers/whatever 建立连接。PM2 需要等待,然后才能将您的申请视为online. 为此,您需要提供--wait-ready给 CLI 或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

2.1.配置就绪超时

默认情况下,PM2 等待ready信号的时间为 3000 毫秒。

通过 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
  }]
}

2.2.使用 http.Server.listen 优雅开始

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

3.说明:信号流

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

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

通过设置环境变量PM2_KILL_SIGNAL可以在任何其他信号(例如SIGTERM)上替换信号SIGINT

4.Windows优雅停止

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

通过命令行:

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

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

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