Difficulty: Beginner
How do you remove unused Docker volumes, and how do you make sure you do not delete data you still need?
Run docker volume prune to remove unused volumes, meaning volumes not referenced by any container, running or stopped. Since Docker Engine 23.0 it only removes unused anonymous volumes by default; add -a (--all) to also remove unused named volumes. Always list what will go first with docker volume ls -f dangling=true, because pruned volumes and their data cannot be recovered.
VOLUME instruction in an image (the official postgres and mysql images declare one) or by -v /data without a name. They pile up quietly as containers are recreated.docker volume create pgdata, -v pgdata:/var/lib/postgresql/data, or a top-level volumes: key in Compose). These normally hold data you care about.The Engine 23.0 change made the default safer: a plain docker volume prune will no longer delete your named database volume just because its container was removed. Many older blog posts describe the previous behaviour.
A volume is in use if any container references it, including stopped containers. So:
docker rm of that container, the volume becomes dangling and eligible for pruning.docker container prune followed by docker volume prune -a can therefore wipe a database you only stopped temporarily.docker volume ls -f dangling=true shows exactly which volumes are unused.docker volume prune -a --filter "label!=keep" skips volumes you labelled with keep, and --filter label=env=ci limits pruning to CI volumes.docker run --rm removes the container's anonymous volumes on exit, and docker rm -v does the same when removing a container manually.docker compose down keeps volumes; docker compose down -v removes the project's named and anonymous volumes. Use -v only when you really want a clean database.-f to skip the confirmation prompt in scripts, and only in scripts you trust.docker system prune --volumes also prunes volumes as part of a wider cleanup, which is convenient on CI runners but a bad habit on any machine that holds real data.
# What is unused right now?
docker volume ls -f dangling=true
# Remove unused anonymous volumes only (default since Engine 23.0)
docker volume prune -f
# Include named volumes, but skip anything labelled keep
docker volume prune -a -f --filter "label!=keep"
# Protect an important volume by labelling it at creation
docker volume create --label keep=true pgdata
Listing dangling volumes first and protecting important ones with a label makes pruning predictable.
# Tar the contents of pgdata into the current directory
docker run --rm \
-v pgdata:/source:ro \
-v "$PWD":/backup \
alpine tar czf /backup/pgdata-$(date +%F).tar.gz -C /source .
A short-lived container mounts the volume read-only and writes a compressed archive to the host. For a live database, prefer a logical dump such as pg_dump.
docker volume prune, Anonymous volumes, Named volumes, Dangling volumes, Data safety