Closing database connection in Express 3

express, node.js

Solution

Based on the info from:

- https://github.com/visionmedia/express/issues/1366

- http://blog.argteam.com/coding/hardening-node-js-for-production-part-3-zero-downtime-deployments-with-nginx/

--

var express = require('express');

var app = express();
var server = app.listen(1337);
var shutting_down = false;

app.use(function (req, resp, next) {
 if(!shutting_down)
   return next();

 resp.setHeader('Connection', "close");
 resp.send(503, "Server is in the process of restarting");
 // Change the response to something your client is expecting:
 //   html, text, json, etc.
});

function cleanup () {
  shutting_down = true;
  server.close( function () {
    console.log( "Closed out remaining connections.");
    // Close db connections, other chores, etc.
    process.exit();
  });

  setTimeout( function () {
   console.error("Could not close connections in time, forcing shut down");
   process.exit(1);
  }, 30*1000);

}

process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);

The `Connection: close` header is used to tell any `keep-alive` connection to close the next time they send a HTTP request. More info here: http://www.jmarshall.com/easy/http/#http1.1s4

I have no idea if there are other ways of closing the `keep-alive` connection. The node process will hang unless the `keep-alive` connections are closed. The default idle timeout is 2 mins. More info. on node.js `keep-alive` timeouts (including on changing the timeout): How to set the HTTP Keep-Alive timeout in a nodejs server

Problem

In Express 3, how do you handle closing database connections when the process exists? The `.on('close', ...` event is not emitted unless you explicitly use a HTTP server's `.close()` call. So far, this is the closest I've come, but it uses `process.on` instead of `server.on`: ``` process.on('SIGTERM', function () { // Close connections. process.exit(0); }); ```

Original source

Related problems