Skip to content

Instantly share code, notes, and snippets.

@nherment
Created May 11, 2017 12:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nherment/6c480bdab00556f259948c95481c29c7 to your computer and use it in GitHub Desktop.
Save nherment/6c480bdab00556f259948c95481c29c7 to your computer and use it in GitHub Desktop.
init.d nodejs app script
#!/bin/sh
USER="nherment"
NODE_ENV="production"
PORT="5000"
APP_DIR="/opt/node-app/latest"
NODE_APP="server.js"
KWARGS=""
APP_NAME="node-app"
PID_DIR="/var/run"
PID_FILE="$PID_DIR/$APP_NAME.pid"
NODE_EXEC="node"
###############
# REDHAT chkconfig header
# chkconfig: - 58 74
# description: this is the script for starting a node app on boot.
### BEGIN INIT INFO
# Provides: node
# Required-Start: $network $remote_fs $local_fs
# Required-Stop: $network $remote_fs $local_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: start and stop node
# Description: Node process for app
### END INIT INFO
###############
USAGE="Usage: $0 {start|stop|restart|status}"
pid_file_exists() {
[ -f "$PID_FILE" ]
}
get_pid() {
echo "$(cat "$PID_FILE")"
}
is_running() {
PID=$(get_pid)
! [ -z "$(ps aux | awk '{print $2}' | grep "^$PID$")" ]
}
start_it() {
mkdir -p "$PID_DIR"
chown $USER:$USER "$PID_DIR"
echo "Starting $APP_NAME ..."
su -l $USER -c ". \$HOME/.nvm/nvm.sh && cd $APP_DIR && PORT=$PORT NODE_ENV=$NODE_ENV $NODE_EXEC $APP_DIR/$NODE_APP > \$HOME/logs 2>&1 & echo \$! > $PID_FILE"
echo "$APP_NAME started with pid $(get_pid)"
}
stop_process() {
PID=$(get_pid)
echo "Killing process $PID"
pkill -P $PID
}
remove_pid_file() {
echo "Removing pid file"
rm -f "$PID_FILE"
}
start_app() {
if pid_file_exists
then
if is_running
then
PID=$(get_pid)
echo "$APP_NAME already running with pid $PID"
exit 1
else
echo "$APP_NAME stopped, but pid file exists"
echo "Forcing start anyways"
remove_pid_file
start_it
fi
else
start_it
fi
}
stop_app() {
if pid_file_exists
then
if is_running
then
echo "Stopping $APP_NAME ..."
stop_process
remove_pid_file
echo "$APP_NAME stopped"
else
echo "$APP_NAME already stopped, but pid file exists"
echo "Forcing stop anyways ..."
remove_pid_file
echo "$APP_NAME stopped"
fi
else
echo "$APP_NAME already stopped, pid file does not exist"
exit 1
fi
}
status_app() {
if pid_file_exists
then
if is_running
then
PID=$(get_pid)
echo "$APP_NAME running with pid $PID"
else
echo "$APP_NAME stopped, but pid file exists"
fi
else
echo "$APP_NAME stopped"
fi
}
case "$2" in
"")
;;
*)
echo $USAGE
exit 1
;;
esac
case "$1" in
start)
start_app
;;
stop)
stop_app
;;
restart)
stop_app
start_app
;;
status)
status_app
;;
*)
echo $USAGE
exit 1
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment