'Remove docker images not recently used

I've searched through docs about docker prune with many examples, but none were what I need.

How to delete docker images that weren't used since x (for example, 72 hours)?

I don't see a profit from nightly removing images, most of which will be pulled within next 12 hours. But if something wasn't used for longer, it's likely no longer needed...



Solution 1:[1]

Unfortunately this specific request isn't a built in feature in docker. You can run:

docker image prune -a --until=72h

which would delete all images created at least 72 hours ago, but that wouldn't take into account images that were created months ago and used today. Implementing what you're looking for would require a tool that monitors the docker events feed and maintains a separate database of images used recently.

Solution 2:[2]

Solving a very related problem, I want to smartly prune containers and associated objects from a CI/CD runner:

  1. Stopped containers which haven't been run in 8 hours, and
  2. Images that haven't had a container created from then in the last 72 hours,
  3. and remaining dangling objects, ie, volumes, networks.

My algorithm is as follows:

Create a set of the IDs of all stopped/dead containers
For each Container in that set, 
     Get the Image (ID) associated with that Container
     Find its most recent "die" event-time less than the past 72 hours 
     If no die-event in past 72 hours:
        Add Image to Image-Purge-Set
        Add Container to Container-Purge-Set
     Else-If  no die-event in the past 8 hours:
        Add Image to Image-Keep-Set
     Else-If  die-event in the past 8 hours:
        Add Container to Container-Keep-Set
 
Subtract from each Purge-Set the Keep-Set

Remove all containers from the Container-Purge-Set
Remove all images from the Image-Purge-Set
Prune volumes, networks

Implementation using shell script, docker commands to follow.

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 BMitch
Solution 2 Otheus