This post will look at how to keep a Docker container running for testing, debugging, and troubleshooting purposes.
Why Does Docker Container Exit Immediately After Starting?
When you are getting started with Docker, you might have faced the problem of Docker container exiting immediately after starting.
Normally this does not occur if you try to run a official Nginx container.
But if you run a base ubuntu image, the container will exit right after running it.
Here is a screenshot showing both running Nginx container and exited ubuntu container.
Here is the reason for it.
- To keep the container running, you need a foreground process added to the Docker Entrypoint.
- In the official Nginx image, the Nginx foreground process is part of the Dockerfile. See official Nginx Dockerfile.
- Whereas, in the base Ubuntu image, there is no Entrypoint for the foreground process. That’s why it gets exited right after you execute the docker run command.
Let see how to add a Entrypoint that keeps the ubuntu image running.
Dockerfile Command to Keep the Container Running
Here is a basic Dockerfile with an ENTRYPOINT that will keep on running without getting terminated.
FROM ubuntu:latest ENTRYPOINT ["tail", "-f", "/dev/null"]
Also, lets look at another 3 methods to keep the container running with docker run command.
Method 1: You can use the
-t (pseudo-tty) docker parameter to keep the container running.
docker run -d -t ubuntu
Method 2: You can run the container directly passing the tail command via arguments as shown below.
docker run -d ubuntu tail -f /dev/null
Method 3: Another method is to execute a sleep command to infinity.
docker run -d ubuntu sleep infinity
Once you have the running container, you can attach the container to the terminal session using the
exec parameter as shown below.
0ab99d8ab11c is the container ID
docker exec -it 0ab99d8ab11c /bin/bash
Following are the use cases where you will need a basic running container.
- To test/develop docker images and their configuration
- To troubleshoot systems using utilities inside a container.
- To troubleshoot the Kubernetes cluster with required utilities on a pod.
We hope this article helps! If it doesn’t solve your problem or have a different use case, please drop a comment below.