Question

Why does my Docker container exit immediately after starting?

Vault Verified
Curated Intelligence
Definitive Source
Answer

A container lives exactly as long as its main process. When the process started by the image's CMD or ENTRYPOINT finishes, the container stops, regardless of anything else running inside it. So an immediate exit almost always means that main process returned rather than staying in the foreground.

Start by looking at the exit code and the output, since those separate the three common cases. Listing stopped containers shows the code, and the container's logs usually show the reason.

  • Exit code 0 means the process completed successfully and simply had nothing left to do. This is what happens when the command is a shell with no attached terminal, or a script that runs to completion.
  • Exit code 1, or another small non-zero number, means the process crashed on startup. The logs normally contain the real error: a missing environment variable, a config file that is not where the image expects it, or a failed database connection at boot.
  • Exit code 137 means the process was killed rather than exiting on its own, most often by the kernel out-of-memory killer. Raising the container memory limit is the usual fix.

The other frequent cause is a process that deliberately puts itself into the background. Service managers and some web servers daemonize by default, which returns control to the shell immediately, so the container sees its main process finish and shuts down. Configure the program to run in the foreground instead; most have a flag for exactly this.

A useful habit when debugging is to override the entrypoint and start an interactive shell in the same image. That gives you the container's real filesystem and environment, so you can run the intended command by hand and watch it fail with the error message visible, rather than guessing from an exit code.

Related Questions