TIPS to keep Docker Container Running? [5 Methods]

TIPS to keep Docker Container Running? [5 Methods]

What is meant by keeping docker container in Running State?

Docker is a containerization tool used by most organizations for building, testing, and deploying their applications in different environments. Most of you must have faced the problem of a Docker container exiting immediately after the execution is completed. While we have situation where we would like to connect to container and do some task or debugging for which the container must be in Running state.

Firstly, let us run the official Nginx and Ubuntu docker containers.

$ docker run -d nginx

Output

Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
a603fa5e3b41: Downloading [==================>                ] 11.45MB/31.41MB
a603fa5e3b41: Pull complete
c39e1cda007e: Pull complete
90cfefba34d7: Pull complete
a38226fb7aba: Pull complete
62583498bae6: Pull complete
9802a2cfdb8d: Pull complete
Digest: sha256:e209ac2f37c70c1e0e9873a5f7231e91dcd83fdf1178d8ed36c2ec09974210ba
Status: Downloaded newer image for nginx:latest
7f7346350316929960119bd565f35f9b7cf72859f9da300a04e8aae7b2a3b34d
$ docker run -d ubuntu

Output

b45792966d1f151e12bba0dbaeb4c1b904289d312ad9df90f97a0b81dc70b08f

Now let us look at the status of the docker containers

CONTAINER ID  IMAGE     COMMAND         CREATED       STATUS           PORTS   NAMES
b45792966d1f  ubuntu     "bash"          35 seconds ago    Exited (0) 31 seconds ago       interesting_solomon
7f7346350316  nginx     "/docker-entrypoint.…"  About a minute ago  Up About a minute      80/tcp   gifted_lederberg

You can observe that the Nginx container is running whereas the Ubuntu container exited.

The reason for this is that in order to keep running the docker container, there must be a foreground process added to the Docker Entrypoint. This happens in the case of Nginx whereas the Ubuntu docker doesn’t have an entrypoint for the foreground process.

In this article, let us see how to add an Entrypoint that keeps running the docker container.


Understanding Why Containers Stop

At its core, a Docker container is simply a process (or group of processes) isolated from other processes on the host system. This process runs in the foreground and determines the lifespan of the container. When the main process (or command) within the container exits, the container itself stops.

1. Main Process Completion:

Description: This is a straightforward and common reason. If the main process inside the container was designed to complete a task and then exit (e.g., a batch job or a script that performs a one-off task), the container will naturally stop after the task is done.

Example: A container running a script to backup a database will exit after the backup completes.

2. Error in the Main Process:

Description: Sometimes the main process might encounter an error or exception it can’t handle and will crash. When this happens, the container will stop.

Example: A web server inside a container could crash if it’s unable to bind to the required port because it’s already in use.

Troubleshooting Tip: Review container logs using docker logs CONTAINER_ID to see if there are any error messages or stack traces.

3. Misconfiguration:

Description: If the container’s main process expects certain configurations to be present and they aren’t, it might fail to start or exit prematurely.

Example:

A database container expecting specific volume mounts or environment variables might fail if those aren’t provided.

An application requiring a license key provided as an environment variable will stop if it’s missing or invalid.

Troubleshooting Tip: Cross-check your configuration files, environment variables, and runtime parameters to ensure they match what the application expects.

4. OOM (Out Of Memory) Kills:

Description: If a container exceeds the memory limits set for it, the Linux kernel might kill processes inside the container to reclaim memory.

Troubleshooting Tip: Monitor memory usage and consider increasing memory limits if necessary.

5. External Stops:

Description: A user or an orchestrator (like Kubernetes) can forcefully stop a container.

Example: Running the command docker stop CONTAINER_ID.

6. Health Checks Failure:

Description: If health checks are configured and they consistently fail, some orchestrators or management tools might stop or restart the container.

Troubleshooting Tip: Inspect the health check configurations and monitor their logs or outputs.


Techniques to make sure Docker Container keep Running

Method 1 - Using interactive mode

$ docker build -t ubuntu:test .

Output

Sending build context to Docker daemon 2.048kB
Step 1/2 : FROM ubuntu:latest
---> a8780b506fa4
Step 2/2 : ENTRYPOINT ["tail", "-f", "/dev/null"]
---> Running in 0bd9d1f5fa00
Removing intermediate container 0bd9d1f5fa00
---> 8d21ee677a92
Successfully built 8d21ee677a92
Successfully tagged ubuntu:test

Once the container is successfully built, run the container again using -t for interactive mode:

$ docker run -d -t ubuntu:test

Output

4f6a1037bf93647df37a9508183a80f890811b1ce8cc65e6b3dcc5a29a48eb84

Now verify the status to make sure the docker container is still in Running state:

CONTAINER ID  IMAGE     COMMAND         CREATED     STATUS     PORTS   NAMES
4f6a1037bf93  ubuntu:test  "tail -f /dev/null"   24 seconds ago  Up 12 seconds       musing_mendeleev

Method 2 - Adding entrypoint

Here we are overwriting the default entrypoint from the container to make sure the contain keeps running while trying to read /de/null:

$ docker run -d ubuntu tail -f /dev/null

Output

b2995a08921aaaf43ff93ec0b253367c2f2295f792f52bfc500fc7d3f59773c8

Verify the status of the container:

CONTAINER ID  IMAGE     COMMAND         CREATED       STATUS     PORTS   NAMES
b2995a08921a  ubuntu    "tail -f /dev/null"   6 seconds ago    Up 3 seconds       vibrant_chatterjee

Method 3 - Add infinity sleep command

This is another fix to keep docker container running by adding an infinite sleep while running the container as shown below:

$ docker run -d ubuntu sleep infinity
df715c7683c61558dff9a032cfb8d959329bd2ed9e733a139dcd84a82d267151

Verify the container status:

CONTAINER ID  IMAGE     COMMAND         CREATED       STATUS       PORTS   NAMES
df715c7683c6  ubuntu    "sleep infinity"     19 seconds ago    Up 15 seconds         trusting_jang

Method 4: Use infinite loop script

Use a script with an infinite loop as the main process:

docker run -d IMAGE_NAME sh -c "while true; do sleep 1; done"

Method 5: Socket Listening

Run a process that listens to a socket, effectively keeping the container alive as long as there are connections. For instance, using nc (netcat):

docker run -d -p 8080:8080 IMAGE_NAME nc -l -p 8080

Why do you need a docker container in Running state?

You might need to have the docker container running because of the below reasons -

  1. This helps the developer to troubleshoot the issues
  2. This helps the developer to test the docker images

Additionally, docker also provides an option to start the containers automatically. To know more please visit our guide - https://www.golinuxcloud.com/docker-restart-container/


Conclusion

It is important to keep running the docker containers since the developers can troubleshoot the issues. Hope this article helped you understand how to keep running the docker container always. In case of any queries please feel free to reach out to us and we will respond at the earliest.


References

Docker container will automatically stop after “docker run -d”
Start containers automatically

Deepak Prasad

Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels across development, DevOps, networking, and security, delivering robust and efficient solutions for diverse projects.