发出“docker container stop”命令后如何执行命令/脚本?

时间:2021-03-24 18:33:46

标签: docker dockerfile docker-entrypoint

我希望容器在发出“docker container stop”命令后停止之前运行确定的命令。我发现了问题 How to execute a script when I terminate a docker container 但它并没有真正起作用,因为容器在创建后不断崩溃,即使我在运行时添加了一个无限循环来执行。 我正在运行容器: docker run -ti -d --name test stop_test

可能有什么问题?

这是我的 docker 文件:

#Starting with a ubuntu image
FROM ubuntu

#Installing all dependencies

#Copying files
COPY loop.sh .
COPY commands.sh .
COPY stop.sh .

#Running new container
RUN chmod +x commands.sh
RUN chmod +x stop.sh
CMD ["./commands.sh"]

#Adding Entrypoint
ENTRYPOINT [ "/bin/bash", "-c", "./stop.sh" ]

停止脚本是:

#!/bin/bash

#Defining cleanup procedure
cleanup() {
    echo "Container stopped. Running script..."
}

#Trapping the SIGTERM
trap 'cleanup' SIGTERM

#Execute a command
less /etc/password &

#Wait
wait $!

#Cleanup
cleanup

循环脚本:

#!/bin/bash

while :
do
 sleep 300
done

命令脚本是:

#!/bin/bash

./loop.sh

1 个答案:

答案 0 :(得分:0)

问题出在 stop.sh 脚本正在执行的命令中。我用无限循环脚本替换了它并且运行良好。

相关问题