Docker: Container exits immediately with code 0 or 1
Fix containers that terminate immediately upon startup (Exited (0) or Exited (1)) due to foreground process termination, syntax errors, or missing entrypoints.
Symptoms
docker run -d my-imagecreates the container, butdocker psshows nothing running.docker ps -ashows container statusExited (0)orExited (1)seconds after launch.
Why It Happens
A Docker container stays alive only as long as its primary process (PID 1) is actively executing in the foreground. Once PID 1 finishes or crashes, the container lifecycle immediately ends.
Common causes:
- Background daemonizing: Running background daemons (e.g.
nginxorapache2ctl startwithoutdaemon off;). - Interactive shell without TTY: Running
docker run -d alpine shwithout-itor a continuous loop. - Application crashes on startup: Missing environment variables, database connection failure, or syntax runtime errors.
- Shell script exit: Entrypoint script executing and completing without a foreground command at the end (missing
exec "$@").
How to Diagnose
```bash
docker logs <container_name_or_id>
```Solutions & Fixes
1. Run Services in Foreground Mode
If running Nginx or web servers:
# Incorrect: Spawns background process and exits
CMD ["nginx"]
# Correct: Keeps PID 1 in foreground
CMD ["nginx", "-g", "daemon off;"]2. Keep Interactive Containers Alive for Debugging
# Run with interactive terminal
docker run -it my-image /bin/sh
# Or keep container alive with tail loop
docker run -d my-image tail -f /dev/null3. Ensure Entrypoint Scripts End with exec "$@"
#!/bin/sh
set -e
# Run initial migrations
npm run db:migrate
# Hand over PID 1 to the CMD passed in Dockerfile
exec "$@"Related Topics
Docker: permission denied while connecting to daemon socket
Fix Linux Docker daemon permission errors without needing to run sudo docker on every command.
Docker: Cannot connect to database from container (ECONNREFUSED / localhost)
Fix database connection errors from Docker containers caused by using localhost instead of bridge network service names or host.docker.internal.