捕获来自“ docker stop”的信号猛扑 [英] trapping signal from "docker stop" in bash
问题描述
我在Docker容器中有一个入口点脚本,如下所示:
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
我不知道如何捕获通过运行发送的信号在容器上 docker stop
。交互式运行时, ctrl + c
会按预期触发它,但是 docker stop
命令仅等待10第二次超时,并且退出而没有进入 shut_down
函数
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
如何捕获<$ c发送的信号$ c> docker stop 用bash进行清理吗?
How can I trap the signal sent by docker stop
in bash to do some cleanup?
推荐答案
看看此,可能会令人鼓舞:-)
Have a look at this, could be inspiring :-)
更新:
@ nick-humrich这是我的较早副本&过去(贷记给原始作者 https://github.com/lgierth )
@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"
这篇关于捕获来自“ docker stop”的信号猛扑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!