Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Shell script to control the start, stop and restart of a node application.
#!/bin/sh
## Script to control the applicaion start and stop
## Note, if the application was started separate to this script,
## then there is a risk that it will be started twice.
## Also note if you plan to use this with systemd, then you need to ensure
## the 'Service' section looks as follows:
## [Service]
## User=theuser
## Group=thegroup
## Type=oneshot
## Environment=ENV=production
## Environment=NODE_ENV=production
## WorkingDirectory=/home/theuser/myapp
## ExecStart=/home/theuser/myapp/scripts/appctl.sh start
## ExecStop=/home/theuser/myapp/appctl.sh stop
## RemainAfterExit=true
scripts_dir=`dirname $0`
cd "${scripts_dir}/"..
appname="my-app-name"
pidfile="${PWD}/${appname}.pid"
logfile="${PWD}/${appname}.log"
stop() {
printf "Stopping ${appname} ... "
if [ -f "${pidfile}" ]; then
kill `cat "${pidfile}"`
rm "${pidfile}"
printf "done\n"
else
printf "not running\n"
fi
}
start() {
echo "Starting ${appname}"
if [ -f "${pidfile}" ]; then
if kill -0 $(cat "${pidfile}") 2>/dev/null; then
echo "Error: application is already running"
exit 1
fi
fi
echo "pwd: $PWD"
node lib --label "${appname}" >> "${logfile}" &
echo $! > "${pidfile}"
}
restart () {
echo "Restarting ${appname}:"
stop
start
}
status() {
printf "Status of ${appname} .... "
if [ -f "${pidfile}" ]; then
if kill -0 $(cat "${pidfile}") 2>/dev/null; then
echo "running ($(cat "${pidfile}"))"
exit 0
fi
fi
echo "not running"
}
action=$1
if [ -z ${action} ]; then
echo "required one of: start | stop | restart"
elif [ ${action} = 'restart' ]; then
restart
elif [ ${action} = 'start' ]; then
start
elif [ ${action} = 'stop' ]; then
stop
elif [ ${action} = 'status' ]; then
status
else
echo "unknown action, speficify one of: start, stop, restart or status"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.