Automatically Restart SpringBoot on Error

Java Jan 14, 2019
The examples below will edit the configuration on a native host. To keep changes documented, persistent and reproducible, use a configuration management tool.

The explained application is running on a native host. Depending on your setup, you might benefit from a containerized environment.

I recently encountered some problems with a SpringBoot application running on a native 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.

I was looking for a solution for that problem. The best solution for 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 critical error.

How to use a system 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.

Paste and adjust the following code:

[Unit]
Description=Application #use your application name

[Service]
User=root #use user with restricted permissions
Type=simple
ExecStart=/usr/bin/java -jar /path/to/jar #change java path and application 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.


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.