Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restart Node.js App with init.d

Tags:

node.js

init.d

I'd like to have an init.d daemon restart my node.js app if it crashes. This script starts/stops my node app. I've had no luck getting it to restart the app if it crashes.

I'm running under CentOS. What am I missing?

#!/bin/sh
. /etc/rc.d/init.d/functions

USER="rmlxadmin"
DAEMON="/usr/bin/nodejs"
ROOT_DIR="/home/rmlxadmin"

SERVER="$ROOT_DIR/my_node_app.js"
LOG_FILE="$ROOT_DIR/app.js.log"

LOCK_FILE="/var/lock/subsys/node-server"

do_start()
{
        if [ ! -f "$LOCK_FILE" ] ; then
                echo -n $"Starting $SERVER: "
                runuser -l "$USER" -c "$DAEMON $SERVER >> $LOG_FILE &" && echo_success || echo_failure
                RETVAL=$?
                echo
                [ $RETVAL -eq 0 ] && touch $LOCK_FILE
        else
                echo "$SERVER is locked."
                RETVAL=1
        fi
}
do_stop()
{
        echo -n $"Stopping $SERVER: "
        pid=`ps -aefw | grep "$DAEMON $SERVER" | grep -v " grep " | awk '{print $2}'`
        kill -9 $pid > /dev/null 2>&1 && echo_success || echo_failure
        RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && rm -f $LOCK_FILE
}

case "$1" in
        start)
                do_start
                ;;
        stop)
                do_stop
                ;;
        restart)
                do_stop
                do_start
                ;;
        *)
                echo "Usage: $0 {start|stop|restart}"
                RETVAL=1
esac
exit $RETVAL
like image 730
Sparky1 Avatar asked Jun 06 '12 21:06

Sparky1


People also ask

How do I restart node app?

js Automatic restart Node. js server with nodemon. In this case, if we make any changes to the project then we will have to restart the server by killing it using CTRL+C and then typing the same command again.

How do I restart node server automatically?

If you need to restart your application while Nodemon is running manually. Instead of stopping and restarting your app, you can type rs and then enter. This action will do a quick reboot of your process. If at any point you would like to look at the available CLI options, then you can use -h.


Video Answer


1 Answers

You need to use additional tools like node-supervisor for this case.

  1. Install node-supervisor with npm:

    sudo npm install -g supervisor

  2. Change DAEMON variable in your init.d script to node-supervisor executable: /usr/bin/supervisor. You can check this path using command 'whereis supervisor' in your system (after installation, of course).

Now supervisor will restart your application if it's crash.

like image 66
Vadim Baryshev Avatar answered Sep 17 '22 22:09

Vadim Baryshev