Raspberry Pi - init.d script to run a node app on boot using Forever

References
http://labs.telasocial.com/raspberry-nodejs-init.d/ << the big one.
http://blog.podrezo.com/init-d-startupshutdown-script-for-node-js-applications-via-forever/
https://www.exratione.com/2013/02/nodejs-and-forever-as-a-service-simple-upstart-and-init-scripts-for-ubuntu/
http://www.stuffaboutcode.com/2012/06/raspberry-pi-run-program-at-start-up.html

This should be easy, but it really, really isn't, primarily because it relies super heavily on your use of the correct directory structure, which is tricky when you're new to command-line computing.

In the end, I made this work by copying all my files to a directory in /home/pi (which, weirdly, displays as a simple directory when one types "ls" with no arguments) and then running it directly from there using a very, very basic init.d file. All of the above have many more options and commentary about what they're doing.

By convention, init.d scripts live in /etc/init.d. If there is something obviously wrong below, feel free to comment.

So!

  • Put your node application into the home directory, or somewhere you can reliably find it.
  • Make sure it actually boots when you run forever normally.
  • Then do this bit.

sudo nano /etc/init.d/MyScriptName

#!/bin/bash
### BEGIN INIT INFO
# Provides:             MyScriptName
# Required-Start:       $local_fs
# X-UnitedLinux-Should-Start:
# Required-Stop:        $local_fs
# X-UnitedLinux-Should-Stop:
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    MyScriptName does a thing
# Description:          MyScriptName does a longer thing
### END INIT INFO

case "$1" in
        start)
                su - pi -c "forever start --spinSleepTime 5000 --sourceDir=/home/pi/MyScriptDirectory MyScriptName.js"
                ;;
        stop)
                su - pi -c "forever stopall"
                forever stopall
                ;;
        restart)
                su - pi -c "forever restartall"
                forever restartall
                ;;
        status)
                su - pi -c "forever list"
                forever list
                ;;
esac

sudo update-rc.d MyScriptName defaults

This should add your file to the list of services that turn on at boot.

Notes
You do need to include the superuser command. It won't work properly without it.

There is some discussion in the reference pages of how forever handles services as versus how upstart handles services as versus how init.d handles things. The main point is that Forever will keep your app running, even though Node apps crash a lot, and node apps that serve gigantor quantities of static video files crash even more. I don't think there is a good way to serve huge amounts of video. YouTube is an illusion. Netflix ditto.

It happens.

Big thanks to this blog author

Latest blog

Web Analytics