Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker - remove all but last N images

Tags:

docker

I am trying to build a small script that removes all docker images besides a small "cache" of N last images (for rolling back to one of the last working versions).

Is there an idiomatic way to do this?

like image 755
Giuseppe Maggiore Avatar asked Nov 30 '16 15:11

Giuseppe Maggiore


1 Answers

You can use the tail command to accomplish this.

Let's say you only want to keep the most recent 5 images. You can tell tail to show you the list starting with the nth line. For 5 images, you would want tail to start on the 6th line:

tail -n +6

Pair this with docker to show a list of your image IDs, which are sorted by most recent, by default.

docker images -q | tail -n +6

You can pass all of that to the remove images command. This assumes you're using the bash shell; if you use a csh-derived shell, you may need different syntax.

docker rmi $(docker images -q | tail -n +6)
like image 75
Dan Lowe Avatar answered Sep 29 '22 02:09

Dan Lowe