Tuesday, 26 September 2017

Run application/command as linux service with startup



        This post is about how you can run an application or a custom command as linux service. Here I will use a JAR (java application) to demonstrate the same as I require my java application to run as service with startup. To run java application as service, we need to make some shell script to start stop our command as service. Following are some simple steps and scripts to achieve our goal.


Steps:

(Note: Please set appropriate file permission for scripts, many times it causes problems.)

#1 Service starting script

/usr/local/bin/git_monitor-start.sh
#!/bin/bash

red=`tput setaf 1`
green=`tput setaf 2`
reset=`tput sgr0`

# Here 'git-monitor-0.0.1-SNAPSHOT.jar' is name of my java application

# Logic
# Get pid of already running service by application name
# If application/command is running then display error message that service is already running
# Else main logic to run application

pid=`ps aux | grep git-monitor-0.0.1-SNAPSHOT | grep jar | awk '{print $2}'`

if [ -n "$pid" ]; then
    echo "${red}[NOT OK] Service is already running!${reset}"
else
    cd /home/myuser/git
    nohup java -jar git-monitor-0.0.1-SNAPSHOT.jar &
    echo "${green}[OK] Service is booting now!${reset}"
fi

#2 Service stopping script

/usr/local/bin/git_monitor-stop.sh
#!/bin/bash

red=`tput setaf 1`
green=`tput setaf 2`
reset=`tput sgr0`

# Here 'git-monitor-0.0.1-SNAPSHOT.jar' is name of my java application

# Logic
# Get pid of already running service by application name
# If application/command is running then kill pid and display success message
# Else display error message that service is not running

pid=`ps aux | grep git-monitor-0.0.1-SNAPSHOT | grep jar | awk '{print $2}'`

if [ -n "$pid" ]; then
    kill -9 $pid
    echo "${green}[OK] Service is stopped!${reset}"
else
    echo "${red}[NOT OK] Service is not running!${reset}"
fi


#3 Service script

Create the following script (git-monitor) and put it on /etc/init.d

/etc/init.d/git-monitor
#!/bin/bash

# Use name of start stop script name in cases
# For restart case first use stop script then start script

case $1 in
    start)
        /bin/bash /usr/local/bin/git_monitor-start.sh
    ;;
    stop)
        /bin/bash /usr/local/bin/git_monitor-stop.sh
    ;;
    restart)
        /bin/bash /usr/local/bin/git_monitor-stop.sh
        /bin/bash /usr/local/bin/git_monitor-start.sh
    ;;
esac
exit 0

#4 Service is ready to run

Now we can use service command from command prompt.
$ service git-monitor start

$ service git-monitor stop

$ service git-monitor restart

#5 Start service with system

Put the script to start with the system (using SysV). Just run following command as root that's it:
# update-rc.d git-monitor defaults




Hope this information will help you.
I would really appreciate your feedback, suggestions, requests and ideas.

Thank You.