0

We know that docker image prune has a --filter argument that can be used to select (and remove) images older than a given number of hours (e.g.--filter "until=7*24h").

We also know that docker images has a similar --filter argument that supports a before key (e.g. docker images --filter "before=ubuntu:22.04"), but that can only filter images created before a given image or reference (not a date).

But pruning as described above would apply to all containers, which is rather too broad. What if we wanted to prune the "old" images more selectively, restricting the pruning to the images of just a single container (e.g. to spare older base containers, etc.)?

mirekphd
  • 4,799
  • 3
  • 38
  • 59

1 Answers1

0

I've come up with something looking ugly, but apparently rather effective.

The example below removes (forcefully) all images older than 2 weeks (the shortest period for which this implementation works - can be tweaked to any period though) of the an mirekphd/ml-cache container (caution: as a special case it can remove all images of this container):

$ MAX_WEEK_NUM=2 && REPO=mirekphd && CONTAINER=ml-cache && docker images --format "{{.ID}} {{.CreatedSince}}" --filter=reference="$REPO/$CONTAINER" | grep "[$MAX_WEEK_NUM-9999] weeks\|[1-999] months\|[1-99] years" | awk '{print $1}' | xargs docker rmi -f
mirekphd
  • 4,799
  • 3
  • 38
  • 59