Linux

Running Spring Boot Apps with systemd

Running Spring Boot Apps with systemd

Spring Boot and systemd go hand in hand to make running and controlling apps easy and efficient.

Basic Unit File

A systemd service is described using a unit file. Start by creating a unit file named my-awesome-service.service with the following contents and locate it in the /etc/systemd/system directory. From this point on, we can refer to our service as my-awesome-service when issuing systemd commands. Feel free to name it whatever you want though and make sure you point your service to your actual app.

[Unit]
Description=My Awesome Service
Requires=network.target eureka-server.service config-server.service
After=network.target

[Service]
User=myuser
Group=mygroup
Type=simple
ExecStart=/usr/java/latest/bin/java -jar /srv/spring/my-awesome-service-1.0.0.jar
RestartSec=10
Restart=on-failure

[Install]
WantedBy=multi-user.target

Without going into too much detail about systemd, suffice it to say you need at least the [Unit] section to describe the service and its dependencies. The [Service] section to tell systemd how to start the service. Finally the [Install] section in order to enable the service to start at system boot.

Many additional settings exist that are beyond the scope of this tutorial. You can view this systemd reference for more details.

Controlling the Service with systemd

Starting the service is as easy as issuing the following command.

systemctl start my-awesome-service

Restarting the service.

systemctl restart my-awesome-service

Stopping the service.

systemctl stop my-awesome-service

This command can be issued to tell systemd to start the service at system boot.

systemctl enable my-awesome-service

Logging

One of the things I like about running Spring Boot apps with systemd is I can worry even less about capturing the log output. In the past I would capture the logs in a log file. Using systemd, there is a built in logging journal where all services are logged. If I want to see the log output of a service, I simply issue the following command.

journalctl -f -u my-awesome-service

The -f option tells journalctl to continue outputting entries that are added to the log. It’s identical to using the -f option on the tail command. The -u option is a filter that allows me to only see the log entries for the service name specified. Without this option, I would see the log output of all services currently running on the system.

Conclusion

In this short post, I showed you how you can quickly setup a Spring Boot app as a system service using systemd. If you have any suggestions, feel free to leave a comment below.

Posted by Patrick Grimard in Linux, 0 comments