From 79da225b9f63aa9b9370c8abc21bae9ee1f0d04a Mon Sep 17 00:00:00 2001 From: jomo Date: Sun, 16 Aug 2015 22:11:08 +0200 Subject: [PATCH] gracefully shut down on SIGTERM this will close the server, i.e. all new connections will be dropped while existing connections are able to complete within 30 seconds otherwise they are dropped and the server force quits --- lib/server.js | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/lib/server.js b/lib/server.js index b480a3e..d9380a0 100644 --- a/lib/server.js +++ b/lib/server.js @@ -131,18 +131,33 @@ var exp = {}; exp.boot = function(callback) { var port = process.env.PORT || 3000; var bind_ip = process.env.BIND || "0.0.0.0"; - logging.log("Server running on http://" + bind_ip + ":" + port + "/"); server = http.createServer(requestHandler).listen(port, bind_ip, function() { + logging.log("Server running on http://" + bind_ip + ":" + port + "/"); if (callback) { callback(); } }); + + // stop accepting new connections, + // wait for established connections to finish (30s max), + // then exit + process.on("SIGTERM", function() { + logging.warn("Got SIGTERM, no longer accepting connections!"); + + setTimeout(function() { + logging.error("Dropping connections after 30s. Force quit."); + process.exit(1); + }, 30000); + + server.close(function() { + // all connections have been closed + process.exit(); + }); + }); }; exp.close = function(callback) { - server.close(function() { - callback(); - }); + server.close(callback); }; module.exports = exp;