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:
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:
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:
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:
Add this line to the end of the file:
Check it works
Reboot Linux (sudo reboot
), when it’s finished booting your app should be running.