When docker ps shows Restarting (1) 12 seconds ago, the number in brackets is the answer to most of the problem. Run docker inspect -f '{{.State.ExitCode}} {{.State.OOMKilled}}' <name> and read it: 0 means the process finished on purpose, 1 means the app crashed and the reason is in docker logs, 125 to 127 mean the container never really started, 137 means something sent SIGKILL (very often the memory limit), 139 is a segmentation fault, and 143 is a polite SIGTERM stop. Fix the cause, then pick a restart policy that gives up instead of looping for ever. The rest of this post is a decision flow through those codes, on a small VDS running one app, one database and not much else.
Why a container restarts in the first place#
A container is one process, the one your image starts as PID 1. When that process exits, the container exits, and the exit code of the process becomes the exit code of the container. Nothing restarts it unless you asked. The restart is done by the Docker daemon, according to the restart policy set on the container. So "keeps restarting" always means two separate facts: the process is dying, and a policy is bringing it back.
That split is the most useful way to debug it. If you only look at the policy, you will fiddle with restart: lines and change nothing. If you only look at the app, you may miss that it exited cleanly and Docker is simply obeying restart: always. Look at both, in this order:
- How is the container being restarted (policy and restart count)?
- Why did the process exit (exit code, logs, OOM flag)?
- Is the host involved (memory, disk, daemon restarts)?
The two posts nearby cover single topics in depth: exit code 137 and out-of-memory kills and Docker health check timing. This one is the map that tells you which of them you need.
The first two minutes: five commands#
Before reading any theory, collect the facts. These commands are read-only and safe on a production box.
$ docker ps -a --format 'table {{.Names}}\t{{.Status}}\t{{.Image}}'$ docker inspect -f 'exit={{.State.ExitCode}} oom={{.State.OOMKilled}} restarts={{.RestartCount}} policy={{.HostConfig.RestartPolicy.Name}}' myapp$ docker logs --tail 100 -t myapp$ docker events --since 30m --filter container=myapp --filter event=die$ dmesg -T | grep -i -E 'killed process|out of memory' | tailWhat each one tells you:
docker ps -aincludes stopped containers.Restartingmeans the daemon is in the delay between attempts;Up 3 secondsfor a container that should have been up for days means it just came back.- The
inspectline is the one to paste into a support ticket or a chat.exitis the last exit code,oomis whether Docker saw the kernel kill the container for memory,restartsis how many times the daemon has restarted it, andpolicyis what is doing the restarting. docker logskeeps output across restarts of the same container, so the tail shows the last crash and the ones before it. The-tflag adds timestamps, which is how you tell a crash that happens 2 seconds after start from one that happens after an hour. If you recreate the container (docker compose up -d --force-recreate, ordocker rm), that history is gone, so read the logs first.docker eventsprints onedieevent per exit with anexitCodeattribute, which is the cleanest way to see the pattern of a loop over time.dmesgshows what the kernel itself did. A line such asOut of memory: Killed process 2314 (node)is the proof for exit 137 caused by memory. You may needsudo, and on systemd hostsjournalctl -kshows the same.
Once you have the exit code, the flow below picks the section to read.
Exit code 0: it finished, and Docker started it again#
Code 0 is not a crash. The process did its work and returned success. A container restarts after 0 only if the policy is always or unless-stopped, so the loop is your own policy meeting a process that was never meant to run for ever. The usual culprits:
- A one-shot job given a service policy. A migration, a seed script or a cron-style task finishes in two seconds, and
restart: alwaysruns it again every few seconds. Give jobsrestart: "no"oron-failure. - A process that forks into the background. A command like
service myapp startor a daemon that detaches returns at once, PID 1 exits with0, and the container ends while the real process is orphaned and killed. Run the program in the foreground (nginx -g 'daemon off;',--no-daemon, whatever flag your program uses). - A shell script that ends. An
entrypoint.shthat sets things up and then does notexecthe application will exit when the script reaches its last line. - A development server with no terminal. Some tools exit immediately when stdin is closed. If it works with
docker run -itand exits with-d, that is the clue.
The fix is to decide what the container is: a long-running service, which must stay in the foreground in PID 1, or a job, which should be allowed to finish. In a shell entrypoint, end with exec "$@" so the application replaces the shell and receives signals directly.
Exit code 1: the application crashed#
Code 1 is the generic failure. Docker did nothing wrong, the program started and then raised an uncaught error, so the answer is in the last lines of docker logs. The failures that account for most small-server loops are boring and repeatable:
| Log line | Usual cause |
|---|---|
ECONNREFUSED / connection refused | The database is not ready or the host name is wrong |
EADDRINUSE / address already in use | Two processes on one port, or the port is taken inside the container |
Cannot find module / ModuleNotFoundError | The image was built without a dependency, or a volume hides node_modules |
permission denied | The container user cannot write to a mounted volume |
missing required environment variable | An .env file was not passed to the container |
A few of these deserve more than a table row.
Database not ready. On a stack with an app and a database, the app often starts a second or two before the database accepts connections. The app exits with 1, Docker restarts it, and the second attempt works. This "works by accident" setup is fragile: it hides the race behind a restart and writes a scary line into your logs on every boot. Make the dependency explicit with a health check on the database and depends_on with condition: service_healthy, or give the app a short retry loop on its own connection. The Compose side is in Docker Compose for small stacks.
Environment that exists on your laptop only. docker run does not read your shell's variables or a .env file unless you pass --env-file .env or -e NAME. In Compose, env_file: or environment: does it. If the error names a variable, run docker exec into a running copy (or docker run --rm --env-file .env image env) and check what the container actually sees.
Volumes that shadow the build. A bind mount such as ./:/app replaces everything the image put in /app, including installed dependencies. The container then crashes with a missing-module error even though the image is fine. Mount only the data directory.
Permissions. If the image runs as a non-root user and a named volume or bind mount is owned by root, writes fail and many apps exit with 1. docker exec myapp id shows the user; ls -ln on the host path shows the numeric owner.
If the logs are empty, the crash happens before your app logs anything. Start a shell in the same image with the entrypoint replaced and run the command by hand, where you can see the error:
$ docker run --rm -it --entrypoint sh myimage:latest$ docker run --rm -it --env-file .env --entrypoint sh myimage:latestExit codes 125, 126 and 127: it never really started#
These three have a different meaning from application codes: they come from Docker and the shell that launches your command, not from your program.
| Code | Meaning | Typical message |
|---|---|---|
125 | The Docker daemon itself failed to run the container | port is already allocated, Conflict. The container name is already in use, an unknown flag |
126 | The command was found but cannot be executed | permission denied, not executable |
127 | The command was not found | executable file not found in $PATH |
125 shows up on docker run when the problem is in the request, before any of your code runs. The common message on a VDS is Bind for 0.0.0.0:80 failed: port is already allocated. Something else owns the port: another container, or a web server running on the host. ss -ltnp | grep ':80 ' shows who. A container with a restart policy that fails this way can sit in a loop of failed starts, which is why the policy is not a substitute for reading the first error.
126 means the file exists but the kernel refused to run it. The classic: a script copied into the image without the executable bit. Fix it in the build with RUN chmod +x /entrypoint.sh or COPY --chmod=755, or call the interpreter explicitly (CMD ["sh", "/entrypoint.sh"]).
127 means the shell or runtime could not find the program. Typos in CMD, a binary that exists in your build stage but was not copied into the final stage of a multi-stage build, or a minimal image (scratch, distroless) with no sh while your command assumes one. Check with docker run --rm --entrypoint sh image -c 'command -v myprogram', or inspect the final stage of the Dockerfile.
There is one trap that looks like 127 and is not obvious: exec ./entrypoint.sh: no such file or directory, when the file is plainly there. The usual cause is Windows line endings (CRLF) in the script, so the interpreter named on the first line is /bin/sh\r, which does not exist. Convert the file to LF (dos2unix, or fix the editor setting and a .gitattributes rule). A related message, exec format error, means the binary was built for a different CPU architecture than the host, for example an ARM image on an x86 server; build or pull the image for the right platform.
Exit code 137: SIGKILL, and why it is not always memory#
Exit codes above 128 follow one rule: the process was ended by a signal, and the code is 128 plus the signal number. 137 is 128 + 9, signal SIGKILL, which a process cannot catch or clean up after. Three different things send it:
- The kernel's OOM killer. The container hit its memory limit (or the host ran out) and the kernel picked a process.
docker inspectshowsOOMKilled=true, anddmesgshows aKilled processline. This is the most common source on a small server. - `docker kill`, or `docker stop` that ran out of patience.
docker stopsendsSIGTERM, waits 10 seconds by default, then sendsSIGKILL. An app that ignoresSIGTERMis therefore reported as 137 on every stop and on every redeploy. In that caseOOMKilledisfalse. - Something else on the host, such as a script, a monitoring tool or you.
So 137 plus oom=true is memory; 137 plus oom=false and a stop in the events log is a shutdown problem (see 143 below). If it is memory, the quick work is: look at docker stats --no-stream to see how close to the limit the app runs, cap the runtime's own heap below the container limit, and look for growth over time. The settings per runtime are in the exit code 137 post, and the host side, swap and why the kernel kills instead of waiting, in swap and the OOM killer.
Two details that matter on a small VDS. First, a container with no --memory limit can use all the host's memory and take the database or SSH down with it, so a limit on each container turns "the whole server froze" into "one container restarted". Second, a limit set below what the app needs at startup produces a loop that looks like a crash at the same second every time: the app dies while loading, restarts, loads, dies. A restart count that climbs with an uptime of two or three seconds is that pattern.
Exit code 139: segmentation fault#
139 is 128 + 11, SIGSEGV. The process touched memory it did not own. Unlike 1, there is usually no stack trace and no log line, because the process died instantly. Your own JavaScript, Python or Go code will rarely cause it. The causes are lower down:
- A native extension or addon. Node native modules, Python wheels with compiled code (image processing, database drivers, cryptography) and similar. A binary built against one C library and run on another can crash on load.
- Alpine versus glibc. Alpine images use musl instead of glibc. A prebuilt binary that expects glibc may segfault or fail to start on Alpine, and the reverse is rarer. If you build or install native dependencies, build and run on the same base image, or switch to a Debian-slim base to test.
- CPU architecture or instruction set mismatches, including images running under emulation. This is more common on a developer's laptop than a VDS, but a binary compiled with instructions your CPU lacks will crash with
SIGILL(code132) orSIGSEGV. - Failing RAM or a very unlucky kernel. Rare, and you should rule out every software cause first.
The practical approach: change one variable at a time. Try the previous image tag, a different base image, a different version of the suspected native package. If you have a reproducible crash, a core dump or strace -f is the next step, but most small-server cases end at "wrong base image" or "bad native build".
Exit code 143: SIGTERM, a normal stop#
143 is 128 + 15, SIGTERM, the polite request to shut down that docker stop, docker compose down and a system reboot send. Exiting with 143 after a stop you asked for is normal, not a fault. It is a problem in two cases.
It restarts after you stopped it. docker stop marks the container as stopped by you, and on-failure, always and unless-stopped all respect that until the daemon restarts. If it came back by itself, something else started it: Compose's up, a cron job, a deploy hook, or always after a daemon or server reboot (more in the next section).
The stop takes ten seconds and ends in 137. That is the app not handling SIGTERM. The most common reason is that your application is not PID 1. If the image uses the shell form CMD npm start or CMD python app.py, Docker runs it through /bin/sh -c, the shell is PID 1, and it does not pass the signal on. Use the exec form, a JSON array:
# shell form: sh is PID 1 and the signal does not reach the appCMD npm start# exec form: the app receives SIGTERM directlyCMD ["node", "server.js"]If you need an init that forwards signals and reaps zombie processes, docker run --init or init: true in Compose adds a tiny one. Also give a slow app a longer grace period with docker stop -t 30 or stop_grace_period: 30s, and handle SIGTERM in code to finish in-flight requests and close the database connection. The reasoning, with health endpoints, is in graceful shutdown and health checks.
Restart policies and their pitfalls#
Docker has four policies. Set one explicitly; the default is no.
| Policy | Restarts when | Survives daemon restart |
|---|---|---|
no | Never | No |
on-failure[:max] | Exit code is not 0, up to max times | Yes, if it was running |
always | Any exit | Yes, even if you stopped it |
unless-stopped | Any exit, unless you stopped it | Yes, only if not stopped by you |
In Compose, the line is restart: unless-stopped (quote "no", because an unquoted no is parsed as the boolean false by YAML). On the command line it is --restart unless-stopped. For an existing container, docker update --restart=on-failure:5 myapp changes it without recreating.
The pitfalls, in the order they cost people time:
`always` hides a loop. A container that crashes every two seconds and is restarted every two seconds looks "up" to anything that polls it, and docker ps flips between Up and Restarting. Docker adds a growing delay between attempts (it starts small and doubles up to a cap of about a minute), so the CPU cost of the loop shrinks, but the logs fill and the service is still down. Check RestartCount after any incident.
A policy only counts after a successful start. Docker documents that the policy takes effect once the container has been up for a short period (about 10 seconds), so a container that dies immediately is handled by the daemon's startup backoff rather than being instantly respawned. Either way: do not count on a restart policy to rescue something that cannot start.
`on-failure` never restarts exit 0, and `max` resets. Use on-failure:5 for services where giving up is better than looping: the container ends up Exited (1), the loop stops, and the logs of the last run are still there. That is a better state to find on Monday morning than a container which has restarted 40,000 times.
`unless-stopped` versus `always`. After a server reboot, unless-stopped brings back what was running; a container you deliberately stopped stays stopped. always brings it back even if you stopped it. On a VDS you maintain by hand, unless-stopped is the least surprising choice for services, and no for tools you run on demand.
A restart is not a health check. A hung app that is not exiting is never restarted by the policy. A container marked unhealthy by its HEALTHCHECK also keeps running; plain Docker takes no action on health status. The detail is in the health check post. To restart a hung app, use a health check plus a small watcher, or an orchestrator, or run the service under systemd (see systemd services for your apps).
Restart loops can fill the disk. The default json-file logging driver does not rotate logs unless you configure it. A crash loop that prints a long stack trace on every start can write a surprising amount in a day on a small disk. Set limits per service:
services: app: image: myapp:1.4.2 restart: on-failure:5 mem_limit: 512m logging: driver: json-file options: max-size: "10m" max-file: "3"The same max-size and max-file options can be set for every container in /etc/docker/daemon.json (they apply to containers created afterwards, so recreate the existing ones). Check df -h and docker system df if the server feels tight.
A worked example: three restarts, three different causes#
Suppose a VDS runs a Node API, a PostgreSQL container and a small worker. After a deploy, docker ps shows the API as Restarting (1). Walk the flow.
docker inspecton the API saysexit=1 oom=false restarts=14. Exit 1, not memory.docker logs --tail 50 -t apiends withError: connect ECONNREFUSED 172.18.0.2:5432about two seconds after each start. The database is slower than the app. The fix is a health check ondb(pg_isready),depends_on: db: condition: service_healthyon the API, andrestart: on-failure:5so the loop is bounded.- The worker shows
Exited (0) 3 seconds agoand keeps coming back. It is a batch job withrestart: always. Change it torestart: "no"and start it from a timer or cron. - A week later the API is
Exited (137)withoom=trueevery few days.docker statsshows memory creeping up and the limit was never set. Cap the heap, setmem_limit, and schedule a restart if you cannot fix the leak yet. Restart schedules are a legitimate stopgap when they are planned, as restart schedules that help argues, but a stopgap is not a fix.
Each of the three had the same symptom in docker ps and three different causes, and each was named by one number plus one log line.
Where to run this, and what a small VDS can carry#
A restart loop on a shared or tiny machine is a memory and disk problem more often than a code problem, so the host's size matters. A box with 1 GB of memory running Docker, a database and an app is one traffic spike away from exit 137. As a rough guide, leave Docker itself and the OS a few hundred megabytes, give the database what it needs, cap the app below the remainder, and keep some swap as a safety margin (not as capacity - see the swap post above).
If you want the full Docker experience with your own daemon, restart policies, Compose and root access, that is what a VDS is for. RE:NODE's VDS plans start from $17 a month with 8 GB of memory, and the VDS page in the panel shows live CPU, memory, disk, swap and load, which is the quickest way to see whether a container restart lines up with a memory peak. VDS servers are prepared by hand, within 24 hours of payment. If you would rather not run Docker at all, a plain Node, Python or .NET app on app hosting runs without a daemon to maintain: at the memory limit the container is stopped and restarts clean, and three restarts in an hour raise a warning on the server page. If you are starting from scratch with Docker on a VDS, begin with Docker on a VDS: getting started.
The same reading habits carry over to games. Why your game server keeps restarting covers the equivalent questions for a panel-managed server: exit versus crash, schedules, memory.
FAQ#
Why does my Docker container keep restarting?
Because the process in it keeps exiting and the restart policy keeps starting it again. Find the exit code with docker inspect -f '{{.State.ExitCode}}' <name> and the reason in docker logs --tail 100 <name>. Code 1 is an app error, 137 is usually memory, 0 is a job that finished.
What does exit code 137 mean in Docker?
The process was killed by SIGKILL (128 + 9). If docker inspect shows OOMKilled=true, the container hit its memory limit. If it is false, the container was killed by docker kill or by docker stop after the 10-second grace period ran out.
What does exit code 143 mean?
The process ended after SIGTERM (128 + 15), the signal docker stop sends. After a stop you requested it is normal. If every stop takes ten seconds and ends in 137, your app is not receiving or handling the signal; use the exec form of CMD or init: true.
How do I stop a container restart loop?
Run docker update --restart=no <name> (or docker stop), then read the logs and fix the cause. To keep the policy but bound it, use on-failure:5. In Compose, change restart: and run docker compose up -d.
Should I use always or unless-stopped?
For long-running services, unless-stopped: containers return after a reboot, but one you stopped on purpose stays stopped. Use on-failure:N where you would rather the container give up after N attempts than loop. Use no for one-off jobs.
Does a restart policy fix an unhealthy container?
No. A health check only sets a status; plain Docker does not restart a running container for being unhealthy. A policy acts only when the process exits.


