Fix: Docker Container Exits Immediately — Debugging and Solutions

Problem

You start a Docker container and it exits immediately:

docker run my-app
# Running...
docker ps
# (no container shows up)

docker ps -a
# CONTAINER ID   STATUS
# a1b2c3d4e5f6   Exited (0) 2 seconds ago

Symptoms

  • docker ps shows no running container
  • docker ps -a shows Exited (0) or Exited (1) within seconds
  • No error output visible
  • docker logs <container> shows nothing or truncated output

Root Cause

Docker containers run as long as their PID 1 process runs. When that process exits, the container stops. Common causes:

  1. The main process finishes and exits — e.g., a script that runs once and terminates
  2. No foreground process — the CMD/ENTRYPOINT runs something that daemonises or backgrounds itself
  3. Crash on startup — the process fails immediately, often before logs flush
  4. Wrong ENTRYPOINT/CMD — the command is invalid or returns instantly

Solution

Step 1: Check the container logs

docker logs <container-id>

If no logs appear, the process likely exited before writing anything.

Step 2: Inspect the exit code

docker inspect <container-id> | grep -i exit
  • Exit code 0: The process finished successfully. Common with scripts that run to completion.
  • Exit code 1: Application error or crash.
  • Exit code 127: Command not found.
  • Exit code 137: Killed by OOM or docker kill.

Step 3: Override the entrypoint to debug interactively

docker run -it --entrypoint /bin/sh my-app

From inside the shell, run the original command manually to see what happens:

# Inside the container
python app.py    # Example — replace with your actual command

This reveals the actual error without the container exiting.

Step 4: Ensure a foreground process

In your Dockerfile, the final process must run in the foreground. For example:

❌ Wrong — nginx daemonises:

CMD ["nginx"]

✅ Correct — runs in foreground:

CMD ["nginx", "-g", "daemon off;"]

For custom applications, ensure no fork() or daemonize() calls near the end, and that your process doesn’t intentionally background itself.

Step 5: Add a keep-alive for debugging

Temporarily add this to keep the container alive for inspection:

docker run -d my-app tail -f /dev/null

Then docker exec -it <container> /bin/sh to explore.

Verification

After fixing your Dockerfile or run command:

docker run -d --name test my-app
sleep 2
docker ps --filter name=test
# Should show the container as "Up"

docker logs test
# Should show application logs without immediate exit

Prevention

  • Always run apps in the foreground inside containers
  • Use a process manager like tini or --init flag for proper signal handling
  • Add health checks: HEALTHCHECK in Dockerfile or --health-cmd flag
  • Log to stdout/stderr — don’t write to files inside the container
  • Test locally before deploying: docker run --rm my-app

References


Advertisement