Andreas Petersson
Andreas Petersson

Reputation: 16518

shutdown / undeploy tomcat from Servlet

I have an init servlet in Tomcat that loads critical data. Sometimes it is necessary to abort startup on certain errors.

how do i gracefully shutdown the deployed app/ the whole app server without calling System.exit(1)

i want to avoid calling the shutdown servlet via port, since this is not configured in my installation.

there may be tasks that need to be run from listeners on shutdown defined in web.xml

Upvotes: 6

Views: 3832

Answers (2)

Archimedes Trajano
Archimedes Trajano

Reputation: 41790

What I added was a healthcheck probe that would check if the server was still up using a curl I think it can be modified to check if a "flag" file is present as well. I just send a catalina.sh stop command.

If this was a Docker container, you can use the healthcheck probe to let it close itself as well.

Ideally if you can migrate to something like Spring Boot which runs tomcat but terminates it if the Spring Context does not load properly.

Upvotes: 0

matt b
matt b

Reputation: 140061

First of all, you should never ever ever ever call System.exit() from within a servlet container, as there might be other applications running within the same process as yours, and it would be incredibly incorrect to forcibly kill the entire process.

Assuming your "init servlet" implements ServletContextListener, there is no formal way defined in the API/interface to signal to the servlet container "please shut down the app neatly". You could however throw some sort of RuntimeException from the contextInitialized() method, which in most containers (at least Tomcat) will stop the startup of your webapp and leave it in the "stopped" state. However I doubt that Tomcat will continue to call your shutdown listeners.

You might want to rethink your design so that your critical data / shutdown logic is not tied so tightly with the lifecycle of the servlet container.

Upvotes: 7

Related Questions