How to start a Node.js app on system boot?

user2650875 picture user2650875 · Feb 4, 2014 · Viewed 23.5k times · Source

I'm working on a Raspberry Pi running Raspbian running a Node.js app and trying to get it to start when the Pi boots. I found a couple of examples but I can't seem to get it working. My current code is:

#! /bin/sh
# /etc/init.d/MyApp

### BEGIN INIT INFO
# Provides:          MyApp.js
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Starts MyApp.js
# Description:       Start / stop MyApp.js at boot / shutdown.
### END INIT INFO

# If you want a command to always run, put it here

# Carry out specific functions when asked to by the system
case "$1" in
   start)
    echo "Starting MyApp.js"
    # run application you want to start
    node /home/pi/app/MyApp/MyApp.js
   ;;
   stop)
    echo "Stopping MyApp.js"
    # kill application you want to stop
    killall MyApp.js
    ;;
  *)
    echo "Usage: /etc/init.d/MyApp {start|stop}"
    exit 1
    ;;
esac

exit 0

I have this in the etc/init.d folder, ran chmod +x /etc/init.d/MyApp, I'm able to run it manually, then I run sudo update-rc.d MyApp defaults, reboot and the script never runs. I've looked at some different examples, made adjustments and still no luck.

Answer

Mohit Athwani picture Mohit Athwani · Feb 17, 2014

I solved this problem by first checking where node.js was installed on RaspberryPi:

which node

This gave me :

/usr/local/bin/node

Open crontab config:

sudo crontab -e

Then in my crontab :

@reboot sudo /usr/local/bin/node <complete path to your .js app> &

Save, reboot, and problem solved !