Node has a funny quirk to listening on port 0 in a cluster.
First, what do you expect to happen when you listen on port 0? It means that I don't care what port I'm listening on, I just need one!
So, why don't you just generate a random port number and listen on that?
-Naive network programmer
Now, that will work MOST of the time. However, as a developer creating networking applications, I hate saying that my code will work MOST of the time.
What happens if you randomly select an already busy port? You get an error, and you're probably not handling that test case. I wish, oh how I wish, the operating system provided me some way to listen on a random port that is available!
Oh yeah, there is a way for me to do this. Just listen on port 0.
I <3 you port 0
Listening on port 0 is good... but nodejs has this "feature" that mucks everything up.
why u no work node?
Here's what the docs say about listing on port 0 in node
Normally, this will cause servers to listen on a random port. However, in a cluster, each worker will receive the same "random" port each time they do listen(0). In essence, the port is random the first time, but predictable thereafter. If you want to listen on a unique port, generate a port number based on the cluster worker ID.
So, I can't really listen on port 0 in a cluster. In fact doing so would be irresponsible (especially in a module to be used by other people.)
It's a terrible decision to allow just ONE global port 0 connection for the entire application to share. If ANY module or dependency listens on port 0 in your code, prepare for strange bugs when using cluster.
what I did about it
I debated the issue before 0.8 came out saying that this is wrong. Sadly, I wasn't able to convince @isaacs or @bnoordhuis. The only thing I got from them was that documentation that I made fun of above.
So, I did the next best thing in my power. I wrote a drop-in replacement for node's net module that doesn't have this quirky behavior!
what you can do
- Use net-cluster instead of net if you need to listen on port 0!
- Give me feedback on net-cluster; I want it to be good healthy code!
- Make net-cluster popular! List it as a dependency!
- Let's show our friendly Joyent powers that they need to listen on port 0 the way that Al Gore intended!