3

Signals Handling Inside Docker Container

 2 years ago
source link: https://blog.knoldus.com/signals-handling-inside-docker-container/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Signals Handling Inside Docker Container

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK