-
-
Save mitchellporter/e1c3bfe38e16a16c3c6d5840ceb4802a to your computer and use it in GitHub Desktop.
Graceful shutdown of a nodejs server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
/* | |
* Usage: | |
* | |
* const gracefulShutdown = require('./app/utils/gracefulShutdown'); | |
* | |
* const server = app.listen(port, callback) | |
* | |
* gracefulShutdown.init(server, logger); | |
*/ | |
const assert = require('assert'); | |
function init(server, logger, timeout) { | |
assert.ok(server, 'server must be set'); | |
assert.ok(logger, 'logger must be set'); | |
const forcedTimeout = timeout || 20 * 1000; // default timeout 20 secs | |
function gracefulShutdown() { | |
logger.info('Received SIGINT or SIGTERM. Shutting down gracefully...'); | |
server.close(() => { | |
logger.info('Closed out remaining connections.'); | |
process.exit(); | |
}); | |
// force stop after timeout | |
setTimeout(() => { | |
logger.error('Could not close connections in time, forcefully shutting down'); | |
process.exit(); | |
}, forcedTimeout); | |
} | |
// e.g. kill | |
process.on('SIGTERM', gracefulShutdown); | |
// e.g. Ctrl + C | |
process.on('SIGINT', gracefulShutdown); | |
} | |
module.exports.init = init; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment