The ultimate Docker cleanup command
If you use Docker (native and especially machine, which has only limited virtual disk space on macOS), you might have some problems with all those images you build during development polluting your hard drive. Good thing is, if you want all of that stuff gone, there is a neat oneliner that will do exactly that!
docker rm -f $(docker ps -a -q) && docker rmi -f $(docker images -q)
This oneliner consists of two commands.
The latter will only be executed if the first one is successful (due to &&
being used instead of just &
or ;
).
Those two commands each consist of two commands themselves and I’ll explain here what they do in the sequence they are executed:
docker ps -a -q
prints out all container ids that are present on your system.- The
$()
syntax takes its output as parameter for the next command
- The
docker rm -f
removes the container passed as argument and the-f
flag makes it stop and delete running containers.- If you want to keep the currently running containers, omit this
- Now the shell checks if the command was executed successful. If yes it resumes, if not it stops.
docker images -q
prints out all of the image ids present on your system.- Again its output is used as parameter for the next one
docker rmi -f
removes all images present on your system.- This includes all intermediate layers!
After you executed this script, all of the containers and images are deleted and you have a nice and clean environment.
I hope this post is helpful to you :)