Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 111 Β· Containers in Depth

The Container Lifecycle

Understand every Docker container state: created, running, paused, exited, restarting. Learn create, start, stop, kill, pause, rm and restart policies with real output.

So far you have used docker run as one magic command. Under the hood, a container passes through a series of states, and every Docker command either moves it from one state to another or reports which state it is in. Once you know that map, many puzzling things become obvious: why a stopped container still exists and still uses disk space, why docker rm sometimes refuses, what Exited (137) means, and how a restart policy brings a crashed service back.

This lesson walks through the full lifecycle with a real container, then covers restart policies, which are the lifecycle's built-in self-healing. Everything below was run on Docker Engine 29.8.

The states at a glance

TEXT
                        docker create
                              |
                              v
                         [ created ]
                              |  docker start
                              v
   docker unpause     [ running ]  <----------------+
        ^   |   docker pause |  |                  |
        |   v                |  |   restart policy  |
     [ paused ] <------------+  |   kicks in        |
                                |                  |
                 exit / stop / kill                |
                                v                  |
                          [ exited ] --------------+
                                |  docker rm
                                v
                            (deleted)

Docker reports the state in docker ps (the STATUS column) and in docker inspect (.State.Status). The values you will meet:

State Meaning
created The container exists (filesystem prepared, config stored) but its main process has never started
running The main process (PID 1 inside) is alive
paused All processes are frozen in place but still in memory
restarting The process exited and the restart policy is waiting to start it again
exited The main process ended; the container's filesystem and logs are still there
removing, dead Transitional or failed-removal states you rarely see

A container is not "gone" when it stops. It is only gone after docker rm. That is a core idea: a stopped container is a record on disk.

created: docker create

docker run is really two steps, create and start, rolled into one (plus an automatic pull if the image is missing). You can do the steps separately:

CONSOLE
$ docker create --name tcd-life alpine:3.22 sh -c 'echo started; sleep 300'
8cb5d1efdf1e...
$ docker ps -a --filter name=tcd-life --format 'table {{.Names}}\t{{.Status}}\t{{.Command}}'
NAMES         STATUS    COMMAND
tcd-life      Created   "sh -c 'echo started…"
$ docker inspect -f '{{.State.Status}} running={{.State.Running}} started={{.State.StartedAt}}' tcd-life
created running=false started=0001-01-01T00:00:00Z

Notice that docker ps without -a would not even list it, because nothing is running. The zero timestamp 0001-01-01... is Docker's way of saying "never started". Why would you separate the steps? To prepare a container (for example copy a file in with docker cp) before it starts, or to define containers up front and start them later in a chosen order.

running: docker start

CONSOLE
$ docker start tcd-life
tcd-life
$ docker ps --filter name=tcd-life --format 'table {{.Names}}\t{{.Status}}'
NAMES      STATUS
tcd-life   Up 1 second
$ docker logs tcd-life
started

docker start runs the stored command again; a container remembers its image, command, environment, ports and mounts from create. You can start a stopped container as often as you like, and its writable layer (changes you made to files) is still there. Only docker rm discards it.

A container is "running" as long as its main process (PID 1) is alive. When that process exits, so does the container. This surprises beginners who start an image with a command that finishes immediately, like echo hi: the container flashes through running and lands in exited.

paused: docker pause and unpause

pause uses a kernel feature (the cgroup freezer) to freeze every process in the container without terminating it. Memory stays allocated and network connections stay open, but the processes get no CPU time.

CONSOLE
$ docker pause tcd-life
tcd-life
$ docker ps --filter name=tcd-life --format '{{.Names}} {{.Status}}'
tcd-life Up 3 seconds (Paused)
$ docker inspect -f '{{.State.Status}} paused={{.State.Paused}}' tcd-life
paused paused=true
$ docker unpause tcd-life
tcd-life
$ docker inspect -f '{{.State.Status}}' tcd-life
running

Pause is useful for taking a consistent snapshot (such as a docker commit or file copy) of a busy container, or for temporarily freeing CPU. It is not a way to save memory; for that, stop the container. Note that it shows up in docker ps as part of the Up status.

exited: stop, kill and the exit code

There are three ways a running container ends: its process exits on its own, you ask it to stop politely (docker stop), or you force it (docker kill).

docker stop sends SIGTERM to PID 1, waits for a grace period, and then sends SIGKILL. The grace period is controlled by -t:

CONSOLE
$ docker run -d --name tcd-life alpine:3.22 sleep 300
$ time docker stop -t 10 tcd-life
real	0m10.749s
$ docker inspect -f '{{.State.Status}} exit={{.State.ExitCode}} oom={{.State.OOMKilled}}' tcd-life
exited exit=137 oom=false

