Introduction: Node.js App As a RPI Service (boot at Startup)
I wanted to make a Node.js app/script I wrote, persistent among reboots, on my Raspberry Pi 2. Although Forever gives us the possibility of running a script continuously (on background), that doesn't include system reboots whether manual or by power failures...
After digging on the web with lots of info, i found a way that works for me, and I'm sharing it so that, hopefuly, it will help someone. On the PI, there's a directory ( /etc/init.d ) where some services are specified, as well as the commands and parameters to use them. That allows us to create a service to be called on every boot of the RPI.
Step 1: Service Specification
My Node.js app is called myNodeApp.js and lies on /usr/local/bin/server/ directory.
The first step, on terminal window, is change to the etc/init.d folder (as root)
$ cd /etc/init.d
Create a new file, using a text editor like 'nano'. In this case let's call the service we want to create "myService":
$ nano myService
The contents of the new file are these: (Note the 4th line where my particular Node.js instalation is specified)
#!/bin/sh #/etc/init.d/myService export PATH=$PATH:/usr/local/bin export NODE_PATH=$NODE_PATH:/usr/local/lib/node_modules case "$1" in start) exec forever --sourceDir=/usr/local/bin/server -p /usr/local/bin/server myNodeApp.js #scriptarguments ;; stop) exec forever stop --sourceDir=/usr/local/bin/server myNodeApp.js ;; *) echo "Usage: /etc/init.d/myService {start|stop}" exit 1 ;; esac exit 0
Step 2: How to Use the Newly Created Service
After creating the service on step1 we need to make it ready to run on boot:
The file we created is a text file, so we need to make it executable with the following command:
chmod 755 /etc/init.d/myService
Now we can test it:
sh /etc/init.d/myService start/stop
If all goes well we can, finally, make it bootable:
update-rc.d myService defaults
To remove it from boot:
update-rc.d -f myService remove
I have it running for a few months without any fault...Hope you enjoy...