Since this post has gotten a lot of attention over the years, I've listed the top solutions per platform at the bottom of this post.
Original post:
I want my node.js server to run in the background, i.e.: when I close my terminal I want my server to keep running. I've googled this and came up with this tutorial, however it doesn't work as intended. So instead of using that daemon script, I thought I just used the output redirection (the 2>&1 >> file
part), but this too does not exit - I get a blank line in my terminal, like it's waiting for output/errors.
I've also tried to put the process in the background, but as soon as I close my terminal the process is killed as well.
So how can I leave it running when I shut down my local computer?
Top solutions:
- Systemd (Linux)
- Launchd (Mac)
- node-windows (Windows)
- PM2 (Node.js)
I am surprised that nobody has mentioned Guvnor
I have tried forever, pm2, etc. But, when it comes to solid control and web based performance metrics, I have found Guvnor to be by far the best. Plus, it is also fully opensource.
Edit : However, I am not sure if it works on windows. I've only used it on linux.
If you are running OSX, then the easiest way to produce a true system process is to use
launchd
to launch it.Build a plist like this, and put it into the /Library/LaunchDaemons with the name
top-level-domain.your-domain.application.plist
(you need to be root when placing it):When done, issue this (as root):
and you are running.
And you will still be running after a restart.
For other options in the plist look at the man page here: https://developer.apple.com/library/mac/documentation/Darwin/Reference/Manpages/man5/launchd.plist.5.html
has anyone noticed a trivial mistaken of the position of "2>&1" ?
should be
This answer is quite late to the party, but I found that the best solution was to write a shell script that used the both the
screen -dmS
andnohup
commands.I also add the
>> logfile
bit on the end so I can easily save the nodeconsole.log()
statements.Why did I use a shell script? Well I also added in an if statement that checked to see if the
node myserver.js
process was already running.That way I was able to create a single command line option that both lets me keep the server going and also restart it when I have made changes, which is very helpful for development.
Node.js as a background service in WINDOWS XP
Installation:
Create c:\node\helloworld.js
Open command console and type the following (setx only if Resource Kit is installed)
A nifty batch goodie is to create c:\node\ServiceMe.cmd
Service Management:
You can use Forever, A simple CLI tool for ensuring that a given node script runs continuously (i.e. forever): https://www.npmjs.org/package/forever