How to start Node-red automatically on boot using init.d

Print

This procedure describes how to start Node-red automatically when the PLCnext starts. It is a alternative to pm2 that apparently it is not working with the node from PLCnext Store.

The idea is to include a script to run in init.d directory. The script bellow was adapted from the script found in the node-red page.

Procedure

1) Log in to the PLC as root:

Using username "admin".
This email address is being protected from spambots. You need JavaScript enabled to view it..1.2's password:
Last login: Wed May 8 15:33:03 2019 from 192.168.1.120
admin@axcf2152:~$ su root
Password:
root@axcf2152:/opt/plcnext/#

2) Change to init.d folder and open a new file with the name "start_nodered"

root@axcf2152:/opt/plcnext/# cd /etc/init.d
root@axcf2152:/etc/init.d# sudo nano start_nodered

 3) Copy the script bellow to this file. This script can be found in the follow link Link to start_nodered script

#! /bin/sh
### BEGIN INIT INFO
# Provides:          node-red
# Required-Start:    $local_fs $remote_fs $network
# Required-Stop:     $local_fs $remote_fs $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 6
# Short-Description: Start or stop the node-red server
### END INIT INFO

# Script to start node-red with PLCnext from Phoenix Contact using init.d 
# Execute these commands:
# sudo chmod 755 start_nodered
# sudo update-rc.d start_nodered defaults 99

USER=root

USER_DIR='/opt/plcnext/.node-red'

PATH=/usr/bin:/usr/sbin:/opt/plcnext/apps/60002172000051/opt/node-v10.15.3-linux-armv7l/bin 

NAME=node-red
DAEMON=/opt/plcnext/appshome/data/60002172000051/bin/node-red
OPTIONS="--max-old-space-size=128"

if [ -n "$USER_DIR" ];  then
    OPTIONS="$OPTIONS --userDir=$USER_DIR"
fi

LOG='/var/log/node-red.log'

PIDFILE=/var/run/node-red.pid

. /etc/init.d/functions

start_daemon () {
        start-stop-daemon --start --background \
        --chuid $USER --name $NAME \
                $START_STOP_OPTIONS --make-pidfile --pidfile $PIDFILE \
        --startas /bin/sh -- -c "$DAEMON $OPTIONS >> $LOG 2>&1"
    echo "Logging to "$LOG
}

case "$1" in
        start)
             echo "Starting daemon" "$NAME"
             start_daemon
        ;;
        stop)
             echo "Stopping daemon" "$NAME"
             start-stop-daemon --stop \
             --user $USER \
             --name $NAME --pidfile $PIDFILE --retry 30 \
             --oknodo
        ;;
        restart)
         $0 stop
         sleep 5
         $0 start
    ;;

    status)
             status "$DAEMON" "$NAME"
             exit $?
        ;;

        *)
             echo "Usage: $0 {start|stop|restart}"
             exit 1
esac
exit 0

4) Execute the two commands bellow:

root@axcf2152:/etc/init.d# sudo chmod 755 start_nodered
root@axcf2152:/etc/init.d# sudo update-rc.d start_nodered defaults 99

5) Restart the PLC and check if Node-RED has started.

Note: