Sub topic 4
Removing stopped containers
This chapter assumes you can run docker run, docker ps, and docker build, and that you know an image is a read-only template while a container is a running or stopped instance of it. You should also be comfortable in a Linux or macOS terminal.
Why stopped containers take up space
A container that exits is not deleted. Docker keeps its filesystem changes, its metadata, and its log file so you can inspect it with docker logs or docker cp. Each container has a thin writable layer on top of its image. Anything the process wrote to the container filesystem lives in that layer until the container is removed.
Three things stay on disk for every stopped container:
- The writable layer, which holds files the process created or changed.
- The log file, which is a JSON file for the default
json-filelog driver. - Any anonymous volumes the container created, unless you remove them explicitly.
A stopped container also blocks cleanup elsewhere. Docker will not remove an image that a container, running or stopped, still references. Removing stopped containers is therefore usually the first step before pruning images.
The container lifecycle
Only containers that are not running are candidates for removal.
Finding stopped containers
Look before you delete. docker ps -a lists all containers, and --filter narrows the list.
docker ps -a --filter status=exited
docker ps -a --filter status=created
docker ps -a --filter "exited=0"The status filter accepts created, restarting, running, removing, paused, exited, and dead. The exited=<code> filter matches the exit code, so exited=0 finds containers that finished cleanly. A non-zero code, such as 137 for a process killed by SIGKILL, usually means something failed. You may want to read those logs before deleting.
To see how much each container has written, add -s:
docker ps -a -s --filter status=exited \
--format "table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Size}}"The SIZE column shows the writable layer size, followed by the "virtual" size, which includes the image layers. Image layers are shared between containers, so do not add the virtual figures together. Only the first number is space you recover by removing the container.
A worked example
This creates a container that writes 50 MB and exits, then shows the cost.
docker run --name demo-writer alpine \
sh -c 'dd if=/dev/zero of=/data.bin bs=1M count=50'
docker ps -a -s --filter name=demo-writer
docker system dfThe demo-writer row shows a writable layer of roughly 52 MB, and the Containers row of docker system df grows by about the same amount. The container has exited, but the file is still there. Remove it:
docker rm demo-writerRun docker system df again and the space is back.
Removing containers by hand
docker rm (the same as docker container rm) removes one or more containers by name or ID.
docker rm demo-writer
docker rm -v web-old
docker rm -f stuck-workerThe options behave differently:
| Option | Effect | When to use it |
|---|---|---|
| none | Removes a stopped container only. A running container is refused with an error. | Normal cleanup |
| `-v` | Also removes anonymous volumes attached to the container. Named volumes are never removed. | The container had throwaway data volumes |
| `-f` | Sends SIGKILL to a running container, then removes it. | A container that will not stop |
You can feed docker rm a list of IDs. The -q flag prints only IDs:
docker ps -aq --filter status=exited | xargs -r docker rmThe -r flag, from GNU xargs, skips the command when the list is empty. BSD xargs on macOS does this by default and does not accept -r on older versions, so drop it there.
Pruning stopped containers
docker container prune removes every container that is not running and not paused.
docker container pruneDocker prints a warning and asks for confirmation. After you answer y, it lists the removed container IDs and the reclaimed space. A container in the created state, which was made with docker create but never started, is removed too.
Skip the prompt with -f:
docker container prune -fLimiting by age or label
The command accepts --filter with two keys:
docker container prune --filter "until=24h"
docker container prune --filter "label=purpose=ci"
docker container prune --filter "label!=keep"untilaccepts a duration such as24hor30m, or a timestamp. It compares against the container's creation time, not the time it stopped. A container created three days ago that exited a minute ago matchesuntil=24h.label=keyorlabel=key=valuekeeps only containers with that label.label!=keyexcludes containers with that label.
Filters of different types are combined with AND. Repeating the same key, for example two label= filters, requires both to match.
The label filter is useful once you put the labels on containers deliberately:
docker run -d --label purpose=ci --name build-42 alpine sleep 5Later, docker container prune --filter "label=purpose=ci" removes only CI leftovers and leaves your hand-started containers alone.
What a container prune does not remove
Know these limits before relying on the command:
- Running and paused containers. Stop a container first if you want it pruned.
- Anonymous volumes. A pruned container leaves its volumes behind as unreferenced volumes. These show up under
docker system dfas reclaimable volume space, and a later volume prune handles them. - Named volumes and bind mounts. Neither is touched, so data in them survives.
- The images the containers used. Those become unused and can be pruned in the next step.
A frequent surprise is a volume that keeps growing after you prune containers. The space is in the volume, not the container.
Containers managed by Compose
Containers from a Compose project are ordinary containers. If you stop a project with docker compose stop, its containers show up as exited, and docker container prune removes them. Compose recreates them on the next docker compose up. Data in named volumes survives, but anything written only to the container filesystem is lost.
docker compose down removes the project's containers and networks directly. It leaves volumes unless you add -v, which deletes the named volumes declared in the Compose file. Treat down -v like a volume prune for that project.
Stopping the buildup at the source
If you run short-lived commands, --rm makes Docker delete the container, along with its anonymous volumes, as soon as it exits:
docker run --rm alpine echo "no leftover container"The tradeoff is that you cannot inspect logs or the filesystem after the exit. For tests, scripts, and one-off tasks that is usually what you want. For a service you may need to debug, leave --rm off. Do not combine --rm with a restart policy, because Docker rejects that combination for docker run.
Safety checklist
- Preview with
docker ps -a --filter status=exitedbefore running a prune. Prune has no dry-run flag. - Check for containers with non-zero exit codes and read their logs if you are still investigating a failure.
- Remember that
docker rm -vanddocker run --rmdelete anonymous volumes, and these can hold database files if an image declares aVOLUME. - Use
untilwhen other people or jobs share the host, so you do not remove containers that were just created.
Exercise
A host has several containers that exited yesterday and one that exited ten minutes ago but was created a week ago. You run docker container prune --filter "until=24h". Which of these containers are removed, and why? What happens to anonymous volumes they used?
Show answer
All of them are removed, including the one that exited ten minutes ago, because until compares against creation time and all of them were created more than 24 hours ago. Any anonymous volumes they used are not removed by the prune. They remain as unreferenced volumes until you run a volume prune, or until you had used docker rm -v or --rm when removing them.
Exercise
Write one command that removes only exited containers that finished with exit code 0, and explain why docker container prune is not the right tool for this.
Show answer
docker ps -aq --filter "exited=0" | xargs -r docker rm. Container prune supports only the until and label filters, so it cannot select by exit code. It would also remove containers that failed with non-zero codes, whose logs you may still need.