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+.