Stopping and restarting

How a container receives a signal and why it sometimes waits ten seconds.

A container has several states: created, running and exited. A container runs exactly as long as its main process runs. When the program finishes, the container stops too, with the same exit code. That is why a container with the command echo hello lives for a fraction of a second, and that is normal.

docker stop stops a container politely. First the main process receives SIGTERM and has time to close connections and finish writing data. If the process has not finished after 10 seconds, Docker sends SIGKILL, which cannot be caught. The timeout is changed with the -t flag. docker kill sends SIGKILL immediately without waiting, and data held in the process's memory is lost.

docker stop web
docker stop -t 30 worker
docker start web
docker restart web

docker start starts a stopped container with the same writable layer, name and settings: everything the program wrote to files inside the container is kept until docker rm.

To bring a service back after a crash or a server reboot, you set a restart policy: --restart on-failure restarts only on a non-zero exit code, --restart unless-stopped always restarts except when the container was stopped by hand, and --restart always restarts no matter what. Services usually get unless-stopped.

A common mistake is an application that does not handle SIGTERM. Every stop then takes exactly 10 seconds and ends with SIGKILL, and unwritten data is lost. If docker stop always takes 10 seconds for you, check whether your program is the one receiving the signal: the lesson on CMD and ENTRYPOINT covers this.

Practice

  1. Order of signals

    What does docker stop do to the container's main process?

    • Sends SIGKILL immediately
    • Sends SIGTERM, then SIGKILL after 10 seconds
    • Pauses the process without ending it
    • Removes the container together with its data
  2. Restart policies

    Which statements about restart policies are true? Mark all.

    • on-failure restarts the container only on a non-zero exit code
    • unless-stopped does not bring back a container that was stopped by hand
    • Without the --restart flag Docker restarts a crashed container by itself
    • The policy is set with the --restart flag
  3. The waiting time

    How many seconds does docker stop wait by default after SIGTERM before sending SIGKILL? Answer with a number.