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.
- 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.
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
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
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.