TExcelTAD
Home › Docker › Container Lifecycle

Container Lifecycle

docker run hides the fact that a container goes through several states. Knowing them helps you understand what docker ps -a shows, why a name is "already in use", and what an exit code like 137 means.

text
           docker create            docker start
  (image) ───────────────> created ─────────────> running ──┐ docker pause
                                                    │  ▲     ▼
                              docker stop / kill /  │  │   paused
                              process exits         │  │     │ docker unpause
                                                    ▼  │ <───┘
                                                  exited ── docker start ──> running
                                                    │
                                          docker rm ▼
                                                 (removed)

The commands

Command Effect
docker create --name web nginx:1.27 create the container (writable layer + config) but do not start it
docker start web start a created or exited container
docker run ... create + start (+ attach) in one step
docker stop web send SIGTERM, wait 10 s (-t to change), then SIGKILL
docker kill web send SIGKILL immediately (or another signal with -s)
docker restart web stop + start
docker pause / unpause freeze / thaw all processes (cgroup freezer)
docker rm web delete a stopped container; -f stops it first

A stopped container still exists: its writable layer, logs and configuration are kept until you docker rm it. That's why you can docker start it again with its files intact, and why its name stays reserved.

A state-machine model

The model enforces the same transitions as the engine and prints Docker-like errors for invalid ones.

python · try it yourself
TRANSITIONS = {
    ("created", "start"): "running",
    ("running", "stop"): "exited",
    ("running", "kill"): "exited",
    ("running", "pause"): "paused",
    ("paused", "unpause"): "running",
    ("paused", "stop"): "exited",      # Docker thaws a paused container, then stops it
    ("exited", "start"): "running",
    ("created", "rm"): "removed",
    ("exited", "rm"): "removed",
    ("running", "start"): "running",   # already running: nothing to do
    ("exited", "stop"): "exited",      # already stopped: nothing to do
}

def error(state, command):
    if command == "rm" and state in ("running", "paused"):
        return f"cannot remove container \"web\": container is {state}: stop the container before removing or force remove"
    if command == "pause":
        return "container web is not running"
    if command == "unpause":
        return "container web is not paused"
    return f"cannot {command} a {state} container"

state = "created"
print("docker create --name web nginx:1.27 ->", state)
for command in ["start", "pause", "rm", "unpause", "stop", "stop", "pause", "start", "kill", "rm", "start"]:
    if state == "removed":
        print(f"docker {command:<8} -> Error: No such container: web")
    elif (state, command) in TRANSITIONS:
        state = TRANSITIONS[(state, command)]
        print(f"docker {command:<8} -> {state}")
    else:
        print(f"docker {command:<8} -> Error: {error(state, command)}")
docker create --name web nginx:1.27 -> created
docker start    -> running
docker pause    -> paused
docker rm       -> Error: cannot remove container "web": container is paused: stop the container before removing or force remove
docker unpause  -> running
docker stop     -> exited
docker stop     -> exited
docker pause    -> Error: container web is not running
docker start    -> running
docker kill     -> exited
docker rm       -> removed
docker start    -> Error: No such container: web

Exit codes tell you why it stopped

When a container's main process ends, its exit code is shown in docker ps -a (Exited (137) 5 minutes ago). Codes above 128 mean "killed by signal number code − 128".

python · try it yourself
import signal

def explain(code):
    if code == 0:
        return "finished successfully"
    if code == 125:
        return "docker run itself failed (bad flag, name in use, ...)"
    if code == 126:
        return "the command could not be executed (permission problem, not executable)"
    if code == 127:
        return "command not found inside the image"
    if code > 128:
        sig = signal.Signals(code - 128)
        hint = {"SIGKILL": "docker kill, stop timeout, or the out-of-memory killer",
                "SIGTERM": "docker stop, and the app exited on SIGTERM",
                "SIGSEGV": "the program crashed (segmentation fault)"}.get(sig.name, "")
        return f"killed by {sig.name} ({code} - 128 = {code - 128}): {hint}"
    return "the application exited with an error"

for code in [0, 1, 125, 127, 137, 143, 139]:
    print(f"Exited ({code}): {explain(code)}")
Exited (0): finished successfully
Exited (1): the application exited with an error
Exited (125): docker run itself failed (bad flag, name in use, ...)
Exited (127): command not found inside the image
Exited (137): killed by SIGKILL (137 - 128 = 9): docker kill, stop timeout, or the out-of-memory killer
Exited (143): killed by SIGTERM (143 - 128 = 15): docker stop, and the app exited on SIGTERM
Exited (139): killed by SIGSEGV (139 - 128 = 11): the program crashed (segmentation fault)

137 deserves special attention: if you didn't kill the container yourself, check docker inspect --format '{{.State.OOMKilled}}' web. A true means it hit its memory limit (see Resource Limits).

Seeing and cleaning up containers

bash
docker ps                      # running containers
docker ps -a                   # all, including exited
docker ps -a --filter status=exited --format '{{.Names}}\t{{.Status}}'
docker container prune         # remove all stopped containers
docker run --rm alpine true    # auto-remove when it exits

Sample output:

text
CONTAINER ID   IMAGE        COMMAND                  STATUS                       NAMES
8b1f0c2d3e4a   nginx:1.27   "/docker-entrypoint.…"   Up 12 minutes                web
c4d5e6f7a8b9   alpine       "sh -c 'exit 3'"         Exited (3) 2 minutes ago     job-3

Tip: for one-off tasks (docker run alpine ..., build tools, migrations), always add --rm. Without it, every run leaves a stopped container behind.

Test yourself

What is the difference between docker stop and docker kill?

  1. There is none
  2. stop sends SIGTERM and waits before SIGKILL; kill sends SIGKILL right away
  3. kill also deletes the container
  4. stop pauses the container

A container shows Exited (137). What is the most likely cause?

  1. The app returned 137 from main()
  2. It was killed with SIGKILL (137 = 128 + 9), e.g. by docker kill, a stop timeout or the OOM killer
  3. The image is missing
  4. A network error

You stopped a container named web. Why does docker run --name web ... fail?

  1. Names can only be used once per day
  2. The stopped container still exists and keeps its name until you remove it
  3. You must use docker restart
  4. The image was deleted