Why Does My Docker Container Exit Immediately?

One of the most common frustrations developers face when starting with Docker is this:

👉 “I ran my container with docker run -d <image>, but it exits immediately!”

Don’t worry — this behavior is actually by design. Let’s break it down.


1️⃣ Containers Run a Single Process

A Docker container is not a lightweight VM — it’s designed to run one main process.
When that process ends, the container also stops.

Example:

docker run ubuntu echo "Hello"
  • The command echo "Hello" runs.
  • Once it finishes, there’s nothing left to do.
  • The container exits immediately.

✅ This is expected behavior.


2️⃣ Detached Containers Still Need a Process

Running with -d (detached mode) doesn’t keep the container alive unless there’s a foreground process.

Example:

docker run -d ubuntu

This exits right away because there’s no command to run in the foreground.

If you want an interactive shell:

docker run -it ubuntu bash

This will keep the container alive until you exit the shell.


3️⃣ Common Causes of Immediate Exit

🔹 No foreground process

If your CMD or ENTRYPOINT finishes quickly, the container exits.

🔹 Running services incorrectly

If you run a service (like nginx) in the background inside the container (nginx -g "daemon off;" &), the backgrounding causes the container to stop — because Docker sees no foreground process.

🔹 Misconfigured Dockerfile

If CMD or ENTRYPOINT is set to something that ends right away, the container will stop.


4️⃣ How to Keep Containers Running

Here are a few solutions depending on your use case:

✅ Run a long-lived process

For servers like Nginx or MySQL, run them in the foreground:

CMD ["nginx", "-g", "daemon off;"]

✅ Use tail -f for debugging

If you just want to keep the container alive to inspect it:

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

✅ Start with an interactive shell

For debugging inside the container:

docker run -it ubuntu bash

✅ Check logs

If your container exits unexpectedly, view the logs:

docker logs <container_id>

5️⃣ Key Takeaways

  • A Docker container runs one main process.
  • When that process exits, the container stops.
  • Detached mode (-d) does not prevent this behavior.
  • To keep a container running, ensure the main process runs in the foreground.

👉 So, next time your container exits immediately, don’t panic! Just remember: no running process = no running container.

Sharing Is Caring:

Leave a Comment