Spring Boot Application as Service in Linux


To run a Spring Boot application as a background service on Linux, you can use systemd, which is a commonly used service manager in Linux distributions. Here’s a step-by-step guide to setting up your Spring Boot application as a background service:

Create a service unit file:

Open a text editor and create a new file with a .service extension, such as invoiceapp.service.

Add the following content to the file, adjusting the values as necessary:

[Unit]
Description=Your Spring Boot Application

[Service]
User=yourusername
ExecStart=/usr/bin/java -jar /path/to/invoiceapp.jar
WorkingDirectory=/path/to/invoiceapp
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=invoiceapp
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target
  • Set Description to a brief description of your application.
  • Replace yourusername with the username under which the application should run.
  • Adjust /usr/bin/java and /path/to/invoiceapp.jar to the actual path of the Java executable and your JAR file, respectively.
  • Set /path/to/invoiceapp to the directory where your Spring Boot application should be executed from.
  • Restart=always ensures that the service is automatically restarted if it stops for any reason.
  • StandardOutput and StandardError specify that the application’s output and error messages should be logged to syslog.
  • SyslogIdentifier sets the identifier for log messages in syslog.
  • SuccessExitStatus=143 ensures that the service is considered successfully stopped when it receives a termination signal (SIGTERM).

Save the service unit file.

Move the service unit file to the appropriate location:

Run the following command to move the service unit file to the systemd directory:

sudo mv invoiceapp.service /etc/systemd/system/

Update systemd to recognize the new service:

Run the following command to reload systemd and make it aware of the new service unit file:

sudo systemctl daemon-reload

Enable and start the service:

Run the following command to enable the service to start on boot:

sudo systemctl enable invoiceapp

Run the following command to start the service:

sudo systemctl start invoiceapp

Verify the service status:

Run the following command to check the status of the service:

sudo systemctl status invoiceapp 

The output will display the current status of the service, indicating whether it is running or not.

At this point, your Spring Boot application should be running as a background service. You can also use other systemctl commands to manage the service, such as stop, restart, or disable.

Ensure that the Java environment is properly set up on your Linux system and that the required dependencies for your Spring Boot application are installed.

Note that modifying system-wide configuration files requires administrative privileges. Ensure you have the necessary permissions or consult your system administrator if needed.

Thanks for Reading…