教程 > pm2 教程 > pm2 高级 阅读:1180

pm2 优雅的开启/关闭应用程序

优雅的关闭

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

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

现在 pm2 reload 将变成优雅的重载


配置kill超时

通过CLI,将延长超时至3000ms:

$ pm2 start server.js --kill-timeout 3000

通过配置文件,要使用 kill_timeout 选项

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

优雅的开启

有时,你可能需要等待应用程序与DBS/CACHES/Worker的连接进行连接。 PM2需要等待,然后在将申请视为在线申请之前。 为此,你需要为CLI提供 - 就绪或在进程文件中提供 wait_ready: true。 这将使PM2 监听那个事件。 在应用程序中,当希望将应用程序视为准备就绪时,你需要添加process.send('ready')

app.js

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等待3000ms用于就绪信号。

通过下面的命令,延长超时到10000ms:

$ 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服务器接受连接时,它将自动将应用程序状态置为 Ready。 你可以使用与-wait-ready的变量相同的变量来增加PM2等待时间侦听 - Process文件中的 Listen_timeout 属性或终端命令中的 --listen-timeout = xxxx


Windows 优雅的关闭

当信号不可用时,进程将被终止。在这种情况下,必须通过CLI使用 --shutdown-with-message 或在 ecosystem.config.js 文件中使用 shutdown_with_message 监听关机事件。

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

查看笔记

扫码一下
查看教程更方便