'Docker image Prune Filtering

Currently I am running

while true; do
    docker system prune --all -f;
    sleep 6400;
    done

In a daemonset to remove older images in my containers.

There is some unused images that I still want to keep around. Is there a possibility to filter out some images to not be pruned by this command?

for example after running docker system prune command,the following should not change if I want to prune everything else except repository a

Repository         TAG          IMAGE_ID         CREATED     SIZE
a                  12dac         3eadf            now          1
a                  44rfd         233df            4 month ago  1

Thanks.



Solution 1:[1]

You can add regular expression filters to prevent certain containers from pruning.

filtered=$(docker image prune –filter name=foo* -aq)
docker rm $filtered

This will delete all except containers that begin with the letters foo.

If necessary, you can read about the additional keys you can use for filtering in the docs

Solution 2:[2]

docker images --format "{{.Repository}}:{{.Tag}}:{{.ID}}" | grep "what_you_need" | cut -f 3 -d ":" | xargs docker rmi 

works for single "what_you_need" image. Look at the example:

docker images --format "{{.Repository}}:{{.Tag}}:{{.ID}}" | grep "prom/prometheus:v2.32.1" | cut -f 3 -d ":" | xargs docker rmi

Solution 3:[3]

From the docs on filter, adding a label to the bottom of your docker image will allow you to group your images.

For example, you could create a label in your dockerfile called storage and set its value to do_not_delete for the images you want to keep:

LABEL storage="do_not_delete"

Then run docker build ... to apply this label to the image.

Now, in your script, you can prune all images where the label storage isn't explicitly set to do_not_delete. Here is a sample command:

docker image prune --all -f --filter label!=storage="do_not_delete"

EXTRA
We can chain these filters too. In this example we prune all images older than one hour, while respecting the do_not_delete label:

docker image prune --all -f --filter label!=storage="do_not_delete" --filter until=1h

This can also be useful for clean up images you're actively developing against and/or testing. I use the command below to remove clutter in my dev environment:

# assuming all the images I'm working against have this line
LABEL env="scratch"

docker image prune --all --filter label=env="scratch"  --filter until=1h

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 justahuman
Solution 2 Oleksii Radetskyi
Solution 3 mts