Run a Java Application as a Service on Linux

221,299

Solution 1

I wrote another simple wrapper here:

#!/bin/sh
SERVICE_NAME=MyService
PATH_TO_JAR=/usr/local/MyProject/MyJar.jar
PID_PATH_NAME=/tmp/MyService-pid
case $1 in
    start)
        echo "Starting $SERVICE_NAME ..."
        if [ ! -f $PID_PATH_NAME ]; then
            nohup java -jar $PATH_TO_JAR /tmp 2>> /dev/null >> /dev/null &
            echo $! > $PID_PATH_NAME
            echo "$SERVICE_NAME started ..."
        else
            echo "$SERVICE_NAME is already running ..."
        fi
    ;;
    stop)
        if [ -f $PID_PATH_NAME ]; then
            PID=$(cat $PID_PATH_NAME);
            echo "$SERVICE_NAME stoping ..."
            kill $PID;
            echo "$SERVICE_NAME stopped ..."
            rm $PID_PATH_NAME
        else
            echo "$SERVICE_NAME is not running ..."
        fi
    ;;
    restart)
        if [ -f $PID_PATH_NAME ]; then
            PID=$(cat $PID_PATH_NAME);
            echo "$SERVICE_NAME stopping ...";
            kill $PID;
            echo "$SERVICE_NAME stopped ...";
            rm $PID_PATH_NAME
            echo "$SERVICE_NAME starting ..."
            nohup java -jar $PATH_TO_JAR /tmp 2>> /dev/null >> /dev/null &
            echo $! > $PID_PATH_NAME
            echo "$SERVICE_NAME started ..."
        else
            echo "$SERVICE_NAME is not running ..."
        fi
    ;;
esac 

You can follow a full tutorial for init.d here and for systemd (ubuntu 16+) here

If you need the output log replace the 2

nohup java -jar $PATH_TO_JAR /tmp 2>> /dev/null >> /dev/null &

lines for

nohup java -jar $PATH_TO_JAR >> myService.out 2>&1&

Solution 2

A simple solution is to create a script start.sh that runs Java through nohup and then stores the PID to a file:

nohup java -jar myapplication.jar > log.txt 2> errors.txt < /dev/null &
PID=$!
echo $PID > pid.txt

Then your stop script stop.sh would read the PID from the file and kill the application:

PID=$(cat pid.txt)
kill $PID

Of course I've left out some details, like checking whether the process exists and removing pid.txt if you're done.

Solution 3

Linux service init script are stored into /etc/init.d. You can copy and customize /etc/init.d/skeleton file, and then call

service [yourservice] start|stop|restart

see http://www.ralfebert.de/blog/java/debian_daemon/. Its for Debian (so, Ubuntu as well) but fit more distribution.

Solution 4

Maybe not the best dev-ops solution, but good for the general use of a server for a lan party or similar.

Use screen to run your server in and then detach before logging out, this will keep the process running, you can then re-attach at any point.

Workflow:

Start a screen: screen

Start your server: java -jar minecraft-server.jar

Detach by pressing: Ctl-a, d

Re-attach: screen -r

More info here: https://www.gnu.org/software/screen/manual/screen.html

Solution 5

Another alternative, which is also quite popular is the Java Service Wrapper. This is also quite popular around the OSS community.

Share:
221,299
dreza
Author by

dreza

Average Joe programmer who is always looking to improve, learn and where possible offer help to those who want it.

Updated on February 21, 2020

Comments

  • dreza
    dreza about 4 years

    I have written a Java server application that runs on a standard virtual hosted Linux solution. The application runs all the time listening for socket connections and creating new handlers for them. It is a server side implementation to a client-server application.

    The way I start it is by including it in the start up rc.local script of the server. However once started I do not know how to access it to stop it and if I want to install an update, so I have to restart the server in order to restart the application.

    On a windows PC, for this type of application I might create a windows service and then I can stop and start it as I want. Is there anything like that on a Linux box so that if I start this application I can stop it and restart it without doing a complete restart of the server.

    My application is called WebServer.exe. It is started on server startup by including it in my rc.local as such:

    java -jar /var/www/vhosts/myweb.com/phpserv/WebServer.jar &
    

    I am a bit of a noob at Linux so any example would be appreciated with any posts. However I do have SSH, and full FTP access to the box to install any updates as well as access to a Plesk panel.

  • dreza
    dreza almost 12 years
    Looks promising. I will be taking a closer look into this. cheers
  • Denys Séguret
    Denys Séguret almost 12 years
    I'm not very good in linux but doesn't pkill nameofprocess do about the same thing ?
  • Scuba Steve
    Scuba Steve over 10 years
    Question: Wouldn't the kill $PID command cause the process to be killed without finishing? I'm writing a server program that interfaces with a database, and I would want all currently running threads to finish before the program exits, so as to ensure that the program doesn't die in the middle of a write to the DB or something.
  • dreza
    dreza over 10 years
    @PbxMan thanks for this. I might give it a go and see how we get on. Cheers.
  • rjohnston
    rjohnston almost 10 years
    @scuba-steve sort of. kill will send the TERM signal, which will invoke any shutdown hooks that are in place, so use them to end your process gracefully. They won't execute if the process gets a kill signal (i.e., kill -9). The OS may interrupt your shutdown hooks if they're taking too long to complete, so keep them succinct
  • Jack Daniel
    Jack Daniel over 8 years
    but how I can run this file? where I must put it?
  • Andre
    Andre over 8 years
    @JackDaniel on debian-based distros, like debian itself and ubuntu, you can add that script to /etc/init.d. Then you can invoke it like this: /etc/init.d/MyService start. And you can make it start automatically by running update-rc.d MyService defaults .
  • giorgio79
    giorgio79 about 8 years
    PbxMan thx! Could we add a status query that would return whether service is running, stopped etc. @Andre any tips for Centos? :)
  • wired00
    wired00 almost 8 years
    supervisord is great, for those who don't know, it allows monitoring services (which must be foreground - not daemonized), it will then auto restart services (and can email alerts when restarts occur via plugins)
  • matbrgz
    matbrgz over 7 years
    But the kill $PID approach does not give the Java program any chance to shut down properly, does it?
  • PbxMan
    PbxMan over 7 years
    @ThorbjørnRavnAndersen That would depend on your java program. If you cannot kill your java program Check out stackoverflow.com/questions/2541597/…. I would delete the MyService-pid instead of the kill and have deamon thread in the Java part that checks if it exists.
  • M. Schena
    M. Schena about 7 years
    Where will the ouput file of the jar be? how can i configure it's name?
  • V-Q-A NGUYEN
    V-Q-A NGUYEN almost 7 years
    I have the same question as M. Schena, where is the output file (log) ? and how can i rename the name ?
  • HomeIsWhereThePcIs
    HomeIsWhereThePcIs over 5 years
    For some reason this always reports service is already started. It appears that pgrep is returning 0 when run from inside the script, but if I enter the pgrep command manually it returns 1.
  • HomeIsWhereThePcIs
    HomeIsWhereThePcIs over 5 years
    The reason why pgrep thinks the service is running is because it detects "/bin/sh /sbin/service MATH start" and "/bin/bash /etc/init.d/MATH start" and returns 0
  • java acm
    java acm over 5 years
    Thank you so much , nice and worked , but how to add status section ?