I've read the docs on graceful termination of a pod in Kubernetes but I'm not quite sure how to map my specific use case of shutting down a Java process gracefully.
What I want to do is to run the following bash command as a part of the termination process:
$ kill -SIGTERM `pidof java`
I've tried this:
...
lifecycle:
preStop:
exec:
command: ["kill", "-SIGTERM", "`pidof java`"]
...
But nothing happens but the Java shutdown hook doesn't seem to kick-in when I stop the pod (kubectl stop pod pod-xxx
). I suspect that the pidof java
part of the kill
command doesn't work (but I'm not sure). How would I do this in Kubernetes?
I can't say why your script is not doing anything. Maybe the command is not in the container, maybe you should try with full path (/bin/kill)?
But, kubernetes will send SIGTERM to the application when it does stop, so your script doesn't improve anything. It will wait after that for terminationGracePeriodSeconds and it will do a force kill.
I started a bash shell inside the container and executed my command instead and that turned out to work:
command: ["/bin/bash", "-c", "PID=`pidof java` && kill -SIGTERM $PID && while ps -p $PID > /dev/null; do sleep 1; done;"]
Without /bin/bash
I couldn't get it working.