问题描述
我想要保持Docker容器运行即使执行运行命令(容器在 docker运行后立即退出..
我知道命令:
while:; do
$ p $
sleep 300
done
docker run
中的p>
将使其运行,但是如何按顺序编辑 Dockerfile 本身保持运行?
解决方案您可以通过将要执行的命令放入脚本中,并设置脚本作为Docker启动容器时运行的命令:
FROM sixeyed / ubuntu-with-utils
RUN echo'ping localhost&'> /bootstrap.sh
RUN echo'sleep infinity'>> /bootstrap.sh
RUN chmod + x /bootstrap.sh
CMD /bootstrap.sh
从这个Dockerfile构建一个图像并运行一个容器从图像开始,它将开始
ping
背景和sleep
在前台,所以您可以使用docker run -d
守护程序集,并且它将继续运行。这不是理想的 - Docker只监视运行容器的最后一个进程,因此它将检查sleep
code>而不是
ping
。如果ping
命令错误,容器将继续运行。通常,您希望真正的应用程序成为您在CMD
中开始的唯一工具。I want to keep a docker container running even after executing the run command (containers exit immediately after
docker run..
. I know the command:while :;do sleep 300 done
during
docker run
will make it run but how do I edit the Dockerfile itself in order to keep it running?解决方案You can do this by putting the commands you want to execute into a script, and setting the script to be the command Docker runs when it starts a container:
FROM sixeyed/ubuntu-with-utils RUN echo 'ping localhost &' > /bootstrap.sh RUN echo 'sleep infinity' >> /bootstrap.sh RUN chmod +x /bootstrap.sh CMD /bootstrap.sh
When you build an image from this Dockerfile and run a container from the image, it will start
ping
in the background andsleep
in the foreground, so you can daemonize the container withdocker run -d
and it will keep running.This is not ideal though - Docker only monitors the last process it started when it ran the container, so it will be checking on
sleep
rather thanping
. If theping
command errors the container will keep running. Typically, you want the real application to be the only thing you start in theCMD
.这篇关于如何保持无限循环运行,以便在docker中不要关闭容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!