Containers are all the rage these days and for good reason. They offer a significant leap forward in software development in terms of convenience and environment stability. Although not the only available option for containers, docker has emerged as the de facto. While there is no shortage of articles about getting containers up and running, there doesn’t seem to be much written about gracefully terminating containers.
Assuming that your container has a startup shell script, you’ll need to define a function to handle the SIGTERM
signal issued by the docker engine when stopping the
container. The function should resemble the following example. It is important to exit the function with an exit code of 143
. This signals to the docker engine that
the container exited, as expected.
pid=0
function sigterm_handler() {
if [ $pid -ne 0 ]; then
kill -9 $pid
wait "$pid"
# insert any cleanup code here
fi
exit 143
}
When the docker engine wants to stop a container, it will issue a SIGTERM
signal to the container. In order to gracefully terminate the child process and optionally
perform additional resource cleanup, we’ll need to register the sigterm_handler
function with the SIGTERM
signal. In the following example, an uberjar is forked
as a background process. Once forked, the process identifier of the child process is assigned to the pid
variable.
trap 'kill ${!}; sigterm_handler' SIGTERM
java -jar uber.jar &
pid=${!}
The final step is to wait
for the child process to terminate.
while true
do
tail -f /dev/null & wait ${!}
done