How can I tell docker to prune old images, except any images that have been used in the past 4 weeks?

To prevent the oft-cited issue of docker filling our disks in prod, we have a script that runs the following command (among others):

time nice docker image prune --force --all --filter until=672h

This should, by our interpretation, delete only images that have been unused for 672 hours = 4 weeks.

Sadly, we stopped the image temporarily during a change the other day, and our docker ... prune cron kicked-off right in the middle of our change. The result: An hour later when we finished the change, the image had been deleted.

So even though the image had been used in a container <24 hours ago (that containter itself was started 5 weeks ago, but stopped <24 hours ago), the filter deleted it because it was [a] currently unused and [b] the image was created >4 weeks ago.

How can I do docker image prune cleanups such that it doesn't delete images unless the image hasn't been used by a container for over 4 weeks?

1 Answer 1


It seems that this is still an ongoing issue. No metadata is available (contained in the image itself) that provides information about last usage.

You can try to implement your own script/tool that monitors docker events and keeps track of image usage and prunes older ones. For example, docker events --since 24h --filter event=start --format '{{ .Time }} {{ .From }}' will return timestamp and image name of started containers for the past 24h.

It also depends on what's your criteria for an "used image". If using the events log, however, keep in mind that Only the last 1000 log events are returned., so that should also be taken care of.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.