Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graceful shutdown of a node.JS HTTP server

Tags:

http

node.js

exit

Here is a simple webserver I am working on

var server = require("http").createServer(function(req,resp) {     resp.writeHead(200,{"Content-Type":"text/plain"})     resp.write("hi")     resp.end()     server.close() }) server.listen(80, 'localhost') // The shortest webserver you ever did see! Thanks to Node.JS :) 

Works great except for keep-alive. When the first request comes in, server.close gets called. But the process does not end. Actually the TCP connection is still open which allows another request to come through which is what I am trying to avoid.

How can I close existing keep-alive connections?

like image 840
700 Software Avatar asked Mar 10 '11 17:03

700 Software


People also ask

How do I shutdown my HTTP server?

Simply shutdown HTTP server http. Server provides Shutdown method for graceful shutdown. Run a server and send a request to /shutdown , then the server stops. This is just enough for shutdown but a HTTP client cannot know whether the shutdown has been successfully done or not.

What is gracefully shutdown?

A graceful shutdown is when a computer is turned off by software function and the operating system (OS) is allowed to perform its tasks of safely shutting down processes and closing connections. A hard shutdown is when the computer is forcibly shut down by interruption of power.


1 Answers

You can control the idle timeout for a connection, so you can set how long a keep-alive connection will remain open. For example:

server=require('http').createServer(function(req,res) {     //Respond     if(req.url.match(/^\/end.*/)) {         server.close();         res.writeHead(200,{'Content-Type':'text/plain'});         res.end('Closedown');     } else {         res.writeHead(200,{'Content-Type':'text/plain'});         res.end('Hello World!');     } }).listen(1088); //Set the idle timeout on any new connection server.addListener("connection",function(stream) {     stream.setTimeout(4000); }); 

We can test this with netcat:

ben@quad-14:~/node$ echo -e "GET /test HTTP/1.1\nConnection: keep-alive\n\n" | netcat -C -q -1 localhost 1088 HTTP/1.1 200 OK Content-Type: text/plain Connection: keep-alive Transfer-Encoding: chunked  c Hello World! 0  

after 4 seconds, the connection closes

And now we can show that closing the server works: after all idle connections are dropped, the server exits:

ben@quad-14:~/node$ echo -e "GET /end HTTP/1.1\nConnection: keep-alive\n\n" | netcat -C -q -1 localhost 1088 HTTP/1.1 200 OK Content-Type: text/plain Connection: keep-alive Transfer-Encoding: chunked  9 Closedown 0 

after 4 seconds, the connection closes and the server exits

like image 54
Ben Last Avatar answered Sep 28 '22 05:09

Ben Last