Short and sweet example for using trap in BASH with Docker containers to handle signals/container stop requests
This repository provides a script: runner.sh
This is used as an entrypoint for the container. It spawns a mock daemon (nc -l) and will trap these signals:
SIGTERMSIGINTSIGQUITSIGABRT
Once the service is running, the script uses wait for either the process to terminate, or a signal to be trapped.
tini makes this possible -- it forwards the signals it receives from the Docker daemon to the trapping script.
The _signal_handler function in the script provides a handle for the shutdown process.
This is where checking on agent work status or cleanup before/after shutdown would happen.
Note: SIGKILL cannot be trapped. This is generally used in emergency situations (out-of-memory/host machine shutdown timeout) and is unavoidable/expected.
While this uses tini as a very simple init process (PID 1) to handle spawning the actual process/pass signals, the image doesn't need to include it.
It's reportedly included with Docker when using the --init option with docker run, see upstream
See below for an example of how the script in the container traps the signal, and runs through some mock cleanup steps
The left pane shows the container logs/messages, including ps output with the running process -- after the signal is trapped
While the right pane shows the stop request.
BASH
While the provided Docker container installs tini-static, nmap-ncat, and procps-ng, these are likely not truly needed.
