So, personally I recommend doing this as part of your deploy script for both images and containers, keeping only the most recent n containers and images. I tag my Docker images with the same versioning schema I use with git tag
as well as always tagging the latest Docker image with "latest." This means that without cleaning up anything, my Docker images wind up looking like:
REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE
some_repo/some_image 0.0.5 8f1a7c7ba93c 23 hours ago 925.4 MB
some_repo/some_image latest 8f1a7c7ba93c 23 hours ago 925.4 MB
some_repo/some_image 0.0.4 0beabfa514ea 45 hours ago 925.4 MB
some_repo/some_image 0.0.3 54302cd10bf2 6 days ago 978.5 MB
some_repo/some_image 0.0.2 0078b30f3d9a 7 days ago 978.5 MB
some_repo/some_image 0.0.1 sdfgdf0f3d9a 8 days ago 938.5 MB
Now, of course I don't want to keep all my images (or containers) going back to perpetuity on all my production boxes. I just want the last 3 or 4 for rollbacks and to get rid of everything else. Unix's tail
is your best friend here. Since docker images
and docker ps
both order by date, we can just use tail
to select all but the top three and remove them:
docker rmi $(docker images -q | tail -n +4)
Run that along with your deploy scripts (or locally) to always keep just enough images to comfortably roll back without taking up too much room or cluttering stuff up with old images.
Personally, I only keep one container on my production box at any time, but you can do the same sort of thing with containers if you want more:
docker rm $(docker ps -aq | tail -n +4)
Finally, in my simplified example we're only dealing with one repository at a time, but if you had more, you can just get a bit more sophisticated with the same idea. Say I just want to keep the last three images from some_repo/some_image. I can just mix in grep
and awk
and be on my way:
docker rmi $(docker images -a | grep 'some_repo/some_image' | awk '{print $3}' | tail -n +4)
Again, the same idea applies to containers, but you get it by this point so I'll stop giving examples.
docker run
with the--rm
flag which would make the container ephemeral, removing all container files after the run. – Gordondocker system prune
command. See my answer below. – VonCPortainer
We can manageall the old containers, non using volumes and images
by using this tool Its a simple management UI for dockersPlease refer my update below on how to deploy the application
– Anish Varghese