Skip to content

Instantly share code, notes, and snippets.

@gerlacdt
Created October 25, 2016 07:33
Show Gist options
  • Save gerlacdt/43358e315ddd18128ef7df35dfc6e54d to your computer and use it in GitHub Desktop.
Save gerlacdt/43358e315ddd18128ef7df35dfc6e54d to your computer and use it in GitHub Desktop.
Graceful shutdown of a nodejs server
'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