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 the Docker container exiting immediately after starting.
Normally this does not occur if you try to run an official Nginx container.
But if you run a base Ubuntu image, or build a Docker image with the wrong configs, the container will exit right after running it.
Here is a screenshot showing both the 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’s see how to add an 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.
ENTRYPOINT ["tail", "-f", "/dev/null"]
Also, let’s look at another 3 methods to keep the container running with the docker run command.
Method 1: Use pseudo-tty
You can use the
-t (pseudo-tty) docker parameter to keep the container running.
docker run -d -t ubuntu
Method 2: Using the tail command
You can run the container directly by passing the tail command via CMD arguments as shown below.
docker run -d ubuntu tail -f /dev/null
Method 3: Using sleep infinity
Another method is to execute a Linux 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 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.
If you want to learn about optimizing Docker images, check out our guide on reducing docker image size