Running containers in detached mode using:
docker run -d <image>
is a common practice. But sometimes, the container stops immediately after starting. This can be confusing, especially if you expect it to stay running.
Let’s understand why this happens and how to fix it.
1️⃣ Why Does It Stop?
A Docker container lives only as long as its main process is running.
When you run docker run -d <image>, Docker:
- Starts a container
- Executes the command specified in the Dockerfile (
CMDorENTRYPOINT) - Stops the container as soon as that command finishes
If the command is short-lived (e.g., echo "Hello"), the container will exit right away.
Example:
docker run -d alpine echo "Hello"
This prints “Hello” and exits — so the container stops immediately.
2️⃣ Common Causes
- No long-running process — Image was built for a single task, not a service.
- Wrong command — You overwrote the default command with something that finishes quickly.
- Misconfigured entrypoint — Script runs and exits without keeping the container alive.
3️⃣ How to Diagnose
- Check container logs:
docker logs <container_id> - Inspect container exit status:
docker ps -aIf the container is stopped, note theSTATUSorExit Code.
4️⃣ How to Keep a Container Running
Option 1 — Run a Long-Running Service
If you want the container to host something like Nginx:
docker run -d nginx
This stays running because nginx is a service that doesn’t exit immediately.
Option 2 — Override Command to Keep Alive
Use a process like tail -f or sleep:
docker run -d alpine tail -f /dev/null
This keeps the container running without doing anything.
Option 3 — Interactive Mode
For debugging, use:
docker run -it <image> sh
You’ll be inside the container until you exit.
Option 4 — Check Your Dockerfile
If building your own image:
CMD ["your", "long-running", "command"]
Ensure your container runs something that keeps running, like a server.
📌 Summary
- Rule: A Docker container stops when its main process exits.
- Fix: Run a long-running command or keep the process alive.
- Use
docker logsanddocker ps -ato see why it stopped.