How to deploy a Spring Boot app on Linux

Last updated : Jul 30, 2023 12:00 AM

1. Overview

In this article, we will take a look at how to deploy a Spring Boot application as a service in a Linux system. By deploying the application as a service, we enable the ability to re-start the Spring application on system reboot.

2. Setting up and Building the Spring Boot Application

We have to follow a few steps to make the Spring Boot app executable. First, set the Spring Boot app's packaging to jar by changing the <packaging> tag to jar in pom.xml.
<packaging>jar</packaging>

Next, we need to make the Spring Boot jar executable by setting executable to true in pom.xml. This will enable Linux to find the main class entry in the Spring Boot application to invoke SpringApplication.run(Application.class, args) by reading the Manifest file.

<configuration> 
   <executable>true</executable> 
</configuration>

3. Build the Spring Boot application

Build the application by running mvn clean package.
This will create the jar file springboot.jar (file name depends on your artifactId and version) in the target folder.
Place this jar file in your Linux system. For this tutorial, we will assume the path to springboot.jar as /software/api/springboot.jar.

4. Setting up Linux service

4.1 Create a service file

Create a file named springboot.service (you can name it anything you like, but the file should have .service file extension) /etc/systemd/system/springboot.service
Include the below code in the springboot.service file.

[Unit]
Description=Springboot port 8090
After=syslog.target

[Service]
User=username
ExecStart=/software/java/openjdk17/jdk-17.0.1/bin/java -jar /software/tomcat/springboot.jar --server.port=8090
SuccessExitStatus=143
TimeoutStopSec=10
Restart=on-failure
RestartSec=5

[Install] 
WantedBy=multi-user.target

Make sure to set the correct path to ExecStart, your java installation directory, and the directory that contains the springboot.jar file. --server.port=8090 is optional and allows you to specify the server port at runtime. You can ignore it if you like.

4.2 Create a symlink

The next step is to create a symlink for the service
sudo ln -s /software/tomcat/springboot.jar /etc/init.d/springboot
You can delete an existing symlink with
rm /etc/init.d/springboot

4.3 Update systemd

Next, update the systemd by running
systemctl daemon-reload
This will notify systemd about the new service

4.4 Enable the service

Now, enable service to run on system boot
systemctl enable springboot.service

4.5 Start the service

Finally, start the service by running
systemctl start springboot
Additionally, you can use the below commands on the service you created.
systemctl stop springboot systemctl restart springboot systemctl status springboot

Lance

By: Lance

Hi, I'm Lance Raney, a dedicated Fullstack Developer based in Oklahoma with over 15 years of exp

Read more...