Automatically Restart SpringBoot on Error

Java Jan 14, 2019

I recently encountered some problems with my SpringBoot application running on a low resource server. The application was not automatically restarted as a result of an OutOfMemoryError.

At this time, I was not notified about this crash. I only received exception messages which occurs within the SpringBoot application (for example an NullPointerException).

I was looking for a solution for that problem. The best solution for me was to use the service functionality. In this article I want to show how to automatically start your SpringBoot application on system startup and restart after a fatal error.

How to use a service?

A service is handled by the linux operating system. For example, your ssh daemon is also using the service functionality.

To create a new service, create a new file (of type .service) in the folder /etc/systemd/system. Change the permission of this file to 0644 and the owner to root:root.

Paste and adjust the following code:

[Unit]
Description=My Spring Boot Application #use your application name

[Service]
User=root #use user with restricted permissions
Type=simple
ExecStart=/usr/bin/java -jar /path/to/jar #change path
Restart=always

[Install]
WantedBy=multi-user.target

This is a simple declaration of a service. You can also add additional properties.

Save this file and execute:

systemctl status YOURSERVICENAME

If this command does not show any errors, you can enable and start your new service:

systemctl enable YOURSERVICENAME
systemctl start YOURSERVICENAME

With this set, your SpringBoot application will automatically restart after an error and also start on system startup.


Please comment below, if you have any questions.

Credits:

Tags

Stefan

Howdy! I'm Stefan and I am the main author of this blog. If you want know more, you can check out the 'About me' page.

Impressum | Data Privacy Policy | Disclaimer
Copyright: The content is copyrighted and may not be reproduced on other websites without permission.