Can I make a HTTP server listen on a shared socket, to allow no-downtime code upgrades?
Problem
I want to be able to kill my old process after a Code update without any downtime.
In Ruby, I do this by using Unicorn. When you send the Unicorn master process a USR1 kill signal, it spawns a new copy of itself, which means all the libraries get loaded from file again. There's a callback available when a Unicorn master has loaded its libraries and its worker processes are ready to handle requests; you can then put code in here to kill the old master by its PID. The old master will then shut down its worker processes systematically, waiting for them to conclude any current requests. This means you can deploy code updates without dropping a single request, with 0 downtime.
Is it possible to do this in Node? There seem to be a lot of libraries vaguely to do with this sort of thing - frameworks that seem to just do mindless restarting of the process after a crash, and stuff like that - but I can't find anything that's a stripped-down implementation of this basic pattern. If possible I'd like to do it myself, and it wouldn't be that hard - I just need to be able to do http.createServer().listen() and specify a socket file (which I'll configure nginx to send requests to), rather than a port.
Solution
Both the net
and http
modules have versions of listen
that take a path to a socket and fire their callback once the server has been bound.
Furthermore, you can use the new child_process.fork
to launch a new Node process. This new process has a communication channel built in to its parent, so could easily tell its parent to exit once initialized.
net
documentationhttp
documentationchild_process.fork
documentation
(For the first two links, look just under the linked-to method, since they are all the same method name.)
Discussion
View additional discussion.