Signals Handling Inside Docker Container

Table of contents
Reading Time: 2 minutes

Linux supports both POSIX reliable signals and POSIX real-time signals.

Signal Dispositions: Each signal has a current disposition, which determines how the process behaves when it is delivered the signal.

We have different types of signals in Linux

The specified default disposition of few signals are below:

Term : default action is to terminate the process.
Ign     : default action is to ignore the signal.
Stop   : default action is to stop the process.
Cont  : default action is to continue the process if it is currently stopped.


List of few standard signals :

Name            Default Action              Description
SIGHUP         Terminate Process         Terminal line hangup
SIGINT          Terminate Process         Interrupt program
SIGQUIT        Create Core Image         Quit Program
SIGABRT       Create Core Image        Abort Program
SIGKILL        Terminate Process        Kill Program
SIGTERM      Terminate Process         Software Termination Signal     
SIGUSR1       Terminate Process         User Defined Signal 1
SIGUSR2       Terminate Process         User Defined Signal 2

Note: The signal SIGKILL and SIGSTOP cannot be caught, blocked or ignored.


Case Study: Handle Sigterm Signal in docker container and terminate the process gracefully.

Let suppose we need to run scala application inside our container and based on the signal received we need to handle it and terminate the application gracefully.


Suppose our Dockerfile has an entrypoint as:
ENTRYPOINT [“/bin/bash”, “blog.sh”]


inside our blog.sh script we need to trap the Signal and handle it based on the use case of the case study.

#!/usr/bin/env bash
set -x
pid=0
sigterm_handler() {
echo "sigterm handler called…"
if [ $pid -ne 0 ]; then
kill -TERM "$pid"
echo "scala application terminated…"
wait "$pid"
fi
exit 143;
}
trap 'kill ${!}; sigterm_handler' TERM
#running scala application
sbt run &
pid="$!"
echo "PID=$pid"
# wait forever
while true
do
tail -f /dev/null & wait ${!}
done
set +x


references:

https://medium.com/@gchudnov/trapping-signals-in-docker-containers-7a57fdda7d86
http://man7.org/linux/man-pages/man7/signal.7.html


Knoldus-blog-footer-image

Written by 

Neelam is a software consultant with experience of more than 6 months. She likes to keep up with the trending technologies. She is familiar with languages such as C, C++, Java, Scala, Angular 4 and is currently working on lagom with java. Her hobbies includes playing Table Tennis and listening music.