Skip to content

Instantly share code, notes, and snippets.

@mtsoleimani
Created December 18, 2018 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtsoleimani/0c35026327c184f3fd596517368c42e1 to your computer and use it in GitHub Desktop.
Save mtsoleimani/0c35026327c184f3fd596517368c42e1 to your computer and use it in GitHub Desktop.
Init.d and Start Script for Nodejs based service. It uses pid file and checks process if exists
#!/bin/sh
# init.d script with LSB support.
### BEGIN INIT INFO
# Provides: NODEJS_APP_NAME
# Required-Start: $network $local_fs $remote_fs $syslog
# Required-Stop:
# Should-Start: $named
# Should-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description:
# Description:
### END INIT INFO
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
SERVICE_NAME="MY SERVICE NAME"
MAIN_FILE="PATH TO JS FILE"
PID_PATH_NAME="PATH TO PID FILE"
start_it() {
export NODE_ENV=production
echo "starting $SERVICE_NAME ..."
if [ ! -f $PID_PATH_NAME ]; then
nohup nodejs $MAIN_FILE /tmp 2>> /dev/null >> /dev/null &
echo $! > $PID_PATH_NAME
echo "$SERVICE_NAME started ..."
else
PID=$(cat $PID_PATH_NAME);
if ps -p $PID > /dev/null
then
echo "$SERVICE_NAME is already running ..."
else
nohup nodejs $MAIN_FILE /tmp 2>> /dev/null >> /dev/null &
echo $! > $PID_PATH_NAME
echo "$SERVICE_NAME started ..."
fi
fi
}
stop_it() {
if [ -f $PID_PATH_NAME ]; then
PID=$(cat $PID_PATH_NAME);
echo "$SERVICE_NAME stoping ..."
kill $PID;
echo "$SERVICE_NAME stopped ..."
rm $PID_PATH_NAME
else
echo "$SERVICE_NAME is not running ..."
fi
}
restart_it() {
if [ -f $PID_PATH_NAME ]; then
stop_it
start_it
else
echo "$SERVICE_NAME is not running ..."
fi
}
case "$1" in
start)
start_it
;;
stop)
stop_it
;;
restart)
restart_it
;;
*)
N=/etc/init.d/$NAME
echo "Usage: $N {start|stop|restart}" >&2
exit 1
;;
esac
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment