Sub topic 5
Stopping containers
This chapter covers how to stop running containers with docker stop. It assumes you have Docker installed with the daemon running and are comfortable at a command line. It also assumes you know that an image is a template and a container is a running or stopped instance of one. You should have met docker ps in the previous chapters, because every example here uses it to check results.
What stopping means
A running container is a process, or a small tree of processes, that Docker isolates from the rest of the host. Stopping a container asks that main process to exit. When it exits, the container moves from the running state to the exited state.
Stopping does not delete anything. The container still exists, and so do its name, its configuration, and the changes it made to its writable layer. You can see it with docker ps -a and start it again later. Deleting is a separate step, covered in a later chapter.
The basic command
Start a container to practice on, then confirm it is running:
docker run -d --name web nginx:alpine
docker psStop it by name:
docker stop webDocker prints the name you passed and then returns. If you passed an ID, it prints the ID instead. Check the result:
docker ps
docker ps -aThe first command no longer lists web, because docker ps shows only running containers. The second shows web with a status such as Exited (0) 5 seconds ago.
docker container stop web is the same command written in the newer grouped form. Both work, and this tutorial uses the shorter one.
Choosing which container to stop
docker stop accepts a container name, a full ID, or any unique prefix of an ID. These three commands are equivalent if the container's ID begins with 3f2a9c:
docker stop web
docker stop 3f2a9c1d8b47
docker stop 3f2aA prefix works only while it matches exactly one container. If two containers have IDs starting with 3f, Docker refuses the ambiguous prefix. Names are usually safer in scripts, because IDs change every time you recreate a container and names do not, as long as you choose them.
You can pass several containers in one command:
docker run -d --name web1 nginx:alpine
docker run -d --name web2 nginx:alpine
docker stop web1 web2Docker stops the containers one after another, or in parallel in recent versions, and prints each name as it finishes. If one name is wrong, Docker reports an error for that one and still processes the others. The exit status of the whole command is non-zero when any of them failed, so a script can detect partial failure.
Verifying that a container stopped
Do not rely only on the command returning. Ask Docker for the container's state:
docker inspect --format '{{.State.Status}} exit={{.State.ExitCode}}' webFor the nginx container above, the output is:
exited exit=0State.Status tells you the lifecycle state. State.ExitCode is the exit code of the main process. It is useful because it tells you how the process ended, not just that it ended.
You can also use the status filter from the listing chapter to find everything that has stopped:
docker ps -a --filter "status=exited"Exit codes after a stop
The exit code shown in docker ps -a comes from the container's main process. Three values come up often after docker stop:
| Exit code | Meaning | Typical cause |
|---|---|---|
| 0 | The process exited cleanly | The program handled the stop request and shut down normally |
| 143 | Terminated by SIGTERM (128 + 15) | The program did not catch SIGTERM and the default action ended it |
| 137 | Killed by SIGKILL (128 + 9) | The program did not exit in time and Docker killed it |
Codes above 128 mean "killed by signal number (code minus 128)". They are not errors in your command. They describe how the process died. A 137 after a normal docker stop is a hint that the application did not shut down on its own, which matters if it needed time to flush data or close connections. The next chapter explains the mechanism behind this.
A stop that takes ten seconds
You can see the difference in practice. Some programs shut down at once when asked and others do not. Run a container whose main process is sleep:
docker run -d --name sleeper alpine sleep 300
time docker stop sleeper
docker inspect --format '{{.State.Status}} exit={{.State.ExitCode}}' sleeperOn a typical system the stop takes about ten seconds, and the exit code is 137. The sleep program runs as process 1 inside the container, and process 1 does not get default signal handling. It ignores the polite stop request, so Docker waits ten seconds and then kills it.
Compare that with nginx, which handles the stop request and exits in well under a second with code 0:
docker run -d --name web nginx:alpine
time docker stop webIf a docker stop seems to hang for ten seconds and then finish, that pause is the grace period running out. You can change the length of the wait with -t:
docker stop -t 30 web
docker stop -t 0 sleeper-t 30 gives the process thirty seconds to finish. -t 0 gives it no time, so the container is killed immediately. Use a longer wait for databases and queues that need time to write data. Use a short one for throwaway test containers. The exact sequence of signals is the topic of the next chapter.
Stopping many containers
To stop every running container, combine docker stop with the quiet listing of IDs:
docker stop $(docker ps -q)The -q flag makes docker ps print only IDs, one per line, and the shell substitutes them as arguments. This is convenient on a development machine and dangerous on a shared one, so read the output of docker ps first.
There is an edge case. If no containers are running, $(docker ps -q) expands to nothing and the command becomes a bare docker stop. Docker then prints an error that says it requires at least one argument. The error is harmless but noisy in scripts. A guard avoids it:
ids=$(docker ps -q)
if [ -n "$ids" ]; then
docker stop $ids
fiCombine this with filters to be more selective. For example, to stop only containers started from the nginx image:
docker stop $(docker ps -q --filter "ancestor=nginx:alpine")Filtering by name works too, for instance --filter "name=web". Be aware that name filters match substrings, so web also matches webapp and my-web.
Stopping something that is already stopped
Running docker stop on a container that is already exited does nothing harmful. Docker prints the name and returns success:
docker stop web
docker stop webThis makes stop safe to repeat in cleanup scripts. A name that does not exist behaves differently:
Error response from daemon: No such container: wbeCheck spelling if you see this. A container that was removed with docker rm or created with --rm and already exited is also gone, and it produces the same message.
Stopping and restart policies
Containers can be started with a restart policy, for example:
docker run -d --name api --restart unless-stopped nginx:alpineWith unless-stopped, Docker restarts the container if it crashes and when the Docker daemon starts, unless you stopped it yourself. A manual docker stop api therefore sticks: the container stays stopped, even after the daemon restarts.
The always policy is slightly different. After a manual stop, the container stays stopped until the daemon restarts, and then it comes back. If a container you stopped reappears after a reboot, check its policy:
docker inspect --format '{{.HostConfig.RestartPolicy.Name}}' apiTo change the policy of an existing container without recreating it, use docker update --restart no api.
Common mistakes
- Expecting stop to free disk space. The writable layer stays until the container is removed.
- Expecting stop to free the name. A stopped container still owns its name. Running
docker run --name web ...again fails with a name conflict until you remove or rename the old one. - Stopping with a short timeout for stateful services. A database killed after a few seconds may need crash recovery on its next start.
- Treating a non-zero exit code as a failed stop. A 137 or 143 shows how the process ended. The container still stopped.
- Stopping the wrong container. Names that are substrings of each other, and ID prefixes, are easy to mix up. Run
docker psfirst.
Summary of the commands
| Goal | Command |
|---|---|
| Stop one container | `docker stop web` |
| Stop several | `docker stop web1 web2` |
| Allow 30 seconds before killing | `docker stop -t 30 web` |
| Stop all running containers | `docker stop $(docker ps -q)` |
| Check how it ended | `docker inspect --format '{{.State.ExitCode}}' web` |
| List stopped containers | `docker ps -a --filter "status=exited"` |
Exercise
You run docker stop sleeper on a container whose main process is sleep 300. The command takes about ten seconds, and docker inspect then reports exit code 137. What does that tell you about the container, and is the container still on the system afterward?
Show answer
The main process did not exit when asked, so Docker waited out the ten second grace period and then killed it with SIGKILL. 137 is 128 + 9, the code for a process killed by signal 9. The container is still on the system in the exited state. Stopping does not remove it, so it appears in docker ps -a and can be started again until you run docker rm.
Exercise
Write a shell snippet that stops all running containers started from the image nginx:alpine, but does nothing and prints no error when none are running.
Show answer
ids=$(docker ps -q --filter "ancestor=nginx:alpine")
if [ -n "$ids" ]; then
docker stop $ids
fi
The test with -n skips the stop when the ID list is empty, which avoids the "requires at least 1 argument" error from a bare docker stop.
Exercise
You stopped a container named api that was created with --restart unless-stopped. After the host reboots, is it running again? Would the answer change if the policy were always?
Show answer
With unless-stopped, it stays stopped, because you stopped it manually and the policy respects that. With always, Docker starts it again when the daemon restarts, so after a reboot it would be running.