Docker: Run a Container Indefinitely
Sometimes, using Docker is a convenient way to build or test our applications that must be run on a Linux environment from Windows. These are many ways to run a container forever, including the tail
, sleep
, ping
, for...
and while...
loops. In this post, I will mainly focus on the second example, with a trick to quickly shut down and delete the container.
Example 1
- Start a container
# in Windows host, start Ubuntu 20.04 and run it forever
docker run --rm --name ub_demo ubuntu:20.04 tail -f /dev/null
- Login to container:
docker exec -ti ub_demo /bin/bash
- After completing the task, exit and delete the container:
# in container
exit
# in host (Windows)
docker stop ub_demo
Example 2
- Start a container, but this time, more robustly, the container will automatically destroy itself if the file
/alive.txt
is deleted
# in Windows host, start Ubuntu 20.04 and run it forever
docker run --rm --name ub_demo ubuntu:20.04 /bin/bash -c "touch /alive.txt && while [ -f /alive.txt ]; do sleep 1; done"
- Login to container:
docker exec -ti ub_demo /bin/bash
- Now, after finishing our jobs, we can stop and destroy the current container directly inside it by removing the file:
rm /alive.txt
Thank you, Google Bard, for helping me correct grammar and typos!