Sub topic 7
Pruning volumes without losing data
This chapter assumes you can run docker run, docker ps, and docker images. It also assumes you know an image is a read-only template and a container is a running or stopped instance of one. Earlier chapters covered stopped containers, images, and build cache. Volumes get their own chapter because deleting one destroys data that may exist nowhere else.
What a volume is and why pruning it is different
A volume is a directory that Docker manages outside any container's writable layer. It survives when the container that used it is removed. Databases, uploaded files, and other state usually live in volumes.
Removing a container, image, or build cache entry loses nothing you can't recreate. You can pull the image again or rebuild the cache. A volume holds the only copy of its data, so deleting it is permanent.
Docker has two kinds of volume:
- Named volumes are created on purpose, for example
docker volume create pgdataor-v pgdata:/var/lib/postgresql/data. They have a name you chose. - Anonymous volumes are created without a name. They come from
-v /some/pathor from aVOLUMEinstruction in a Dockerfile. Docker names them with a 64-character hexadecimal string.
Bind mounts (-v /host/path:/container/path) are not volumes. Docker never prunes them, because they are just host directories.
Which volumes count as unused
A volume is unused, also called dangling, when no container references it. A stopped container still counts as a reference. This has a consequence you should plan around: a volume is safe from pruning while a stopped container uses it, and it becomes a candidate once that container is removed.
Suppose you run docker container prune and then docker volume prune. The first command can turn volumes that were protected into prune candidates.
flowchart TD
A[Volume exists] --> B{Referenced by any container, running or stopped?}
B -->|Yes| C[Not a prune candidate]
B -->|No| D{Anonymous or named?}
D -->|Anonymous| E[Removed by docker volume prune]
D -->|Named| F{Docker version and flags}
F -->|Before 23.0, or prune --all| G[Removed]
F -->|23.0 or later, no --all| H[Kept]The diagram above is the decision a prune makes for each volume, and the code block below preserves the same logic as text.
Version behavior you must check
Docker Engine changed this behavior in release 23.0. Before it, docker volume prune removed every unused volume, named or anonymous. From 23.0 onward, it removes only unused anonymous volumes. To include named volumes you must pass --all (or -a).
Because the behavior differs between engines, check yours first:
docker version --format '{{.Server.Version}}'If the output is below 23.0, treat every unused named volume as at risk. Don't rely on memory of how a plain volume prune behaved on another machine.
Step 1: Measure and list
Start with the per-object view. The verbose output includes a LINKS column for volumes, which is the number of containers that reference each one.
docker system df -vA volume with LINKS of 0 is unused. To list only those volumes:
docker volume ls --filter dangling=trueThe command lists dangling volumes by name. Anonymous ones show as long hexadecimal strings, which tells you nothing about their contents. Look inside before you decide:
docker volume inspect pgdataThe output shows the creation date, the driver, any labels, and the Mountpoint on the host. Compose-managed volumes carry labels such as com.docker.compose.project, which tell you which project owns them.
To see what a volume contains, mount it read-only in a throwaway container:
docker run --rm -v pgdata:/data:ro alpine ls -la /dataThe --rm flag removes the helper container when it exits. The :ro suffix means the helper cannot change the data.
Step 2: Back up anything you are unsure about
If a volume might matter, archive it before you prune. This command writes a compressed tarball of the volume into your current directory:
docker run --rm \
-v pgdata:/data:ro \
-v "$PWD":/backup \
alpine tar czf /backup/pgdata.tar.gz -C /data .To restore it into a new or empty volume:
docker volume create pgdata-restored
docker run --rm \
-v pgdata-restored:/data \
-v "$PWD":/backup \
alpine tar xzf /backup/pgdata.tar.gz -C /dataFor a running database, a file-level copy can capture an inconsistent state. Use the database's own dump tool (such as pg_dump) for those.
Step 3: Prune
The basic command asks for confirmation and removes only what the preview rules above allow on your engine version:
docker volume pruneTo include unused named volumes on Docker 23.0 or later:
docker volume prune --allThe confirmation prompt is a warning, not a list. It does not show you which volumes will go. Use the listing from Step 1 as your preview, since prune has no dry-run flag.
You can also remove volumes by name, which is the safest approach when you know exactly what you want gone:
docker volume rm old_cache_voldocker volume rm refuses to delete a volume that a container still references, so it fails safely.
Protecting volumes with labels
Prune accepts a label filter. You can mark volumes you want to keep and exclude them from every prune. Labels are set at creation time:
docker volume create --label keep=true pgdataThen prune everything unused except volumes carrying that label:
docker volume prune --all --filter "label!=keep"The reverse also works. If you label throwaway volumes with disposable=true, you can restrict a prune to just those:
docker volume prune --all --filter "label=disposable=true"Note that until is not a supported filter for volumes. Volumes have no reliable age filter, so you cannot say "prune volumes older than a week" the way you can for images.
Common mistakes
| Mistake | What happens | Prevention |
|---|---|---|
| Running `docker compose down -v` casually | Removes the project's named volumes along with containers | Use plain `docker compose down` unless you want the data gone |
| Pruning containers, then volumes | Volumes held only by stopped containers become unused and are deleted | Inspect `dangling=true` volumes after the container prune, before the volume prune |
| Assuming old behavior on a new engine | Named volumes survive a prune you expected to remove them (harmless) | Check `docker version` |
| Assuming new behavior on an old engine | Named volumes are deleted by a plain `volume prune` | Check `docker version`, or back up first |
| Trusting the confirmation prompt | You approve a deletion without seeing the volume names | List with `--filter dangling=true` first |
| Pruning on the wrong host | Production data is removed | Confirm with `docker context show` before running |
Preventing anonymous volume buildup
Most unused volumes are anonymous leftovers from containers that were removed without their volumes. Two habits stop them from accumulating:
- Run short-lived containers with
docker run --rm. The flag removes the container and its anonymous volumes on exit. It does not remove named volumes. - Remove containers with
docker rm -v name, which also removes anonymous volumes attached to that container. Without-v, those volumes remain.
Giving every volume you care about a clear name has a second benefit. A named volume is easy to recognize in a listing, and an unnamed one is easy to flag as disposable.
A safe sequence
Putting the steps together, a careful cleanup looks like this:
- Run
docker version --format '{{.Server.Version}}'anddocker context showto confirm engine and target host. - Run
docker system df -vand note volumes withLINKSof0. - Run
docker volume ls --filter dangling=trueand inspect anything you don't recognize. - Back up volumes that might hold data.
- Run
docker volume prune(add--alland a label filter only if you mean to). - Run
docker system dfagain to confirm the space came back.
Exercise
You run docker container prune and then docker volume prune --all --filter "label!=keep" on Docker 24. Your Postgres container had been stopped, and its named volume pgdata has no keep label. Is pgdata deleted, and what should you have done first?
Show answer
Yes, pgdata is deleted. Removing the stopped container left the volume with no references, so it counted as unused. --all includes named volumes, and without the keep label the filter does not protect it. Before pruning, you should have listed unused volumes with docker volume ls --filter dangling=true, backed up pgdata (for example with a tar archive from a helper container), and labeled it at creation time with --label keep=true.