Skip to content

Instantly share code, notes, and snippets.

@lowol
Created August 1, 2012 04:19
Show Gist options
  • Save lowol/3223614 to your computer and use it in GitHub Desktop.
Save lowol/3223614 to your computer and use it in GitHub Desktop.
init.d script for node.js
#!/bin/bash
#
# nodejs - Startup script for node.js server
# /etc/init.d/app1
#
# chkconfig: 35 99 99
# description: Node.js node /apps/app1/server.js
rootdir="/var/www/apps/app1"
server="$rootdir/server.js"
logfile="/var/log/apps/app1.log"
user="www"
nodejs=${NODEJS-/usr/local/bin/node}
script="$(basename $0)"
lockfile="/var/lock/subsys/$script"
. /etc/rc.d/init.d/functions
ulimit -n 12000
RETVAL=0
su "$user" -c "touch $logfile"
do_start()
{
if [ ! -f "$lockfile" ] ; then
date +"%Y-%m-%d %T Starting $server" >> $logfile
echo -n $"Starting $server: "
#runuser -l "$user" -c "nohup $nodejs $server >> $logfile &" && echo_success || echo_failure
runuser -l "$user" -c "NODE_ENV=production $nodejs $server 'production' >> $logfile &" && echo_success || echo_failure
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && touch "$lockfile"
else
echo "$server is locked."
RETVAL=1
fi
}
do_stop()
{
date +"%Y-%m-%d %T Stopping $server" >> $logfile
echo -n $"Stopping $server: "
pid=`ps -aefw | grep "$nodejs $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 "$lockfile"
if [ "$pid" = "" -a -f "$lockfile" ]; then
rm -f "$lockfile"
echo "Removed lockfile ( $lockfile )"
fi
}
do_status()
{
pid=`ps -aefw | grep "$nodejs $server" | grep -v " grep " | awk '{print $2}'`
if [ "$pid" != "" ]; then
echo "$nodejs $server (pid $pid) is running..."
else
echo "$nodejs $server is stopped"
fi
}
case "$1" in
start)
do_start
;;
stop)
do_stop
;;
status)
do_status
;;
restart)
do_stop
do_start
RETVAL=$?
;;
*)
echo "Usage: $0 {start|stop|status|restart}"
RETVAL=1
esac
exit $RETVAL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment