trapping signal from "docker stop" in bash
bash, docker
Solution
Have a look at this, could be inspiring :-)
UPDATE:
@nick-humrich here it is is my lamer copy & past (credit goes to the original author https://github.com/lgierth )
#!/bin/bash
function ensure_started_container {
exists=`docker ps -q | grep $1`
if [ "$?" = "0" ] ; then
echo "[docker-exec] skipping docker start, already started"
else
output=`docker start "$1"`
echo "[docker start] $output"
fi
running=1
}
function setup_signals {
cid="$1"; shift
handler="$1"; shift
for sig; do
trap "$handler '$cid' '$sig'" "$sig"
done
}
function handle_signal {
echo "[docker-exec] received $2"
case "$2" in
SIGINT)
output=`docker stop -t 5 "$1"`
echo "[docker stop] $output"
running=0
;;
SIGTERM)
output=`docker stop -t 5 "$1"`
echo "[docker stop] $output"
running=0
;;
SIGHUP)
output=`docker restart -t 5 "$1"`
echo "[docker restart] $output"
# restart logging
docker attach "$1" &
kill "$logger_pid" 2> /dev/null
logger_pid="$!"
;;
esac
}
running=0
setup_signals "$1" "handle_signal" SIGINT SIGTERM SIGHUP
ensure_started_container "$1"
docker attach "$1" &
logger_pid="$!"
while true; do
if [ "$running" = "1" ]; then
sleep 1
else
break
fi
done
exit_code=`docker wait "$1"`
exit "$exit_code"
Problem
i have an entry point script in a docker container that looks something like the following: ``` #!/bin/bash echo starting up function shut_down() { echo shutting down pid=$(ps -e | grep myapp | awk '{print $1}') kill -SIGTERM $pid exit } trap "shut_down" SIGKILL SIGTERM SIGHUP SIGINT EXIT /opt/myapp ``` I can't figure out how to trap the signal sent in by running `docker stop` on the container. When running interactively, a `ctrl+c` will trigger it as expected, but a `docker stop` command just waits for the 10 second timeout, and exits without ever entering the `shut_down` function How can I trap the signal sent by `docker stop` in bash to do some cleanup?