Your container starts, immediately dies, restarts, dies again. The docker ps output shows “Restarting (1) 2 seconds ago” and you’re watching it cycle endlessly. Here’s how to break the loop and find the actual problem.
Step 1: Check the Exit Code
First, figure out how it’s dying:
| |
Common exit codes:
- 0 — Clean exit (shouldn’t restart unless you have
restart: always) - 1 — Application error (check logs)
- 137 — Killed by OOM (out of memory)
- 139 — Segmentation fault
- 143 — SIGTERM received (graceful shutdown request)
Step 2: Read the Logs (Before They Disappear)
Containers in restart loops lose logs on each restart. Catch them quick:
| |
If logs are empty, the container is crashing before your app even starts — likely a Docker-level issue, not application code.
Step 3: Common Causes and Fixes
Port Already in Use
The most common cause I see. Another process (or another container) already has the port:
| |
Fix: Stop the conflicting process, or change your container’s port mapping:
| |
Missing Environment Variables
Your app expects DATABASE_URL but it’s not set:
| |
Fix: Add the missing variables:
| |
Volume Mount Doesn’t Exist
Container expects a config file at /app/config.yml but the host path doesn’t exist:
| |
Fix: Create the file, or make it optional in your app.
Network Issues (Container Can’t Reach Dependencies)
Your app needs to connect to another container (database, redis) but can’t reach it:
| |
Fix: Ensure both containers are on the same Docker network:
| |
Out of Memory (Exit Code 137)
Docker killed your container for using too much RAM:
| |
Fix: Increase memory limit or fix the memory leak:
| |
Step 4: Stop the Restart Loop to Debug
You can’t debug a container that keeps restarting. Temporarily disable the restart policy:
| |
Or override the entrypoint to keep it alive:
| |
Step 5: The Nuclear Option
When you just need it running and will debug later:
| |
For persistent issues, sometimes a fresh pull helps:
| |
Real Example: What Bit Me Last Week
Had a dashboard container in a restart loop after a server reboot. Exit code 1, logs showed connection refused to the API.
Root cause: The dashboard container started before the API container. It tried to connect, failed, crashed, restarted, failed again.
Fix: Added a health check and dependency:
| |
Now the dashboard waits until the API is actually ready, not just “started.”
Quick Diagnostic Checklist
docker inspect --format='{{.State.ExitCode}}' container— How is it dying?docker logs container— What does it say before death?lsof -i :PORT— Is the port taken?docker exec container env— Are env vars set?docker stats container— Is it running out of memory?docker network inspect— Can it reach its dependencies?
Most restart loops are environment issues, not code bugs. Check the boring stuff first.