Why does my Docker container exit right after it starts?
Common causes
Docker treats the container as finished as soon as its main process stops. A script that runs one task and then ends, or a server that crashes on a missing environment variable, will shut down the container right away. A wrong path or a typo in the command can also stop it before it does any work.
- The main command finishes and exits
- A required environment variable is missing
- The program crashes on startup
- The entrypoint or command path is wrong
Finding the reason
Run docker logs with the container name to see what the program printed before it stopped. If the logs are empty, run the image interactively with a shell so you can test the command by hand. Checking the exit code also helps, since different codes point to different kinds of failure.
Keeping it running
For a long-running service, make sure the main process runs in the foreground instead of being sent to the background. Running a shell script that starts a service and then exits is a common mistake. Restart policies can help after a crash, but they do not fix the underlying error.
Common mistakes
- Running a daemon in the background so the container has no foreground process.
- Ignoring the logs and rebuilding the image several times instead.
- Using a restart policy to hide a crash that needs fixing.
