终止docker容器时如何执行脚本 [英] How to execute a script when I terminate a docker container

查看:84
本文介绍了终止docker容器时如何执行脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的控制台上打字:

I want when I type on my console:

docker ^a docker container^ stop

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

To execute a script before terminating. is that possible?

推荐答案

docker stop 命令首先尝试通过向容器中的根进程 (PID 1) 发送 SIGTERM 信号来停止正在运行的容器.如果进程在超时时间内没有退出,则会发送 SIGKILL 信号.

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 信号并根据需要执行任何关闭逻辑.

In practice, that means that you have to define an ENTRYPOINT script, which will intercept (trap) the SIGTERM signal and execute any shutdown logic as appropriate.

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

A sample entrypoint script can look something like this:

#!/bin/bash

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

#Trap SIGTERM
trap 'cleanup' SIGTERM

#Execute a command
"${@}" &

#Wait
wait $!

(shell 信号处理,关于 wait,在这里有更详细的解释)

(shell signal handling, with respect to wait, is explained in a bit more details here)

请注意,对于上面的入口点,只有在显式停止容器时才会执行清理逻辑,如果您希望它在底层进程/命令自行停止(或失败)时也运行,您可以将其重构为如下.

Note, that with the entrypoint above, the cleanup logic will only be executed if container is stopped explicitly, if you wish it to also run when the underlying process/command stops by itself (or fails), you can restructure it as follows.

...

#Trap SIGTERM
trap 'true' SIGTERM

#Execute command
"${@}" &

#Wait
wait $!

#Cleanup
cleanup

这篇关于终止docker容器时如何执行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