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)
This might not be the accepted way, but I do it with screen, especially while in development because I can bring it back up and fool with it if necessary.
The screen will detach and survive you logging off. Then you can get it back back doing screen -r. Hit up the screen manual for more details. You can name the screens and whatnot if you like.
UPDATE - As mentioned in one of the answers below, PM2 has some really nice functionality missing from forever. Consider using it.
Original Answer
Use nohup:
EDIT I wanted to add that the accepted answer is really the way to go. I'm using forever on instances that need to stay up. I like to do
npm install -g forever
so it's in the node path and then just doforever start server.js
I use tmux for a multiple window/pane development environment on remote hosts. It's really simple to detach and keep the process running in the background. Have a look at tmux
PM2 is a production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, to reload them without downtime and to facilitate common system admin tasks. https://github.com/Unitech/pm2
UPDATE: i updated to include the latest from pm2:
for many use cases, using a systemd service is the simplest and most appropriate way to manage a node process. for those that are running numerous node processes or independently-running node microservices in a single environment, pm2 is a more full featured tool.
https://github.com/unitech/pm2
http://pm2.io
pm2 monit
or process list withpm2 list
pm2 logs
The accepted answer is probably the best production answer, but for a quick hack doing dev work, I found this:
nodejs scriptname.js &
didn't work, because nodejs seemed to gobble up the &, and so the thing didn't let me keep using the terminal without scriptname.js dying.But I put
nodejs scriptname.js
in a .sh file, andnohup sh startscriptname.sh &
worked.Definitely not a production thing, but it solves the "I need to keep using my terminal and don't want to start 5 different terminals" problem.