如何保持无限循环运行以便不关闭docker中的容器 [英] How to keep an infinite loop running in order to not close a container in docker

查看:138
本文介绍了如何保持无限循环运行以便不关闭docker中的容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使在执行运行命令后,我也想保持 docker 容器运行(容器在 docker run.. 之后立即退出.我知道命令:

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

docker run 期间将使其运行,但我如何编辑 Dockerfile 本身以使其保持运行?

during docker run will make it run but how do I edit the Dockerfile itself in order to keep it running?

推荐答案

你可以通过将你要执行的命令放到一个脚本中,并将脚本设置为Docker启动容器时运行的命令:

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

当你从这个 Dockerfile 构建一个镜像并从这个镜像运行一个容器时,它会在后台启动 ping 并在前台启动 sleep,所以你可以守护进程带有 docker run -d 的容器,它将继续运行.

When you build an image from this Dockerfile and run a container from the image, it will start ping in the background and sleep in the foreground, so you can daemonize the container with docker run -d and it will keep running.

但这并不理想 - Docker 仅监控它在运行容器时启动的最后一个进程,因此它将检查 sleep 而不是 ping.如果 ping 命令出错,容器将继续运行.通常,您希望真正的应用程序是您在 CMD 中启动的唯一内容.

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 than ping. If the ping command errors the container will keep running. Typically, you want the real application to be the only thing you start in the CMD.

这篇关于如何保持无限循环运行以便不关闭docker中的容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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