Spring Boot App as Unix/Linux Service

When we run and deploy our spring boot application in Linux or Unix box as jar either we use screen (Can be downloaded from YUM) or nohup(to run the program in the background), both have its pros and cons.

Particularly they both have one thing in common, once the system gets restart both will stop and there is no way you can start them automatically.

To resolve such problems and we can run our spring boot Jar as an Operating System service just like we use

$service httpd start
$service httpd stop

Step 1: Package you jar

$mvn clean package

Step 2 : create a user to run deamon process deamon on Linux/Unix envoirnment.

We will use Systemd configuration file.

First, we will create the user with the password to run the process

$ sudo useradd mjrunner 
$ sudo passwd mjrunner

It will ask you for a password, please enter the password

Then give the permissions to JAR accordingly

$ chown mjrunner:mjrunner mjBoot.jar
$ chmod 500 mjBoot.jar

Note: I am creating a new user to increase security, we can use existing user also.

Step 3: Configure daemon using Systemd
We have to create a script with the name “your-app.service”
vi your-app.service
and put it in “/etc/systemd/system”

paste these contents in a created file

[Unit]
Description=A Spring Boot application
After=syslog.target

[Service]
User=mjrunner
ExecStart=/path/to/mjBoot.jar SuccessExitStatus=143 

[Install] 
WantedBy=multi-user.target

Step 4: Now enable the service file.

$systemctl daemon-reload
$systemctl enable <servicename>.service

 

Happy Learning !!

Leave a comment