Java application as Linux Service in 4 steps

If you are reading this post then, probably, you need to execute your java app as a Linux service.

This can be done in 4 really easy steps

  • Create the service
  • create a bash script
  • give execution permission to the bash file
  • enable and start your brand new service

Step 1: create the system service

sudo nano /etc/systemd/system/MyFantasticJavaApp.service

it will open the nano editor. Add the following, changing the working directory and the User values based on your convenience

                                                                                                 
 [Unit]
 Description=good old Java application
 [Service]
 User=root  
 # The configuration file application.properties should be here:
 # change this with your workspace
 WorkingDirectory=/usr/local/javaproject/

 #path to executable.
 #executable is a bash script which calls jar file
 ExecStart=/usr/local/javaproject/myBashFile
 SuccessExitStatus=143
 TimeoutStopSec=10
 Restart=on-failure
 RestartSec=5
 [Install]
 WantedBy=multi-user.target

save the file (Ctrl-X, select Y(es) and press enter)

Step 2: create the bash script

Now let’s create a script which will basically call our jar/war file.

This file has to be the one specified in previous service file (what we call in ExecStart value). So, let’s write:

sudo nano /usr/local/javaproject/myBashFile

it will open (again) the nano editor. Add the following 2(two) lines, changing the port and the path to your jar/war file

#!/bin/sh
 sudo /usr/bin/java -Dserver.port=7080  -jar /usr/local/javaproject/MyFantasticJavaApp.jar

save the file (Ctrl-X, select Y(es) and press enter)

Step 3: give execution permission to the basch script

this is the simpler step. Just write this, changing the file and his path:

sudo chmod u+x /usr/local/javaproject/myBashFile

Step 4, almost there: let’s play the new service

sudo systemctl daemon-reload
sudo systemctl enable MyFantasticJavaApp.service
sudo systemctl start MyFantasticJavaApp

Et voila! Do not thank me!

0 Comments

Add Your Comment: