They are many ways to shutdown a spring application. One is to call close() on the ApplicationContext
:
ApplicationContext ctx =
SpringApplication.run(HelloWorldApplication.class, args);
// ...
ctx.close()
Your question suggest you want to close your application by doing Ctrl+C
, that is frequently used to terminate a command. In this case...
Use endpoints.shutdown.enabled=true
is not the best recipe. It means you expose an end-point to terminate your application. So, depending on your use case and your environment, you will have to secure it...
A Spring Application Context may have register a shutdown hook with the JVM runtime. See ApplicationContext documentation.
Spring Boot configure this shutdown hook automatically since version 2.3 (see jihor's answer). You may need to register some @PreDestroy methods that will be executed during the graceful shutdown (see Michal's answer).
Ctrl+C
should work very well in your case. I assume your issue is caused by the ampersand (&) More explanation:
On Ctrl+C
, your shell sends an INT
signal to the foreground application. It means "please interrupt your execution". The application can trap this signal and do cleanup before its termination (the hook registered by Spring), or simply ignore it (bad).
nohup
is command that execute the following program with a trap to ignore the HUP signal. HUP is used to terminate program when you hang up (close your ssh connexion for example). Moreover it redirects outputs to avoid that your program blocks on a vanished TTY. nohup
does NOT ignore INT signal. So it does NOT prevent Ctrl+C
to work.
I assume your issue is caused by the ampersand (&), not by nohup. Ctrl+C
sends a signal to the foreground processes. The ampersand causes your application to be run in background. One solution: do
kill -INT pid
Use kill -9
or kill -KILL
is bad because the application (here the JVM) cannot trap it to terminate gracefully.
Another solution is to bring back your application in foreground. Then Ctrl+C
will work. Have a look on Bash Job control, more precisely on fg
.
kill -SIGTERM <PID>
should do the trick. – M. Deinum