Sub topic 2
Pruning Images, Caches, Volumes, and Networks
Assume you know docker run, docker ps, docker images, and docker build. You should also know that an image is a read-only template, while a container is a runnable instance of that image.
Pruning images: dangling versus all unused
A dangling image has no tag pointing to it. These often appear after rebuilding an image. A tagged image can still be unused when no container uses it.
Plain docker image prune removes dangling images only. Use -a to remove every image unused by containers.
docker image ls --filter dangling=true
docker image prune
docker image prune -a --filter "until=168h"The last command removes unused images created more than seven days ago. It does not remove an image used by any container, including a stopped container.
Pruning the build cache
Docker stores intermediate build layers in its build cache. Remove unused cache with:
docker builder prune
docker builder prune --filter "until=168h"The age filter keeps recently used build data, which can make later builds faster.
Pruning volumes without losing data
Volumes hold persistent application data. A plain docker system prune does not remove them. docker volume prune removes volumes unused by containers, so inspect them first:
docker volume ls --filter dangling=true
docker volume pruneNever treat an unused volume as worthless. A stopped database container may be the only reference to important data. Back up the data before pruning. docker system prune --volumes also opts in to volume deletion.
Removing unused networks
Remove networks that no container uses:
docker network pruneDocker’s default networks are protected. Custom networks used by running or stopped containers are not considered unused.
Filtering prunes by age and label
Filters narrow the deletion set. until limits objects by age, while label selects objects with a matching label where that command supports labels.
docker image prune -a --filter "until=168h" --filter "label=temporary=true"
docker builder prune --filter "until=168h"
docker network prune --filter "label=temporary=true"Check the command’s help for supported filters. Docker prune commands do not provide a universal dry run, so list matching objects before deleting them.
Exercise
Which command removes all local images unused by containers, but keeps images created during the last seven days?
Show answer
docker image prune -a --filter "until=168h"