How to Fix Docker Container Exits Immediately Error
In this tutorial, you'll learn about How to Fix Docker Container Exits Immediately Error. We cover key concepts, practical examples, and best practices.
You start a container with docker run and it exits instantly β containers only run as long as their main process is alive, so if that process finishes or fails, the container stops.
The Problem
docker run ubuntu
Returns immediately with no output. docker ps -a shows:
CONTAINER ID IMAGE COMMAND CREATED STATUS
abc123 ubuntu "bash" 2 seconds ago Exited (0) 1 second ago
Exit code 0 means success β bash exited because no terminal was attached.
Step-by-Step Fix
Step 1: Run in interactive mode
docker run -it ubuntu bash
This keeps the container alive with an interactive shell.
Step 2: Run a foreground process
For services like nginx, the process stays alive:
docker run -d nginx
docker ps
Expected:
CONTAINER ID IMAGE COMMAND CREATED STATUS
abc456 nginx "/docker-entrypoint.β¦" 5 seconds ago Up 5 seconds
Step 3: Debug why the process exits
Check logs:
docker logs <container-id>
Inspect exit code:
docker inspect <container-id> --format '{{.State.ExitCode}}'
Exit code meanings: 0 = success, 1 = application error, 137 = OOM kill, 139 = segfault, 143 = SIGTERM.
Step 4: Test with a sleep command
docker run ubuntu sleep 30
The container stays alive for 30 seconds.
Step 5: Check the Dockerfile CMD and ENTRYPOINT
# WRONG β shell form exits immediately
CMD echo "Hello"
# RIGHT β foreground process
CMD ["nginx", "-g", "daemon off;"]
For Node.js apps:
# WRONG
CMD "npm start"
# RIGHT β exec form
CMD ["node", "server.js"]
Step 6: Use a custom entrypoint that stays alive
For debugging:
docker run -d --entrypoint tail ubuntu -f /dev/null
Then exec into it:
docker exec -it <container> bash
This keeps the container running indefinitely for investigation.
Prevention Tips
- Ensure your container's main process runs in the foreground
- Do not use init systems like systemd inside containers
- Use
docker run -dfor daemon services - Set
ENTRYPOINTto a script that keeps running - Check logs immediately with
docker logs --tail 50
Common Mistakes with container exit
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world DOCKER code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro