加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在bash中捕获来自“docker stop”的信号

发布时间:2020-12-15 18:42:49 所属栏目:安全 来源:网络整理
导读:我在docker容器中有一个入口点脚本,看起来像下面这样: #!/bin/bashecho starting upfunction shut_down() { echo shutting down pid=$(ps -e | grep myapp | awk '{print $1}') kill -SIGTERM $pid exit}trap "shut_down" SIGKILL SIGTERM SIGHUP SIGINT EX
我在docker容器中有一个入口点脚本,看起来像下面这样:
#!/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

我不知道如何通过运行停放码头停在容器上来捕获发送的信号.当交互运行时,ctrl c将按预期触发它,但是docker stop命令只是等待10秒超时,并且退出而不用进入shut_down函数

我怎么可以捕获由巴基斯坦码头停止发送的信号进行一些清理?

看看 this,可以鼓舞人心:-)

更新:

@ nick-humrich这里是我的lamer copy&过去(信用原作者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"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读