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

查看:867
本文介绍了我终止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命令首先尝试通过发送一个停止运行的容器来停止正在运行的容器SIGTERM信号发送到容器中的根进程(PID 1)。如果未在超时时间内退出该进程,则将发送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 $!

(关于 wait 的shell信号处理在位更多详细信息此处

(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天全站免登陆