How to keep an infinite loop running in order to not close a container in docker

爷,独闯天下 提交于 2020-01-14 03:56:06

问题


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?


回答1:


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 and sleep in the foreground, so you can daemonize the container with docker 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 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.



来源:https://stackoverflow.com/questions/39818938/how-to-keep-an-infinite-loop-running-in-order-to-not-close-a-container-in-docker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!