I had an interesting issue one night when we had to deploy. We had a setup where we had two different servers set up on the same docker container, so to start both servers we'd use something like node server1.js & node server2.js
.
I know that using pm2 and other ways of managing the services are way better but at the time we weren't launching a full production build, we just quickly wanted to get it up and running.
But then we had a really strange issue. When you node server1.js
everything works perfect, when you do node server2.js
everything works perfect, but when you do node server1.js & node server2.js
it broke with an error saying that "port 4000 is already in use".
Server 1 was using port 4000 and server 2 was using port 4001, other than that there were no node processes and nothing else was using any ports (or at least certainly not 4000). I spent a good 2 hours searching everything I can for that port, but there was nothing.
I ended up realizing that "something" is happening when you background process the first server that makes it somehow try to restart itself, then it breaks on its own port. It's like it starts it, then dies or something, then immediately tries to restart itself again on the same port.
Till today I don't really have an explanation for why exactly that happened.
I ended up using nohup
which solved the problem and made both servers start up just fine, no more port issues, but I'd really like to understand why.
- Why exactly does using
node server1.js & node server2.js
cause a port conflict (or what's happening there)? - Why exactly does using
nohup
fix it?
EDIT: Based on the comments I guess what's happening is that when you run it in a docker container the shell will automatically exit once you've executed your commands (even if you're in a different shell), so once you background process the first server &
won't pick up on the SIGHUP
signal (or won't send it at all), which makes the first process run without stopping. Using nohup
fixes that because it will pick up on the SIGHUP
signal (or add if it it doesn't exist), so it can properly pick up on the first process being killed and restart it properly, thus avoiding the port conflict. So I guess the only thing left that I don't understand is why the server is started twice in the first place, or why it's restarted on using &
, instead of just starting it once and background processing it.