How to set the HTTP Keep-Alive timeout in a nodejs server
For Express 3:
var express = require('express');var app = express();var server = app.listen(5001);server.on('connection', function(socket) { console.log("A new connection was made by a client."); socket.setTimeout(30 * 1000); // 30 second timeout. Change this as you see fit.});
To set keepAliveTimeout on the express server do:
var express = require('express');var app = express();var server = app.listen(5001);server.keepAliveTimeout = 30000;
For Node.js 10.15.2
and newer with express, only server.keepAliveTimeout
was not enough. We also need to configure server.headersTimeout
longer than server.keepAliveTimeout
.
server.keepAliveTimeout = 30000; // Ensure all inactive connections are terminated by the ALB, by setting this a few seconds higher than the ALB idle timeoutserver.headersTimeout = 31000; // Ensure the headersTimeout is set higher than the keepAliveTimeout due to this nodejs regression bug: https://github.com/nodejs/node/issues/27363