HomeJavaHow to Run Java App as a Service in Ubuntu?

How to Run Java App as a Service in Ubuntu?

You have a java executable file (JAR file) which is needed to be executed every timeĀ whenever your Ubuntu system starts. One way to achieve this is by creating the CRON job or another way is to run it as a service.Ā Ubuntu has a built-in mechanism to create custom services, enabling them to get started at system boot time and start/stop them as a service. In this journal entry, we will be sharing a very simple and an elegant way to create a service wrapper to run java app as a service in Ubuntu.

Run Java App as a Service in Ubuntu

Step #1: Create a Service File

sudo vim /etc/systemd/system/java-webapp.service

Copy and Paste the following into newly created service file: /etc/systemd/system/java-webapp.service


[Unit]
Description=Webapp Java REST Service
[Service]
User=ubuntu
# The configuration file application.properties should be here:

#change this to your workspace
WorkingDirectory=/home/ubuntu/project-ws

#path to executable.
#executable is a bash script which calls jar
fileExecStart=/home/ubuntu/project-ws/java-webapp

SuccessExitStatus=143
TimeoutStopSec=10
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

Step #2: Create a Bash Script to Call your Service

The bash script to call your JAR file: java-webapp


#!/bin/sh
sudo /usr/bin/java -jar java-webapp-1.0-SNAPSHOT.jar server config.yml

Don’t forget to give your script execute permission:Ā sudo chmod u+x my-webapp

Step #3: Start the Service


sudo systemctl daemon-reload
sudo systemctl enable java-webapp.service
sudo systemctl start java-webapp
sudo systemctl status java-webapp

Step #4: Setup Logging

Very first step is to run the following command: sudo journalctl --unit=java-webapp.

To see the real-timeĀ logs use the -f option.

You can also view only specified number of lines using the -n <# of lines> option.


sudoĀ journalctlĀ -f -n 100 --unit=java-webapp

Stop the Service

To stop the service at any point of time simply execute the following command in the terminal:


sudo systemctlĀ stop java-webapp

That’s all you need to know to run your java app as a service in Ubuntu.Ā If you like this journal entry and want some more entries like these then please stay tuned and connected byĀ subscribing to our newsletterĀ or you can join us on our social platforms ā€“Ā facebook,Ā twitter,Ā google+.

 

RELATED ARTICLES

Most Popular