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”, “”]

inside our 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
sigterm_handler() {
echo "sigterm handler called…"
if [ $pid -ne 0 ]; then
kill -TERM "$pid"
echo "scala application terminated…"
wait "$pid"
exit 143;
trap 'kill ${!}; sigterm_handler' TERM
#running scala application
sbt run &
echo "PID=$pid"
# wait forever
while true
tail -f /dev/null & wait ${!}
set +x



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.