我已经从 docker 镜像创建了 gcloud
计算实例并将其配置为启动 shutdown script它应该调用 docker stop
以正常关闭容器中的应用程序。
gcloud beta compute instances create-with-container mycontainername \
--container-image ypapax/trap_exit \
--metadata-from-file shutdown-script=./on_shutdown.sh
这是我的初始 on_shutdown.sh:
#!/usr/bin/env bash
docker stop $(docker ps -a -q)
不过,我向其中添加了更多调试行,现在 on_shutdown.sh
看起来像:
#!/usr/bin/env bash
# https://cloud.google.com/compute/docs/shutdownscript
curl -X POST -d "$(date) running containers on $(hostname): $(docker ps)" http://trap_exit.requestcatcher.com/test
docker stop $(docker ps -a -q)
result=$?
curl -X POST -d "$(date) $(hostname) stop status code: $result" http://trap_exit.requestcatcher.com/test
当我重启谷歌计算实例时:
sudo reboot
启动脚本 on_shutdown.sh
(我看到它正在检查 requrest listener)。但是当它试图停止 docker 容器时,还没有什么可以停止,docker ps
显示空行。
所以这一行:
curl -X POST -d "$(date) running containers on $(hostname): $(docker ps)" http://trap_exit.requestcatcher.com/test
给我
Thu Jul 12 04:29:48 UTC 2018 running containers on myinstance:
在调用 sudo reboot
之前,我检查了 docker ps
并看到我的容器正在运行:
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
bbaba30e65ff ypapax/trap_exit "/entrypoint.sh" 7 seconds ago Up 7 seconds myinstance
所以看起来 docker 容器在调用 reboot
和启动 on_shutdown.sh
之间被杀死了。问题是 killing 不会在我的 entrypoint 中调用 trap cleanup EXIT
.需要停止它才能调用清理。
这是我的切入点:
#!/usr/bin/env bash
set -ex
cleanup(){
echo cleanup is called
curl -X POST -d "cleanup is called on $(hostname) $(date)" http://trap_exit.requestcatcher.com/test
}
trap cleanup EXIT
curl -X POST -d "container is started on $(hostname) $(date)" http://trap_exit.requestcatcher.com/test
sleep 10000
所以我想在 gcloud 计算实例重启或关闭时运行我的容器清理,但是标志 --metadata-from-file shutdown-script=./on_shutdown.sh
没有帮助它。我还尝试了其他方法在重新启动时调用脚本,例如 this .但是我的脚本根本没有启动。
这是我的 Dockerfile如果有帮助的话。
最佳答案
首先,有limitations coming with this approach :
- Create and run shutdown scripts that execute commands right before an instance is terminated or restarted, on a best-effort basis.
- Shutdown scripts are especially useful for instances in a managed instance group with an autoscaler.
- The script runs during the limited shutdown period before the instance stops
如您所见,docker 可能在关闭脚本运行时已经停止:使用 docker ps -a
(而不是 docker ps)检查所有退出容器的状态。
尝试 adding a supervisor (如 in this example )一个 docker 镜像本身,以便查看主管是否或至少 use the docker run --init
option :目标是检查容器本身是否确实使用了它们的主管脚本。
关于linux - 使用 gcloud metadata-from-file shutdown-script 优雅地停止 docker 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51298734/