How to keep an infinite loop running in order to n

2019-06-06 03:30发布

问题:

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.