Filter images to prune based on labels
In this final step, we will explore another powerful filtering option for docker image prune
: filtering based on labels. Labels are key-value pairs that you can attach to Docker objects, including images, to add metadata. You can then use these labels to filter and manage your Docker resources.
The --filter
flag with the label
key allows you to specify which images to include or exclude from the pruning process based on their labels.
First, let's create a couple of images with different labels. We'll use a simple Dockerfile and build two images with different labels.
Create a file named Dockerfile.labeled
in your ~/project
directory with the following content:
FROM alpine:latest
LABEL environment="development"
LABEL version="1.0"
RUN echo "This is a labeled image" >/app/info.txt
Now, build two images from this Dockerfile, applying different labels during the build process using the --label
flag.
docker build -t my-labeled-app:dev --label project=myapp --label stage=dev ~/project -f Dockerfile.labeled
docker build -t my-labeled-app:prod --label project=myapp --label stage=prod ~/project -f Dockerfile.labeled
We have now built two images, my-labeled-app:dev
and my-labeled-app:prod
, both based on the same Dockerfile but with different stage
labels.
Let's list the images and inspect their labels.
docker images --filter reference="my-labeled-app*" --format "{{.Repository}}:{{.Tag}} {{.Labels}}"
You should see output showing the images and their associated labels.
Now, let's use docker image prune
to remove images based on their labels. Suppose we want to remove all unused images that have the label stage=dev
. We can use the --filter
flag with label=stage=dev
. We'll also use the -a
flag to consider all unused images, not just dangling ones.
docker image prune -a --filter "label=stage=dev"
Docker will show you the images that match the filter and will be removed. Confirm by typing y
.
After the pruning, list the images again:
docker images --filter reference="my-labeled-app*" --format "{{.Repository}}:{{.Tag}} {{.Labels}}"
You should see that the my-labeled-app:dev
image has been removed, while my-labeled-app:prod
remains because it did not match the filter.
You can also use the label!=key=value
syntax to remove images that do not have a specific label or label value. For example, to remove all unused images that do not have the label stage=prod
:
docker image prune -a --filter "label!=stage=prod"
This command would remove my-labeled-app:dev
(if it still existed) and any other unused images that don't have the stage=prod
label.
Filtering by labels provides a flexible way to manage and clean up your images based on your own defined metadata.