It took the full ten seconds and ended with exit code 137. Why? sleep is PID 1 here, and Linux does not apply default signal actions to PID 1: a process running as PID 1 ignores SIGTERM unless it installs a handler. So Docker waited, gave up, and sent SIGKILL. The exit code of a process killed by a signal is 128 + signal number, and SIGKILL is signal 9, hence 128 + 9 = 137. (On my Docker Desktop, plain docker stop without -t finished in about four seconds and also ended with 137; the default timeout is a daemon setting, so use -t when timing matters.)

Compare that with a program that handles the signal:

CONSOLE
$ docker run -d --name tcd-trap alpine:3.22 sh -c 'trap "echo got TERM; exit 0" TERM; sleep 300 & wait'
$ time docker stop tcd-trap
real	0m0.980s
$ docker inspect -f '{{.State.ExitCode}}' tcd-trap
0
$ docker logs tcd-trap
got TERM

The shell's trap caught SIGTERM, printed a message, and exited with code 0 in about one second. That is a graceful shutdown: closing connections, flushing data. Signals, PID 1 and --init goes deep on how to make your own services behave like this.

docker kill skips politeness: it sends SIGKILL right away (or any signal you choose with -s).

CONSOLE
$ time docker kill tcd-life
real	0m1.403s

Common exit codes to recognize:

Code Usual meaning
0 The program finished successfully
1 to 125 The program's own error codes
126, 127 Command not executable / command not found
137 Killed by SIGKILL (128 + 9): docker kill, a timed-out docker stop, or the out-of-memory killer
143 Ended by SIGTERM (128 + 15)

To find out why a container stopped, look at .State.ExitCode and .State.OOMKilled (true when the kernel killed it for exceeding its memory limit; see Resource Limits). docker wait blocks until a container exits and prints the code:

CONSOLE
$ docker run -d --name tcd-w alpine:3.22 sh -c 'sleep 2; exit 7'
$ docker wait tcd-w
7

You can start an exited container again with docker start, or restart one in a single step:

CONSOLE
$ docker restart -t 1 tcd-life
tcd-life
$ docker inspect -f 'restarts={{.RestartCount}} status={{.State.Status}}' tcd-life
restarts=0 status=running

Note that docker restart (a manual stop plus start) does not count toward RestartCount; that counter belongs to the restart policy.

removed: docker rm

CONSOLE
$ docker rm tcd-life
Error response from daemon: cannot remove container "tcd-life": container is running: stop the container before removing or force remove
$ docker rm -f tcd-life
tcd-life

docker rm deletes a stopped container together with its writable layer and its logs. It refuses to remove a running container; -f stops it (with SIGKILL) and removes it in one go. Named volumes survive rm; anonymous volumes are removed only if you add -v. For throwaway work, avoid the whole dance by passing --rm to docker run, which deletes the container automatically when it exits.

A stopped container also holds its name. Reusing a name that still exists gives a classic error:

CONSOLE
$ docker run --name tcd-w2 alpine:3.22 true
$ docker run --name tcd-w2 alpine:3.22 true
docker: Error response from daemon: Conflict. The container name "/tcd-w2" is already in use by container "cf2e371d5107...". You have to remove (or rename) that container to be able to reuse that name.

Fix it with docker rm tcd-w2, docker rename, or --rm next time. Over time exited containers pile up, so also see Cleaning Up.

Watching state changes with docker events

The daemon publishes an event for every transition. Run docker events in one terminal and the commands in another:

CONSOLE
$ docker events --filter container=tcd-life --format '{{.Action}}'
create
start
pause
unpause
kill
kill
stop
die
destroy

These are the events for: create, start, pause, unpause, then docker stop -t 1 (two kill events, the SIGTERM and then the SIGKILL after the grace period, followed by stop and die), then rm. Tools such as monitoring agents and reverse proxies subscribe to this same stream.

Restart policies: automatic recovery

By default a container that exits stays exited. A restart policy tells the daemon to start it again. Set it with --restart on docker run or restart: in Compose (Services in Compose).

Policy Behavior
no (default) Never restart
on-failure[:max] Restart only if the exit code is non-zero, at most max times if given
always Always restart, whatever the exit code; also starts when the daemon starts
unless-stopped Like always, except a container you stopped manually stays stopped, even after a daemon restart

on-failure

A container that always crashes, with a limit of three retries:

