Running a NodeJS service forever on Linux
I had a NodeJS app that I wanted to run indefinitely in the background on my Raspberry Pi.
There are a few ways to do this. Here’s the one I used.
I like this approach because it’s very low maintenance and fast to set up. Your experience may differ in which case I recommend trying one of the other well-known approaches.
Prerequisites
- Have a NodeJS app you wish to run forever in the background.
- A Linux installation to run your app on.
- NodeJS and NPM installed on said Linux installation.
Install forever
The NPM package forever abstracts away much of the pain of running something in the background.
Add it locally to your app:
npm install forever --save
Note: If you’re using NPM 5+ you can omit --save
as it’s implicit.
Add NPM scripts
Add two scripts to your package.json
file, one to start your app with forever
and one to stop it:
/* Rest of file omitted. */
"scripts": {
"start-background": "forever start index.js",
"stop-background": "forever stop index.js"
}
Note: In the above example index.js
is the entry point to start the application,
yours may differ.
Why use NPM scripts instead of installing forever
globally
and invoking it manually? I prefer to avoid global NPM packages,
but feel free to use them in your own setup.
Test the scripts
Run the scripts to test that they work:
$ npm run start-background
> forever start index.js
warn: --minUptime not set. Defaulting to: 1000ms
warn: --spinSleepTime not set. Your script will exit if it does not stay up for at least 1000ms
info: Forever processing file: index.js
$ npm run stop-background
> forever stop index.js
info: Forever stopped process:
uid command script forever pid id logfile uptime
[0] 5YL5 /Users/shaun/.nvm/versions/node/v7.9.0/bin/node index.js 3022 3039 /Users/shaun/.forever/5YL5.log 0:0:0:33.780
Hook up cron
Now you have the ability to make your script start and stop in the background, you need to add something to your crontab so that it starts when Linux boots.
Open your crontab file:
crontab -e
Add this line to the end of the file:
@reboot /usr/bin/npm run start-background --prefix ~/path/to/repo
Check it works
Reboot Linux (sudo reboot
), when it’s finished booting your app should be running.