I’m working on a legacy project today. There is a Spring Boot project deployed on a physical server on the customer’s intranet, and recently, for some reason, the server has been rebooting frequently. It’s a pain to manually start the Spring Boot project after each reboot, so I’m going to configure it to turn on a self-starting service.
This was done with the help of systemd
. It provides a solution for system startup and management. By convention, in Linux, d
usually means a daemon, such as httpd
.
The easiest way to get a Spring Boot service to start with the system is to configure it as a system service via systemd
.
First, you need to write three scripts to start, stop, and restart the Spring Boot application, and our program JAR package is /path/to/xxx.jar
.
start.sh
stop.sh
restart.sh
|
|
The above three scripts.
start.sh
is the start script, which provides the path to Java, executes the start command of the JAR file, and outputs the information.stop.sh
is a stop script, which finds the PID of the corresponding process of the program by using theps
command, if it doesn’t exist, the program is not running, so don’t do anything, if it exists, then kill it with thekill
command.restart.sh
is a restart script, which is a combination of the above two, to terminate the program first, and then start it.
With these three scripts in the /path/to/bin/
directory, we now configure the system service (assuming the service is named xxx
).
In the /usr/lib/systemd/system/
directory, create the xxx.service
file with the following contents.
In this file, there are three sections.
- Unit block contains the configuration describing the content and the startup order. After indicates that it starts after these services are started.
- The Service block configures the startup behavior, using the three previous script files as the scripts for starting, terminating, and restarting the services, respectively.
- Install block configures how to install this configuration file,
WantedBy=multi-user.target
means the Target where this service is located ismulti-user.target
.
With this configuration file, the following commands can be used to operate this service.
To have the service start with the system, simply execute the following command.
|
|
To unboot with the system, use the following command.
|
|