After springboot starts, its process id needs to be recorded and written to a disk file.

The bash script can easily stop the program by PID.

ApplicationPidFileWriter

A listener provided by springboot is very simple. Just add the listener instance to the SpringApplication before starting the springboot application.

1
2
3
SpringApplication springApplication = new SpringApplication(MyApplication.class);
springApplication.addListeners(new ApplicationPidFileWriter());  // Pid Listener
springApplication.run(args);

Configure the write file for the process ID.

1
2
3
4
spring:
  pid:
    file: /var/run/myapp.pid # Location of the PID file to write (if ApplicationPidFileWriter is used).
    fail-on-write-error: true # Fails if ApplicationPidFileWriter is used but it cannot write the PID file.

Special shell variables in Linux $!

The special variable $! , is the pid of the last running background Process of the Shell.

So you can write the PID at the start of the application by using the following command.

1
nohup java -jar app.jar > app.log 2 >&1 & echo $! > /var/run/myapp.pid

Reference https://springboot.io/t/topic/1026