CentOS init script for the ghost blogging platform
There are actually 4 ways to automatically start ghost automatically.
Some prefer “forever”, take a look here http://blog.nodejitsu.com/keep-a-nodejs-server-up-with-forever/
Other prefer “upstart”, guide here http://www.howtoinstallghost.com/how-to-start-ghost-as-a-service-on-linux/
Another one is “pm2”, http://www.allaboutghost.com/keep-ghost-running-with-pm2/
But I prefer setting up an init script for Linux and in this case CentOS 6.
Here is the Code I’ve used. You should put it in a new file here: /etc/init.d/ghost
#!/bin/sh
#
# ghost - this script starts the ghost blogging package
#
# chkconfig: - 95 20
# description: ghost is a blogging platform built using javascript \
# and running on nodejs
#
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ “$NETWORKING” = “no” ] && exit 0
home=”/var/www/georgemastro.com/web/”
exec=”/usr/local/bin/node index.js >> /var/www/georgemastro.com/log/ghost.log &”
prog=”ghost”
[ -e /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog
lockfile=/var/lock/subsys/$prog
start() {
#[ -x $exec ] || exit 5
echo -n $”Starting $prog: ”
# if not running, start it up here, usually something like “daemon $exec”
export NODE_ENV=production
cd $home
daemon –user=root $exec
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval
}
stop() {
echo -n $”Stopping $prog: ”
# stop it here, often “killproc $prog”
pid=`ps -u $prog -fw | grep $prog | 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
return $retval
}
restart() {
stop
start
}
my_status() {
local base pid lock_file=
base=${1##*/}
# get pid
pid=`ps -u $prog -fw | grep $prog | grep -v ” grep ” | awk ‘{print $2}’`
if [ -z “${lock_file}” ]; then
lock_file=${base}
fi
# See if we have no PID and /var/lock/subsys/${lock_file} exists
if [[ -z “$pid” && -f /var/lock/subsys/${lock_file} ]]; then
echo $”${base} dead but subsys locked”
return 2
fi
if [ -z “$pid” ]; then
echo $”${base} is stopped”
return 3
fi
if [ -n “$pid” ]; then
echo $”${base} (pid $pid) is running…”
return 0
fi
}
rh_status() {
# run checks to determine if the service is running or use generic status
my_status $prog
}
rh_status_q() {
rh_status >/dev/null 2>&1
}
case “$1″ in
start)
rh_status_q && exit 0
$1
;;
stop)
rh_status_q || exit 0
$1
;;
restart)
$1
;;
status)
rh_status
;;
*)
echo $”Usage: $0 {start|stop|restart|status}”
exit 2
esac
exit $?
Make sure you give the file proper permissions
chmod 755 /etc/init.d/ghost
Then the only thing you have to do is type
service ghost start
And finally you just have to set this script to run on every reboot of your server.
chkconfig --levels 235 ghost on