<p>I am running a Java Spring Boot boot application on Tomcat in a Kubernetes cluster, I am using a lifecycle hook to shut down Tomcat before the container gets terminated. Also defining a termination grace period of 30 secs.</p>
<p>Expected behaviour: tomcat shuts down gracefully when I kill a pod or delete a deployment.</p>
<p>Actual behaviour: tomcat shuts down abruptly.</p>
<pre><code>lifecycle:
          preStop:
            exec:
              command:
              - /usr/local/tomcat/bin/catalina.sh
</code></pre>
<p>Can anyone help please?</p>

Lakshmi Reddy
<p>In Kubernetes, the <code>preStop</code> hook is executed before the pod is terminated.</p>
<p>For the above use case, tomcat process has to be shutdown gracefully before the pod is terminated when a pod / deployment is deleted.</p>
<p>The following sample pod definition works, by graceful shutdown of the tomcat server, before pod termination.
Note: The container in this definition is <code>FROM tomcat:9.0.19-jre8</code></p>
<pre><code>apiVersion: v1 
kind: Pod 
metadata:
  name: demopod
spec:
  containers:
  - image: demo:web
    name: demo-container
    ports:
    - containerPort: 8080
    lifecycle:
      postStart:
        exec:
          command: [&quot;/bin/sh&quot;, &quot;-c&quot;, &quot;echo Hello from the postStart handler &gt; /usr/share/message&quot;]
      preStop:
        exec:
          command: [&quot;/bin/sh&quot;, &quot;-c&quot;, &quot;echo Stopping server &gt; /usr/share/message1; sleep 10; sh /usr/local/tomcat/bin/catalina.sh stop&quot;]
</code></pre>
<p>In the above definition file, we run three commands (change as per need).</p>
<ol>
<li><p>Write a shutdown message into /usr/share/message1</p>
</li>
<li><p>sleep 10 (Just to give time to view pod / container logs)</p>
</li>
<li><p>Run <code>Catalina.sh stop</code> script to stop the tomcat server.</p>
</li>
</ol>
<p><strong>To Debug:</strong>
For PreStop, if the handler fails, an event is broadcasted, the FailedPreStopHook event. You can see these events by running <code>kubectl describe pod &lt;pod_name&gt;</code></p>
<p>Refer below post for more detailed instructions:
<a href="http://muralitechblog.com/kubernetes-graceful-shutdown-of-pods/" rel="nofollow noreferrer">http://muralitechblog.com/kubernetes-graceful-shutdown-of-pods/</a></p>
<p><strong>Shutdown logs:</strong>
<a href="https://i.stack.imgur.com/xjxqd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xjxqd.png" alt="Valid shutdown logs" /></a></p>