CONSOLE
$ docker run -d --name tcd-rf --restart on-failure:3 alpine:3.22 sh -c 'echo crash; exit 2'
$ docker ps -a --filter name=tcd-rf --format '{{.Names}} | {{.Status}}'
tcd-rf | Exited (2) 9 seconds ago
$ docker inspect -f 'status={{.State.Status}} restarts={{.RestartCount}} exit={{.State.ExitCode}} policy={{.HostConfig.RestartPolicy.Name}}:{{.HostConfig.RestartPolicy.MaximumRetryCount}}' tcd-rf
status=exited restarts=3 exit=2 policy=on-failure:3
$ docker logs tcd-rf | wc -l
4

One initial run plus three restarts produced four log lines ("crash"), and then Docker gave up and left the container exited. Between attempts Docker waits with an exponential back-off, starting at 100 ms and doubling up to a limit of one minute, so a crash-looping container does not eat the CPU.

always, and what restarting looks like

CONSOLE
$ docker run -d --name tcd-always --restart always alpine:3.22 sh -c 'echo hi; exit 0'
$ docker ps -a --filter name=tcd-always --format '{{.Status}}'
Restarting (0) 1 second ago
$ docker inspect -f 'restarts={{.RestartCount}}' tcd-always
restarts=6

Even a program that exits successfully is restarted again and again; after six seconds the counter had reached six. The status Restarting (0) 1 second ago is the restarting state: the container is waiting out its back-off delay. Use always for services that should never be down, never for one-shot jobs.

unless-stopped, and the manual-stop rule

CONSOLE
$ docker run -d --name tcd-us --restart unless-stopped alpine:3.22 sh -c 'sleep 2; exit 1'
$ sleep 8; docker inspect -f 'restarts={{.RestartCount}} state={{.State.Status}}' tcd-us
restarts=3 state=running
$ docker stop tcd-us
$ docker inspect -f 'restarts={{.RestartCount}} state={{.State.Status}}' tcd-us
restarts=3 state=exited

It crashed and was revived three times in eight seconds. After docker stop the container stayed down, which is the difference from always: the policy respects your intention. In my test even docker kill on a container with unless-stopped was treated as a manual stop and left it exited, so you do not have to worry about killing a policy-managed container and seeing it reappear.

You can change the policy of an existing container without recreating it:

CONSOLE
$ docker update --restart unless-stopped tcd-life
tcd-life
$ docker inspect -f '{{.HostConfig.RestartPolicy.Name}}' tcd-life
unless-stopped

A restart policy is not a substitute for fixing crashes. A container that restarts forever hides a bug, fills your logs and may repeat a damaging action (a half-finished database migration) on every start. Combine policies with a health check, look at RestartCount, and alert when it climbs.

Choosing a policy

Workload Policy
One-off command, script, test run no with --rm
Batch job that may fail transiently on-failure:5
Web app, API, worker on a single host unless-stopped
Infrastructure that must always run, even after manual stops always
Under Kubernetes or Swarm Leave no; the orchestrator restarts things (Why Orchestration?)

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. You run docker create --name web nginx:alpine. In which state is the container, and does docker ps (without -a) list it?

    docker create prepares the container but never starts its main process. It is in the created state, and docker ps without -a shows only running containers.
  2. 2. docker stop took exactly its full timeout and the container ended with exit code 137. What most likely happened?

    137 = 128 + 9, SIGKILL. A process that is PID 1 and has no SIGTERM handler ignores the signal, so Docker kills it after the grace period.
  3. 3. What is the difference between the always and unless-stopped restart policies?

    Both restart crashed containers. unless-stopped honors a manual docker stop, while always brings the container back when the daemon restarts.
  4. 4. A container with --restart on-failure:3 always exits with code 2. How many times does its main process run in total?

    on-failure:3 allows three restarts after the initial run, and the log in the lesson shows four lines of output. After that the container stays exited.
  5. 5. What does docker pause do?

    pause uses the cgroup freezer. The processes stay in memory but get no CPU time until docker unpause.

Summary

  • A container moves through created, running, paused, restarting and exited; it is only deleted by docker rm (or --rm).
  • docker run is create plus start; the container runs as long as its main process lives.
  • docker stop sends SIGTERM, waits the grace period (-t), then SIGKILL; docker kill sends SIGKILL at once. Exit code 137 means SIGKILL (128 + 9).
  • docker wait, docker inspect -f '{{.State...}}' and docker events show how and why a container changed state.
  • A stopped container keeps its name, writable layer and logs, so reuse of a name fails until you remove or rename it.
  • Restart policies (no, on-failure[:n], always, unless-stopped) restart with exponential back-off; change one later with docker update --restart.

Next: Configuring Containers