Install a Service on Ubuntu

From KHicks
Jump to: navigation, search

To have a daemon or script run as a service on Ubuntu, follow these steps:

Create init.d script

Create a startup script with filename /etc/init.d/myservice and paste in this text:

NAME=myservice
DESC="Daemon for my great script"
PIDFILE="/var/run/${NAME}.pid"
LOGFILE="/var/log/${NAME}.log"

DAEMON="/usr/bin/php"
DAEMON_OPTS="/path/to/script.php"

START_OPTS="--start --background --make-pidfile --pidfile ${PIDFILE} --exec ${DAEMON} ${DAEMON_OPTS}"
STOP_OPTS="--stop --pidfile ${PIDFILE}"

test -x $DAEMON || exit 0

set -e

case "$1" in
    start)
        echo -n "Starting ${DESC}: "
        start-stop-daemon $START_OPTS >> $LOGFILE
        echo "$NAME."
        ;;
    stop)
        echo -n "Stopping $DESC: "
        start-stop-daemon $STOP_OPTS
        echo "$NAME."
        rm -f $PIDFILE
        ;;
    restart|force-reload)
        echo -n "Restarting $DESC: "
        start-stop-daemon $STOP_OPTS
        sleep 1
        start-stop-daemon $START_OPTS >> $LOGFILE
        echo "$NAME."
        ;;
    *)
        N=/etc/init.d/$NAME
        echo "Usage: $N {start|stop|restart|force-reload}" >&2
        exit 1
        ;;
esac

exit 0

Be sure to change the NAME, DESC, DAEMON, and DAEMON_OPTS to fit your needs.

Set to run on startup

To start this service on system startup, run these commands:

   $ sudo update-rc.d myservice defaults
   $ sudo update-rc.d myservice enable

Remove from startup

To have the script no longer run on startup, delete or rename the /etc/init.d/myservice file and run this command:

   $ sudo update-rc.d myservice remove