優雅停止
若要允許優雅重新啟動/重新載入/停止程序,請務必攔截 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 需要等待,才會將您的應用程式視為 線上
。為此,您需要提供 --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
設定準備就緒逾時
預設情況下,PM2 會等待 3000 毫秒,以取得 ready
訊號。
透過 CLI,這會將逾時延長至 10000 毫秒
pm2 start app.js --wait-ready --listen-timeout 10000
透過 應用程式宣告 使用 listen_timeout
和 wait_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 訊號以強制程序結束。
訊號SIGINT 可以透過設定環境變數PM2_KILL_SIGNAL替換為任何其他訊號(例如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)
}
})