alt-text

3 Ways to Keep a Docker Container Running

Docker containers will immediately shut down after the main container process has completed. Generally this is set in the CMD or ENTRYPOINT instructions in a Dockerfile, Docker Compose, or the docker run command. Containers shutting down can be problematic when encountering errors, during development, or when you just need to keep containers running so they can be easily used ad-hoc. Below are 3 ways to keep a Docker container running indefinitely.

Using sleep

The sleep command can be used to suspend execution for a specified interval of time. sleep will almost always by available on Linux images making this an easy option. We can use an argument to sleep for a number of seconds, minutes, hours, or days. Some environments will also support the infinity argument which will keep our container running forever.

# sleep for 1 hour
sleep 1h

# sleep for 3600 seconds (1 hour)
sleep 3600

# sleep infinity
sleep infinity

Using this with docker run would look something like the example below.

docker run --name ubuntu --rm ubuntu:latest bash -c 'sleep infinity'

Using an Infinite Loop

A simple while loop will also work to keep a container running. It is easy to combine this while loop with the sleep command mentioned above.

while true
do
  sleep 3600
done

Using this with docker run would look something like the example below.

docker run --name ubuntu --rm ubuntu:latest bash -c 'while true; do sleep 3600; done'

Using tail -f /dev/null

The tail utility is used to display the last part of a file. The -f option causes the utility to wait for additional data to be appended after reaching the end of a file.

/dev/null virtual "null" file that will discard any output redirected to it. We can use tail -f with this file to keep our command and Docker container running forever. Technically using /dev/null is not required, and we can use any file on our file system. But /dev/null is an easy option that won't produce additional output and is available on every Linux distro.

Using this with docker run would look something like the example below.

docker run --name ubuntu --rm ubuntu:latest bash -c 'tail -f /dev/null'