Sutthirak

Jul 13, 2015

Normally, if we want to start application as service. we can do it by creating a script in this path

/etc/init.d

Let's say, I would like to start my Java application. I will write a script like this.

#! /bin/sh

NAME="Example"
DESC="Do somethng"
PIDFILE="/var/run/${NAME}.pid"
LOGFILE="/var/log/${NAME}.log"
DAEMON="/usr/bin/java"
DAEMON_OPTS=" -jar /home/sutthirak/example/build/example.jar"

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

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

When the script above is started. it will execute jar file from this path and start it as a background. After this you I have to make this file executable with this command

chmod +x /etc/init.d/name -v

Then I can start Example application with this

sudo service example start

For writing a script. I have created a project for doing that and named it that Bundit

https://github.com/sutthirak/bundit

After installation is successful. You can use Bundit for writing a script like we did it manually above with given parameter similar this

Enter your service name : Example
Enter your service description : just and example application
Enter full path of application : /usr/bin/java
Enter your application parameter : -jar /home/sutthirak/example/build/example.jar

Bundit will write a script file in the same path that you run this application. you can copy this file to /etc/init.d and give execution permission. Then you can start it as a service as usual.