Fixing Common Docker Container Exit Codes and Crashes: A Comprehensive Guide
Fixing Common Docker Container Exit Codes and Crashes
Quick answer: Docker containers typically exit for one of three reasons — the process inside finished, the process crashed (non-zero exit code), or the container was stopped externally. To diagnose and fix crashes, collect logs and exit codes, inspect container and host resources, validate configuration (images, environment, volumes, networking), and apply targeted fixes such as handling process signals, setting restart policies, adjusting health checks, and fixing permission or dependency issues.

Why this matters (and how to use this guide)
Docker improves development and deployment, but when a container exits unexpectedly it interrupts services and development velocity. This guide shows how to quickly identify the cause, understand common exit codes and patterns, and apply practical fixes. Use the step-by-step checks for rapid triage, then apply the deeper solutions for durable reliability.

How Docker reports container exits
- Exit code 0 — Clean normal termination (process finished). May be expected for one-off tasks.
- Non-zero exit codes — Application returned an error. Common codes: 1 (generic), 137 (killed by SIGKILL / OOM), 143 (SIGTERM), 139 (segmentation fault), 126/127 (permission/command not found).
- Docker events and status — docker ps -a shows Exited (code); docker inspect returns detailed state and exit information.
- Run docker ps -a to find the exited container and the exit code: docker ps -a –filter “name=your_container”.
- Fetch logs immediately: docker logs (add –since or –tail for large logs).
- Inspect container state: docker inspect and look at .State for ExitCode, OOMKilled, and StartedAt/FinishedAt timestamps.
- Check host resources: free -m, df -h, top or htop, and dmesg for OOM killer messages.
- If the container restarts repeatedly, view restart policy: docker inspect shows RestartPolicy; check orchestrator (Docker Compose, Swarm, Kubernetes) policies too.
- Use a long-running process for services (e.g., run your server, not a build script). For test containers, expect exit 0.
- For containers that should stay alive, ensure ENTRYPOINT/CMD starts a persistent foreground process (don’t background the process or use nohup).
- Read logs to find the stack trace or error message.
- Validate environment variables and secrets are provided correctly.
- Confirm dependencies (databases, message brokers) are reachable and credentials are valid.
- Open a shell inside the image: docker run –rm -it –entrypoint /bin/sh myimage and try the command.
- Ensure your Dockerfile installs the executable and sets PATH correctly.
- Use full path to the binary in ENTRYPOINT, or install missing packages (apt, yum, apk).
- Set executable permission in the image: RUN chmod +x /path/to/script.
- Ensure correct shebang (#!) in scripts and that the interpreter is installed.
- docker inspect shows “OOMKilled”: true.
- Host dmesg or journalctl may contain OOM messages.
- Increase container memory limit (Docker: –memory, Kubernetes: requests/limits).
- Optimize the application’s memory usage (fix leaks, use streaming, reduce caches).
- Use swap cautiously or tune kernel OOM adjustments; consider graceful shutdown handling to release memory.
- Implement signal handling in your app to perform graceful shutdown (trap SIGTERM, finish requests, close resources).
- Increase stop timeout so the process can shut down cleanly (Docker: docker stop default timeout 10s; use –time or API stoptimeout). In Docker Compose, set stopgrace_period.
- Check application logs and core dumps if enabled. Enable core dumps by configuring the container and host ulimit/core_pattern.
- Ensure library and runtime versions match (glibc, OpenSSL, shared libs). Rebuild the image against correct base image.
- Reproduce locally with debugging symbols or run inside an interactive container for diagnosis.
- Configuration errors — missing env vars, wrong command: usually show obvious errors in logs.
- Permission and volume issues — app can’t write to mounted path: check UID/GID, file permissions, SELinux context.
- Dependency connectivity — app dies waiting for DB or API: add health checks and startup ordering or use retry/backoff logic.
- Resource constraints — OOM, CPU throttling: observe metrics and tune limits or scale horizontally.
- Signal handling — orchestrator sends SIGTERM; app immediately exits without cleanup: add graceful signal handling.
- docker ps -a — list containers and exit codes
- docker logs — fetch logs
- docker inspect — detailed state (ExitCode, OOMKilled, RestartPolicy)
- docker run –rm -it –entrypoint /bin/sh — debug inside the image
- docker-compose logs -f — combined service logs
- journalctl, dmesg, free, top/htop — host diagnostics
- kubectl get pods, kubectl describe pod, kubectl logs pod — Kubernetes diagnostics
- Use explicit health checks (HEALTHCHECK in Dockerfile or readiness/liveness probes in Kubernetes) to detect bad states early.
- Set sensible resource requests and limits and monitor actual usage with metrics (Prometheus, Datadog, Cloud watch).
- Design containers to run a single foreground process. Avoid scripts that background the app.
- Provide clear logging and structured logs for observability. Send application logs to centralized logging for postmortems.
- Implement graceful shutdown and signal handling for proper cleanup and zero-downtime deploys.
- Use CI to build and smoke-test images before deployment; include start/stop tests and basic health probes.
- Pin base images and dependency versions to avoid surprising runtime mismatches.
- Run docker ps -a to view exit code.
- docker logs — find application error or confirm it ran to completion.
- If logs show “command not found” or permission errors, open the image shell and validate files and permissions.
- If the app intentionally exits, change CMD/ENTRYPOINT to a long-running process or wrap with a supervisor if truly needed.
- docker inspect to check OOMKilled flag.
- Check host dmesg/journal for OOM events.
- Temporarily increase memory limits to confirm the cause; then profile app memory and fix leaks or tune limits.
- kubectl describe pod — look for Events and RestartCount.
- kubectl logs pod –previous to see previous container logs before the crash.
- Check liveness/readiness probes; misconfigured probes can cause restarts. Adjust probe command, initialDelaySeconds, and failureThreshold.
- Confirm image runs locally with docker run for quicker debugging.
- Match UID/GID of the container process to the owner of the mounted directory or chown the directory at image build/startup.
- When using Docker on SELinux-enabled systems, add :z or :Z mount options to set correct labels.
- For AppArmor conflicts, check dmesg or audit logs and adjust or disable restrictive profiles if necessary.
- Reproducible segfaults or native crashes — capture core dumps and run gdb or equivalent analysis.
- Intermittent OOMs — enable heap profiling (if runtime supports it) and collect memory profiles over time.
- Networking-only failures — capture tcpdump inside the container and on the host to inspect traffic and DNS resolution.
- Internal link opportunities: “Dockerfile best practices” (anchor: Dockerfile best practices) and “Container monitoring and observability” (anchor: monitoring containers).
- Authoritative external links: Docker documentation for docker run and docker inspect, and Kubernetes docs for liveness/readiness probes and CrashLoopBackOff.
- “Developer debugging Docker container logs on terminal” — image showing terminal with docker logs output.
- “Diagram of Docker container lifecycle and common exit reasons” — flowchart style showing normal exit, crash, external stop, OOM.

Quick triage checklist (first 5 minutes)

Common exit codes and how to fix them

Exit code 0 — “It finished”
Cause: The containerized process completed successfully (common for one-off jobs or when the command is incorrect for long-running services).
Fixes:
Exit code 1 — generic error
Cause: Application-level error or misconfiguration.
Fixes:
Exit code 127 — command not found
Cause: The command in CMD or ENTRYPOINT doesn’t exist in the image.
Fixes:
Exit code 126 — permission denied
Cause: Executable exists but lacks execute permission or interpreter missing.
Fixes:
Exit code 137 — SIGKILL, often OOM killed
Cause: The kernel or orchestrator killed the process with SIGKILL (128 + 9 = 137). Most often due to out-of-memory (OOM) or manual kill.
How to confirm:
Fixes:
Exit code 143 — SIGTERM
Cause: The process received SIGTERM (128 + 15 = 143) — graceful shutdown requested by Docker stop or orchestrator.
Fixes:
Exit code 139 — segmentation fault
Cause: Native code crashed (segfault in C/C++ extension or runtime).
Fixes:
Crash patterns and where they come from
Tools and commands you should memorize
Best practices to avoid future crashes
Troubleshooting scenarios and step-by-step fixes
Scenario: Container exits immediately after start
Scenario: Container restarts with exit 137
Scenario: Kubernetes pod shows CrashLoopBackOff
Permissions, volumes, and SELinux/AppArmor
Mounting host directories or using volumes can introduce permission issues. Common fixes:
When to capture deeper diagnostics
Suggested internal and external links
FAQ
Q: My container exits with code 0 but I want it to keep running — what now?
A: It means the process finished successfully. Start a persistent foreground process (e.g., your server), or use a supervisor (systemd, tini) if you need multiple processes. Avoid backgrounding processes with &.
Q: How can I tell if the host killed my container due to OOM?
A: docker inspect will show “OOMKilled”: true. On the host, check dmesg or journalctl for OOM killer logs referencing the container or process PID.
Q: How do I handle graceful shutdowns in containers?
A: Implement signal handlers for SIGTERM/SIGINT in your app, stop accepting new requests, finish in-flight work, and close resources. Configure stop timeouts so the orchestrator waits long enough for graceful shutdown.
Image alt text suggestions
Conclusion
Docker container exits and crashes are usually resolvable with systematic triage: check exit codes and logs, inspect container and host state, and apply targeted fixes like correcting commands, adjusting resource limits, fixing permissions, and handling signals. Build long-term resilience by adding health checks, observability, pinned dependencies, and graceful shutdown handling. If you run into a specific exit code or stack trace, share the logs and exit code and I’ll walk you through a focused debugging plan.
Call to action: Try the quick triage checklist when your next container crashes, and if you want, paste the container logs and exit code here — I’ll help diagnose the root cause and propose exact changes.