DockerHigh
Fix: Docker Container Exiting Immediately
Container starts and immediately exits (status 'Exited')
!Symptoms
- Container starts and immediately exits (status 'Exited')
- docker run returns immediately without keeping the container alive
- docker ps shows nothing but docker ps -a shows exited containers
- docker logs shows the application error or nothing at all
?Root Causes
- Entrypoint or CMD process exits (no foreground process)
- Application crashes on startup due to configuration error
- Missing environment variables required by the application
- Incorrect working directory or file permissions inside the container
- Using shell form CMD that exits when the shell exits
#Diagnosis Steps
- 1Check container logs: `docker logs <container-id>`
- 2Check exit code: `docker inspect <container-id> --format='{{.State.ExitCode}}'`
- 3Inspect the entrypoint: `docker inspect <image> --format='{{.Config.Entrypoint}} {{.Config.Cmd}}'`
- 4Run interactively to debug: `docker run -it --entrypoint /bin/sh <image>`
- 5Check if all required env vars are set in your docker run command
>Fix
- 1Ensure CMD runs a foreground process (not a daemon/background process)
- 2Use exec form for CMD: `CMD ["node", "server.js"]` not `CMD node server.js &`
- 3Pass all required environment variables with -e flags or --env-file
- 4Fix file permissions: add proper USER and chmod in Dockerfile
- 5If debugging, keep alive temporarily: `docker run -it <image> /bin/sh`
*Prevention
- Always test Docker images locally before deploying
- Use HEALTHCHECK in Dockerfile to detect startup failures
- Document all required environment variables in the README or .env.example
- Use docker-compose for consistent environment variable management
- Add proper signal handling (SIGTERM) in your application for graceful shutdown
Related Error Messages
Exited (0)Exited (1)Exited (127)Exited (137)exec format errorstandard_init_linux.go: exec user process caused: no such file or directory