Docker Engine 29.10, Docker Compose v5.7
Your Docker container keeps restarting, docker ps says Restarting (1) 3 seconds ago, and the app never answers. This guide shows you how to read what the container is telling you, stop the loop so you can work, and fix the eight causes behind almost every restart loop. It matters because a looping container hides its own error: every restart pushes the real message further up the logs, and the restart delay keeps growing until a 2-second crash feels like a dead server.
Try it on Hubfly space: deploy the same container and watch every failed start in one log view.
What "Restarting" actually means
A container restarts for one reason only: its main process (PID 1) exited, and a restart policy told Docker to start it again. Docker never restarts a running process on its own. So the question is never "why does Docker restart it?" but "why does my process exit?"
The number in brackets is the last exit code. Restarting (1) means the process exited with code 1. Restarting (0) means it exited cleanly and Docker started it again anyway.
Docker waits a little longer before each new attempt. The delay starts at 100 ms and doubles each time, and it resets once the container stays up for 10 seconds. In practice that looks like this:
| Time after first crash | Restarts so far | Gap before the next start |
|---|---|---|
| 4 s | 6 | about 3 s |
| 16 s | 8 | about 13 s |
| 30 s | 9 | about 26 s |
That is why a loop feels fast at first and then looks like the container is "stuck".
Step 1: Read the logs of the failed runs
Logs survive restarts. docker logs shows the output of every attempt in order, so the error is right there:
docker logs --tail 50 orders-api starting api Error: DATABASE_URL is not set starting api Error: DATABASE_URL is not set With Compose, use the service name:
docker compose logs --tail 50 api Why first: the last lines before each crash are the real error in about every case. Read them before you change anything.
Step 2: Get the exit code, OOMKilled flag and restart count
docker inspect orders-api --format \ 'Status={{.State.Status}} ExitCode={{.State.ExitCode}} OOMKilled={{.State.OOMKilled}} RestartCount={{.RestartCount}} Policy={{.HostConfig.RestartPolicy.Name}}' Status=restarting ExitCode=1 OOMKilled=false RestartCount=9 Policy=always To see each crash as it happens, with its exit code:
docker events --filter container=orders-api --filter event=die \ --format '{{.Time}} {{.Action}} exitCode={{.Actor.Attributes.exitCode}}' Match the code to the cause:
| Exit code | What happened | Most likely cause | Go to |
|---|---|---|---|
| 0 | The process finished normally | A one-off script, or the app runs in the background and PID 1 ends | Cause 2 |
| 1 (or 2, 3…) | The app raised an error and quit | Missing env var, bad config, database not reachable yet | Causes 1 and 3 |
| 126 | The entrypoint can't be executed | Script without the execute bit | Cause 4 |
| 127 | The command doesn't exist | Typo, or the binary isn't in this image | Cause 4 |
| 137 | Killed with SIGKILL | Out of memory (OOMKilled=true), or a slow stop | Cause 5 |
| 139 | Segmentation fault | A crash in native code (a bug or a broken library) | Cause 7 |
| 143 | Stopped with SIGTERM | Something told it to stop | Cause 7 |
| 255 | The entrypoint couldn't be executed | Windows line endings (CRLF) in a script, or an image built for another CPU (exec format error) | Causes 4 and 7 |
That last row is easy to misread. A script saved with CRLF line endings fails with exec /entrypoint.sh: no such file or directory and exit code 255, even though the file is plainly there.
Step 3: Stop the loop while you fix it
You can't open a shell in a restarting container:
docker exec -it orders-api sh Error response from daemon: Container cfbef6d670ae... is restarting, wait until the container is running So stop the loop first. Turn the restart policy off without deleting anything:
docker update --restart=no orders-api The container stops at its next exit and stays as Exited (1), with its logs. Then start a fresh copy of the same image with a shell instead of the app:
docker run --rm -it --entrypoint sh your-image:tag With Compose, the same idea:
docker compose run --rm --no-deps --entrypoint sh api Inside, run the app's start command by hand and watch it fail. Check env, file paths and permissions.
Why this works: docker update changes only the policy, and --entrypoint sh gives you the exact filesystem and environment the app sees, without the crash.
Why a Docker container keeps restarting: 8 causes and fixes
Cause 1: A missing or wrong environment variable
The classic. The app checks its config at startup and quits.
Error: DATABASE_URL is not set Fix it in compose.yaml:
services: api: image: your-app:1.4.2 restart: unless-stopped environment: DATABASE_URL: postgres://orders:${POSTGRES_PASSWORD}@orders-db:5432/orders Then recreate the container. docker compose restart keeps the old environment; only a recreate picks up the new value:
docker compose up -d --force-recreate api If the value comes from a .env file, check what Compose actually sees with docker compose config. The guide to Docker Compose PostgreSQL environment variables covers the traps with .env, env_file and special characters.
Cause 2: The process finishes (exit code 0)
Restarting (0) means nothing crashed. Your main process simply ended, and always or unless-stopped started it again. Common reasons:
- The image runs a one-off task (a migration, a seed script).
- The command starts a daemon that forks into the background, so PID 1 exits. For example
nginxwithoutdaemon off;, orservice php-fpm start. -
CMD ["sh"]with no terminal attached.
Fix: run the app in the foreground (nginx -g 'daemon off;', php-fpm -F, gunicorn app:app), and give one-off tasks no restart policy:
services: migrate: image: your-app:1.4.2 command: ["npm", "run", "migrate"] restart: "no" With on-failure, a clean exit is final: the container stays Exited (0) and does not loop.
Cause 3: The database isn't ready yet
The app starts before Postgres or Redis accepts connections, fails with ECONNREFUSED or could not connect to server, and loops until the database is up. A plain depends_on: [db] only waits for the database container to start, not for it to be ready. In a stack where the database needed 8 seconds, the API crashed 7 times before it came up.
Fix: give the database a health check and wait for it:
services: orders-db: image: postgres:18-alpine restart: unless-stopped environment: POSTGRES_USER: orders POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD} POSTGRES_DB: orders volumes: - orders-data:/var/lib/postgresql healthcheck: test: ["CMD-SHELL", "pg_isready -U orders -d orders"] interval: 5s timeout: 3s retries: 10 start_period: 10s api: image: your-app:1.4.2 restart: unless-stopped environment: DATABASE_URL: postgres://orders:${POSTGRES_PASSWORD}@orders-db:5432/orders depends_on: orders-db: condition: service_healthy volumes: orders-data: With condition: service_healthy, docker compose up -d waits until the check passes, then starts the API once, with zero restarts. Still make your app retry its first connection for a few seconds: a database can restart later too. More on writing checks that tell the truth in Docker health checks for Postgres and Redis.
Cause 4: The entrypoint can't run (exit 126, 127 or 255)
Three different messages, three different fixes:
| Message | Exit | Fix |
|---|---|---|
exec /entrypoint.sh: no such file or directory (file exists) | 255 | Convert CRLF to LF |
exec: "/entrypoint.sh": permission denied | 126 | Add the execute bit |
exec: "node": executable file not found in $PATH | 127 | Fix the command or the base image |
For CRLF, strip the carriage returns during the build and stop Git from adding them back:
COPY entrypoint.sh /entrypoint.sh RUN sed -i 's/\r$//' /entrypoint.sh && chmod +x /entrypoint.sh ENTRYPOINT ["/entrypoint.sh"] # .gitattributes *.sh text eol=lf For the missing execute bit, set it while copying (BuildKit, the default builder):
COPY --chmod=755 entrypoint.sh /entrypoint.sh Note: with 126 and 127, docker run fails straight away and the container sits in Created; it doesn't loop. The CRLF case does loop, as Restarting (255).
Cause 5: Out of memory (exit 137, OOMKilled=true)
The kernel kills the process when it goes over the container's memory limit:
Status=restarting ExitCode=137 OOMKilled=true RestartCount=6 Raise the limit, or make the app use less. In Compose:
services: api: image: your-app:1.4.2 restart: unless-stopped mem_limit: 512m memswap_limit: 512m Then check real usage with docker stats --no-stream. Exit 137 has more causes than memory (a slow shutdown ends with SIGKILL too), and a restart can reset the OOMKilled flag.
Cause 6: Corrupt or incompatible data in a volume
The image is fine, but the data it finds on the volume isn't. Typical messages: database files are incompatible with server after a Postgres major upgrade, a stale .pid or lock file, or a config written by a newer version. Removing the container doesn't help, because the volume stays.
Fix: read the log line, then either migrate the data properly or start clean. Back up the volume first:
docker run --rm -v yourproject_orders-data:/data -v "$PWD":/backup alpine:3.22 \ tar czf /backup/orders-data.tgz -C /data . Then reset it. This deletes data:
docker compose down docker volume ls docker volume rm yourproject_orders-data docker compose up -d For Postgres upgrades, don't wipe: follow a dump-and-restore instead.
Cause 7: The app is told to stop, crashes natively, or runs on the wrong CPU (139, 143, 255)
- 143: something sent SIGTERM: an orchestrator, a script calling
docker stop, or an app that stops itself. Look for who sends it withdocker events. - 139: a segfault in native code. Update the image or the native library, and check the logs for the last thing the app did.
-
exec format errorin the logs, exit 255: the image was built for another CPU (for example anarm64image on anamd64server). Build for the right platform withdocker buildx build --platform linux/amd64,linux/arm64.
Cause 8: It "keeps restarting after reboot"
This is usually the restart policy doing exactly its job. The four policies behave differently, and the difference shows after a reboot or a Docker restart:
| Policy | Restarts after a crash | Restarts after a clean exit (0) | After docker stop + Docker restart |
|---|---|---|---|
no (default) | No | No | Stays stopped |
on-failure[:N] | Yes, up to N times | No | Stays stopped |
unless-stopped | Yes | Yes | Stays stopped |
always | Yes | Yes | Starts again |
So a container you stopped by hand with always comes back after every reboot. Use unless-stopped for services, and on-failure:5 when you want Docker to give up: after 5 failed restarts the container stays Exited.
docker update --restart=unless-stopped orders-api What Docker does NOT do: restart unhealthy containers
A HEALTHCHECK that fails only marks the container unhealthy. Plain Docker and Docker Compose never restart it for that:
Up 12 seconds (unhealthy) RestartCount=0 So if your container is unhealthy but not restarting, that's expected. If it is restarting, the health check isn't the reason. Only Swarm or another orchestrator replaces unhealthy containers. Check RestartCount: it stays at 0.
One more trap: a slow stop that ends in 137
If your app runs under a shell (CMD npm start or sh -c "node server.js"), the shell is PID 1 and may not pass SIGTERM on. docker stop then waits 10 seconds and kills it, and the container exits with 137, which looks like a memory problem but isn't. Use the exec form (CMD ["node", "server.js"]) or exec in your script, and either handle SIGTERM in the app or add a small init process (init: true in Compose, docker run --init). Many runtimes, Node included, ignore SIGTERM as PID 1 unless the app handles it.
Fix a restart loop on Hubfly space
On Hubfly space, each container's Logs tab shows stdout and stderr from every start in one list, so a loop is easy to spot: the same error line over and over.
- Open the container and click Logs. Read the repeated error.
- Click Configuration. Under Environment Variables, click Edit, then Add Variable, enter the name and value, and click Save Changes. The container starts again with the new value. Trust the Logs tab over the status badge here: during a fast loop the badge can still read Running.
- Back in Logs, the app's startup line appears.
The restart policy lives under Configuration → Process Settings → Restart policy, with the same four choices: Unless stopped (the default), Always, On failure and Never. Pick Never to keep a crashing container stopped while you look into it. Compose stacks keep their healthcheck and depends_on settings and deploy in dependency order. Still make your app retry its first database connection rather than relying on start order alone. And, like Docker, a failing health check doesn't restart a container on its own.
A small always-on container with 0.5 vCPU, 512 MB of RAM and 4 GB of disk costs about $2.23 a month ($1.46 for CPU + $0.73 for RAM + about $0.04 for 4 GB of storage).
What can go wrong
- You fixed the env var, but it still loops. You restarted instead of recreating. Run
docker compose up -d --force-recreate api. -
docker logsis empty. The app logs to a file, not stdout. Point it to stdout, or look in the file from a debug shell (Step 3). -
docker update --restart=no"did nothing". It only changes the policy. Ifdocker psstill showsRestarting, rundocker stop orders-apito stop it now. - You removed the container and it's back. Compose or a systemd unit started it again. Run
docker compose downfrom the project folder. - The container stays in
Created. Docker couldn't start the command at all (exit 126 or 127). See Cause 4. - It restarts only every few minutes. Look at
RestartCountanddocker events: something slow is failing, often memory creeping up (Cause 5) or a health-checking orchestrator.
FAQ
Why does my Docker container keep restarting?
Because its main process keeps exiting and a restart policy (always, unless-stopped or on-failure) starts it again. Find out why the process exits with docker logs and the exit code from docker inspect.
How do I stop a Docker container from restarting?
Run docker update --restart=no <name> to stop the loop and keep the container for debugging, then docker stop <name> if you need it stopped right away. In Compose, set restart: "no" on the service and run docker compose up -d.
Why does my Docker container start and stop immediately?
The command finishes or fails at once. Exit code 0 means it finished (run the app in the foreground). Any other code means it failed; read docker logs. If the container never leaves Created, the command can't be executed at all (exit 126 or 127).
How do I see the logs of a container that keeps restarting?
docker logs --tail 100 <name> works while it's restarting and shows the output of every attempt. Add -f to follow new attempts as they happen.
Why can't I docker exec into a restarting container?
docker exec needs a running process, and a restarting container has none between attempts, so you get "is restarting, wait until the container is running". Start a separate debug copy with docker run --rm -it --entrypoint sh <image> instead.
Does Docker restart unhealthy containers?
No. Docker and Docker Compose only mark the container unhealthy. Only Swarm and other orchestrators act on health status.
What does Restarting (0) mean?
The process exited successfully and the always or unless-stopped policy started it again. Your container ran a short task, or its main process went into the background.
Do containers stop when Docker restarts?
By default, yes: every container stops when the Docker daemon stops (unless live-restore is turned on). When Docker starts again, containers with always come back, unless-stopped ones come back unless you stopped them by hand, and containers with no restart policy stay stopped.
Why do my Docker containers restart after reboot?
They have restart: always or unless-stopped, and Docker starts them when it starts. With always, even containers you stopped by hand come back. Switch to unless-stopped or no with docker update --restart=....
Go further on Hubfly space
- Add health checks that tell the truth. Write checks for your Compose services that fail when the app is broken: see Docker health checks for Postgres and Redis.
- Keep your data across restarts. Mount a named volume so a crash never wipes your database: Volumes docs.
- Watch logs from your terminal.
hubfly logs --follow <id>streams the same logs, with keyword and time filters: Observability docs.
Try it on Hubfly space: deploy your container and keep an eye on every start from one Logs tab.
By Octave · drafted with AI, tested on Hubfly · Last updated 19 November 2026



