Docker

How to Keep Docker Container Running?

Docker containers are the major element of the Docker environment that is generally utilized to build and deploy applications. Sometimes, developers may want to keep the Docker container running for different reasons, such as testing the Docker images or troubleshooting issues. For this purpose, Docker commands are available to keep the Docker container running infinitely.

This blog will demonstrate the methods to keep the Docker container running.

How to Keep Docker Containers Running?

There are different methods to keep the Docker container running infinitely, such as:

Prerequisite: List Docker Images

First, list all the available images and choose the desired image for building and running the container:

docker images

 
The below output displays all the Docker images and we have selected the “py-img”:

Method 1: Keep Docker Container Running by Adding the ENTRYPOINT Directly in Docker Command

To build Docker container and keep it running, execute the below-provided command:

docker run --name cont1 py-img tail -f dev/null

 
Here:

    • –name” option is used to specify the container name.
    • cont1” is the name of the container.
    • py-img” is the Docker image.
    • tail -f” option is utilized to forcefully read the “dev/null” file.

The above-listed command will overwrite the default entry point from the container to ensure that the container keeps running while reading “dev/null”:

Method 2: Keep Docker Container Running by Adding the Infinite Sleep in Docker Command

Another way to build a Docker container and keep it running is using the “sleep infinity” option in the Docker command:

docker run --name cont2 py-img sleep infinity

 
Here, the “sleep infinity” option will keep the Docker container running infinitely:


Bonus Tip: Verification

Lastly, verify whether the containers are kept running or not by executing the provided command:

docker ps -a

 
In the below screenshot, the status indicates that both containers are running:


We have explained different methods for keeping the Docker container running infinitely.

Conclusion

To keep the Docker container running, utilize the “docker run –name <container-name> <image-name> tail -f dev/null” or “docker run –name <container-name> <image-name> sleep infinity” command. This blog demonstrated the methods for keeping the Docker container running.

About the author

Laiba Younas

I have done bachelors in Computer Science. Being passionate about learning new technologies, I am interested in exploring different programming languages and sharing my experience with the world.