Automatically Restart SpringBoot on Error
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:
- Post photo by Maximilian Weisbecker on Unsplash