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

如何在终止docker容器时执行脚本

发布时间:2020-12-16 03:44:29 所属栏目:安全 来源:网络整理
导读:当我在控制台上输入时我想要: docker ^a docker container^ stop 在终止之前执行脚本.那可能吗? 最佳答案 The docker stop command attempts to stop a running container first by sending a SIGTERM signal to the root process (PID 1) in the containe

当我在控制台上输入时我想要:

docker ^a docker container^ stop

在终止之前执行脚本.那可能吗?

最佳答案

The docker stop command attempts to stop a running container first by sending a SIGTERM signal to the root process (PID 1) in the container. If the process hasn’t exited within the timeout period a SIGKILL signal will be sent.

实际上,这意味着您必须定义一个ENTRYPOINT脚本,该脚本将拦截(陷阱)SIGTERM信号并根据需要执行任何关闭逻辑.

示例入口点脚本可能如下所示:

#!/bin/bash

#Define cleanup procedure
cleanup() {
    echo "Container stopped,performing cleanup..."
}

#Trap SIGTERM
trap 'cleanup' SIGTERM

#Execute a command
"${@}" &

#Wait
wait $!

(shell信号处理,关于等待,更详细解释here)

请注意,使用上面的入口点,只有在显式停止容器时才会执行清理逻辑,如果您希望它在基础进程/命令自行停止(或失败)时也运行,则可以按如下方式对其进行重组.

...

#Trap SIGTERM
trap 'true' SIGTERM

#Execute command
"${@}" &

#Wait
wait $!

#Cleanup
cleanup

(编辑:李大同)

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

    推荐文章
      热点阅读