Start Forever.js on System Restarts
Some time ago, I wrote a post on keeping Node.js apps running even after logging out from the shell. It was cool and all, but soon you will soon realize that Forever alone is not enough. Because, on system reboots, Forever itself is killed. Who will restart your app now?
There are many options for handling this kind of scenario, but today we will implement a solution using
cron. Let's find out how we can make Forever and our Node.js app reboot-proof.
The app you want Forever to start on system restart is probably a web app, so let's try this thing on an Express.js web app.
Install Express, if you haven't already:
$ npm install -g express
Now, create an Express app:
$ mkdir example
$ cd example
There we have our Express app. It should be started using Forever - on system reboots - automatically.
First we need to write a bash script to check if our app is running or not; if it is not running, it should start the app using Forever. Create a file named
app-starter.sh in your home directory with this content:
if [ $(ps aux | grep $USER | grep node | grep -v grep | wc -l | tr -s "\n") -eq 0 ]
forever start ~/example/app.js > /dev/null
Note how we augmented the environment variables in the script. Those are crucial to making the script work successfully from
cron. Change the
NODE_ENV variable, according to your requirement.
/usr/local/bin needs to be added to
PATH, else Forever just won't work on most systems.
Next, make the script executable:
$ chmod 700 ~/app-starter.sh
Then, run it and load
http://localhost:3000 on your browser to confirm it actually started our app using Forever:
Looking good. Now it's time to make
cron do the job for us. We want to make sure that the
app-starter script is execute when the system is rebooted. Append the following code to
@reboot ~/app-starter.sh >> cron.log 2>&1
# guess what the commented line below would do if enabled
# */1 * * * * ~/app-starter.sh >> cron.log 2>&1
To open crontab:
$ crontab -e
After making changes to
crontab, restart your system.
http://localhost:3000 on your browser to behold the magic of Forever +
cron 😀 Now you don't have to worry about system restarts taking your app down, anymore.
cron takes care of Forever, and Forever takes care of your app; and you win at life!
While this example is perfect for a single app, you will need to hack the
app-starter script to make it work for more than one Node.js app. How to do that is your homework. All the best!