docker container exits immediately — how to fix

# Run interactively to see what fails
docker run -it --rm your-image /bin/sh

# Or check the exit log
docker run --name debug your-image
docker logs debug
docker inspect debug --format '{{.State.ExitCode}}'

You run docker run your-image and the container exits immediately or stops instantly:

$ docker run my-app
$ docker ps
CONTAINER ID   IMAGE   COMMAND   CREATED   STATUS    PORTS   NAMES
# (empty — container already exited)

The container started, executed its command, then exited because nothing kept it running in the foreground or the entrypoint failed right away.

No foreground process (daemon forked to background)

If your CMD starts a service that daemonizes (e.g. nginx -g "daemon off;" is missing), the container exits.

# Dockerfile — keep nginx in foreground
CMD ["nginx", "-g", "daemon off;"]

# For a shell-based entrypoint, end with exec "$@" or wait
CMD ["/bin/sh", "-c", "start-server && wait"]

Keep a container alive for debugging

# Override the command to get a shell
docker run -it --entrypoint /bin/sh your-image

# Or keep it running with tail
docker run -d your-image tail -f /dev/null

Restart policy — auto-restart on failure

docker run -d --restart unless-stopped your-image