Monday, April 14, 2014

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

References << the big one.

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.


  • 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

# 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

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

sudo update-rc.d MyScriptName defaults

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

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.

No comments:

Post a Comment