Sub topic 11
Working with many containers and pruning
This chapter covers acting on many containers in one command. It assumes you can already run docker ps, docker stop, docker start and docker rm on a single container. It also assumes you know what --filter and --format do in a listing, and that you use a Linux, macOS or WSL shell such as bash or zsh.
Why bulk operations need care
Single-container commands take a name or ID. Bulk operations take a list of IDs produced by another command. The pattern is always the same:
- Select the containers with a listing.
- Check that the selection is what you meant.
- Pass the list to
stop,startorrm.
The risk is in step 2. A broad listing combined with rm -f can delete containers you wanted to keep, and Docker will not ask. The rest of the chapter builds the selection step carefully, then covers the built-in cleanup command, docker container prune.
Quiet listings: the building block
The -q (--quiet) flag makes docker ps print only full-length-truncated container IDs, one per line, with no header.
docker ps -q
docker ps -aqThe first command lists IDs of running containers. The second adds -a, so it also includes stopped ones. These lists are designed to be passed to other commands.
Command substitution
The shell can insert the output of one command into another with $(...). This is how the spine's example stops every running container:
docker stop $(docker ps -q)The shell runs docker ps -q first, then replaces the $(...) with the IDs. The result is something like docker stop 3f2a1b 9c8d7e 41ab22. Docker stops each container in turn and prints each ID as it finishes.
The empty list problem
If no container is running, docker ps -q prints nothing, and the command becomes plain docker stop. Docker then fails with an error saying it requires at least one argument. The failure is harmless, but it returns a non-zero exit status, which breaks scripts that stop on errors.
Piping to xargs avoids this:
docker ps -q | xargs -r docker stopThe -r flag (--no-run-if-empty) tells GNU xargs to skip the command when there is no input. BSD xargs on macOS already skips empty input.
Selecting containers with filters
You saw --filter "status=exited" earlier. Several other filters are useful for bulk work. Repeating --filter combines conditions with AND. Giving the same filter key twice usually means OR for that key.
| Filter | Matches | Example |
|---|---|---|
| `status` | `created`, `running`, `paused`, `exited`, `restarting`, `dead` | `status=exited` |
| `name` | Names matching a regular expression (substring by default) | `name=^web-` |
| `ancestor` | Containers created from an image or its descendants | `ancestor=nginx:alpine` |
| `label` | A label key, or key and value | `label=batch=demo` |
| `exited` | Exit code (use with `-a`) | `exited=137` |
| `before` / `since` | Containers created before or after another container | `since=web` |
The name filter is a pattern, not an exact match. name=web also matches webapp and my-web-db. Anchor the pattern with ^ and $ when you want precision.
Preview before you act
Always run the listing alone first and read it:
docker ps -a --filter "status=exited" --filter "name=^web-" \
--format "table {{.ID}}\t{{.Names}}\t{{.Status}}"When the table shows only what you expect, reuse the same filters with -q:
docker ps -aq --filter "status=exited" --filter "name=^web-" | xargs -r docker rmKeeping the filters identical in both commands is the whole safety check. Copy them rather than retyping.
A worked example with labels
Names work for a few containers. Labels are better for groups, because you decide the group when you create the containers. This example creates three throwaway containers that share a label.
for i in 1 2 3; do
docker run -d --name "demo-$i" --label batch=demo alpine sleep 3600
done
docker ps --filter "label=batch=demo" --format "table {{.Names}}\t{{.Status}}"The output looks like this:
NAMES STATUS
demo-3 Up 2 seconds
demo-2 Up 2 seconds
demo-1 Up 3 secondsNow stop the whole group:
docker ps -q --filter "label=batch=demo" | xargs -r docker stop -t 2The -t 2 shortens the grace period to two seconds. Without it, this particular command is slow, which is explained in the next section.
Check the result, then remove the group:
docker ps -a --filter "label=batch=demo" --format "table {{.Names}}\t{{.Status}}"
docker ps -aq --filter "label=batch=demo" | xargs -r docker rmThe first command shows three Exited containers. The second removes them. Starting a group works the same way: docker ps -aq --filter "label=batch=demo" --filter "status=exited" | xargs -r docker start.
Why the stop was slow
alpine runs sleep as process ID 1 inside the container. Linux gives PID 1 special treatment: signals with no installed handler are ignored. sleep has no SIGTERM handler, so it ignores the signal. Docker waits out the full grace period (10 seconds by default) and then sends SIGKILL. With three containers stopped one after another, that adds up to about 30 seconds.
There are two fixes. You can lower the grace period with -t, as above. You can also start containers with docker run --init, which runs a small init process as PID 1 that forwards signals to your program. If many containers stop slowly, this is the first thing to check.
Looping when you need more control
Command substitution treats every container the same. When you want to do something per container, or skip some, use a loop over a formatted listing:
docker ps -a --filter "status=exited" --format "{{.Names}} {{.Image}}" |
while read -r name image; do
echo "Removing $name (image: $image)"
docker rm "$name"
done--format without table prints no header, so each line holds only data. Quote the variables, because names are normally safe but quoting costs nothing.
What bulk removal does when something is running
docker rm refuses to remove a running container. When given several containers, it removes the ones it can, prints an error for the others, and exits non-zero. This makes the plain form a reasonably safe cleanup:
docker rm $(docker ps -aq)Stopped containers are removed. Running ones produce You cannot remove a running container errors and stay. Adding -f changes this completely:
docker rm -f $(docker ps -aq)This kills and removes every container on the host, running or not, including databases. Only use -f on a selection you filtered and previewed. Adding -v also deletes anonymous volumes attached to the removed containers, so data in them is lost.
docker container prune
For the common case, removing all stopped containers, Docker has a built-in command:
docker container pruneIt lists nothing in advance. It asks for confirmation and then removes every stopped container:
WARNING! This will remove all stopped containers.
Are you sure you want to continue? [y/N] y
Deleted Containers:
5d1c0b8e7f2a...
c9a3e4417b6d...
Total reclaimed space: 12.3kBWhat it removes is exactly the set that docker ps -aq --filter "status=exited" would show, plus containers in the created and dead states. Running and paused containers are never touched.
Flags
| Flag | Effect |
|---|---|
| `-f`, `--force` | Skip the confirmation prompt. Needed in scripts and CI. |
| `--filter "until=24h"` | Remove only containers created more than 24 hours ago. |
| `--filter "label=batch=demo"` | Remove only stopped containers with this label. |
| `--filter "label!=keep"` | Remove only stopped containers that do not have this label. |
A practical routine is a scheduled job that clears old stopped containers without touching recent ones:
docker container prune -f --filter "until=72h"Use labels to protect containers you want to survive. If you give long-lived stopped containers a label such as keep=true when creating them, --filter "label!=keep" skips them.
Pruning other resources
Containers are one of several resource types that accumulate. Each has its own prune command, and docker system prune combines several.
| Command | Removes |
|---|---|
| `docker container prune` | Stopped containers |
| `docker image prune` | Dangling images (untagged); with `-a`, all images not used by a container |
| `docker volume prune` | Unused anonymous volumes; with `--all`, all unused volumes (Docker Engine 23.0 and later) |
| `docker network prune` | Networks not used by any container |
| `docker system prune` | Stopped containers, unused networks, dangling images, and unused build cache |
docker system prune does not remove volumes unless you add --volumes. That default is deliberate, since volumes usually hold data.
Deciding which approach to use
Troubleshooting bulk commands
- "requires at least 1 argument": the selection was empty. Use
xargs -r, or check the listing first. - "You cannot remove a running container":
docker rmwas given a running container. Stop it first, or usedocker rm -fon a filtered, previewed list. - Prune asks for confirmation in a script: add
-f. Without a terminal, the prompt cannot be answered and the command does not remove anything. - Stops take 10 seconds per container: the main process is ignoring SIGTERM. Lower
-t, or start containers with--init. - A name is still "in use" after a failed cleanup: a container with that name still exists, probably stopped. Run
docker ps -a --filter "name=^demo-1$"to find it, thendocker rm demo-1. - Disk space did not come back: volumes and images are separate from containers. Check with
docker system df, then run the relevant prune command.
Exercises
Exercise
You run docker stop $(docker ps -q) on a host where nothing is running. What happens, and how would you write the command so it succeeds silently?
Show answer
docker ps -q prints nothing, so the shell runs docker stop with no arguments and Docker reports that it requires at least one argument, returning a non-zero exit status. Use docker ps -q | xargs -r docker stop, where -r skips the command when the input is empty.
Exercise
Write two commands. The first previews all exited containers whose names start with test-. The second removes exactly those containers.
Show answer
Preview: docker ps -a --filter "status=exited" --filter "name=^test-" --format "table {{.ID}}\t{{.Names}}\t{{.Status}}". Remove: docker ps -aq --filter "status=exited" --filter "name=^test-" | xargs -r docker rm. The filters are identical, so the removal acts on what you reviewed.
Exercise
You run docker container prune -f on a host with one running container, two exited containers, and an exited container that has an anonymous volume. Which containers are removed, and what happens to the anonymous volume?
Show answer
The three exited containers are removed. The running container is untouched. The anonymous volume is not deleted by container prune, so it remains as an unused volume until you run docker volume prune (or removed the container with docker rm -v).
Exercise
Why does stopping alpine sleep 3600 containers take about 10 seconds each, and name two ways to avoid the delay?
Show answer
sleep runs as PID 1 and has no SIGTERM handler, so the signal is ignored. Docker waits for the grace period (10 seconds by default) and then sends SIGKILL. You can lower the wait with docker stop -t 2, or start the container with docker run --init so an init process forwards signals correctly.