Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly shutdown an ExpressJs server?

I have an ExpressJs (version 4.X) server, and I need to correctly stop the server.

As some requests can take on long time (1-2 seconds), I must reject new connections and wait the end of all the requests in progress. Kill the server in the middle of some tasks could put the server in an unstable state.

I've tried the following code:

//Start
var app = express();
var server = https.createServer(options, app);
server.listen(3000);


//Stop
process.on('SIGINT', function() {
    server.close();
});

However, this code doesn't close keep-alive connections, and some clients can keep the connexion for a long time.

So, how can I properly close all connections ?

like image 409
BAK Avatar asked Sep 29 '22 23:09

BAK


1 Answers

You could use some middleware to block new requests if the server is being shut down.

var app = express(),
    shuttingDown = false;

app.use(function(req, res, next) {
    if(shuttingDown) {
        return;
    }
    next();
});

var server = https.createServer(options, app);
server.listen(3000);

process.on('SIGINT', function() {
    shuttingDown = true;
    server.close(function(){
        process.exit();
    });
});
like image 59
Ben Fortune Avatar answered Oct 16 '22 10:10

Ben Fortune