Keep Node running forever

If you’ve ever started up a deployed Node application, you’ve probably had this problem: you start the server with node server.js, check on your site, and it’s up and running. Great! Some time later, your SSH session times out or you close your terminal. Then you go to your site, and it’s down. What happened?

You ran the server in the foreground, which means that when you log out of SSH, it will be stopped along with all the other running processes.

I’ve found two good solutions. Before using either of them, make sure you are starting the server with root privileges by running sudo -i. This will take you to the root of the server, so you will need to cd back to the folder where the server file is located.

Method 1: Run node in the background

In this method, you start Node with the & flag to run it in the background and the nohup flag to detach it from the console window.

To start the Node server:

sudo nohup node server.js &

To shut down the Node server, first find the running process ID with:

ps -aef | grep node
// root     21404     1  0 08:05 ?        00:00:00 node server.js
// alex     21530 21494  0 08:08 pts/0    00:00:00 grep --color=auto node

Then kill the process via the ID:

sudo kill 21404

More details are in these Stack Overflow posts: run node permanently and stop node.

Method 2: Use Forever to keep the server up

In this method, you install Forever and use it to run the server for you. This method is more robust, because it will restart your server automatically if it crashes.

Make sure to use forever start to run the server as a service.

sudo npm install -g forever
sudo forever start server.js

Now, when you close your terminal window, Node will continue to run. Here are a few helpful forever commands from the StackOverflow post:

To list all running processes:

forever list

Note the integer in the brackets and use it as following to stop a process:

sudo forever stop 0

Restarting a running process goes:

sudo forever restart 0

If you’re working on your application file, you can use the -w parameter to restart automatically whenever your server.js file changes:

sudo forever -w server.js

More info on Forever is available on GitHub.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *