If you are a Docker fan, like me, your dev environment may look like this:

It’s a good practice to clean up your Docker resources every now and then to avoid such clutter.
In this post, you will look into some useful Docker commands and scripts to help you clean your system tidy.
Overall cleaning with system prune
The first tool in your toolbelt to do an overall cleaning is docker system prune
.
When you run the command, you get a warning that looks like this:

This is a great way to get rid of all the unused resources.
If you use the --all
option,
docker system prune --all
it deletes all unused images and not just the dangling ones.
The difference between unused and dangling Docker images is
- An unused image means that it has not been assigned or used in a container.
- A dangling image means that there is a new build of the image, but it wasn’t given a new name. (As you can see in the top screenshot, I have lots of containers with image name <none>)
Stop and remove containers
You can stop and remove containers by running the following commands:
docker stop {container id} docker rm {container id}
If you want to do a bigger cleaning by applying the above to all containers, you can run the following commands:
docker stop $(docker ps --all --quiet) docker rm $(docker ps --all --quiet)
If you want even a shorter version, you can only use the rm command with the force flag:
docker rm --force --volumes $(docker ps --all --quiet)
The above command will remove all containers, including the running ones.
Remove all images
The Docker command to remove an is rmi (shot for remove image).
You can remove all images in one go like this:
docker rmi $(docker images --quiet)
Remove based on a filter
Sometimes you can’t go nuclear like the above, and you have to be more selective about what you delete. For example, you may want to delete containers and images that belong to a specific project. To accomplish this, you can run the following command:
docker rm --force $(docker ps --all | grep <keyword> | awk '{print $1;}')
Make sure to replace <keyword> with the actual keyword.
Similarly, you can remove all images based on a keyword by running the following command:
docker rmi $(docker images | grep <keyword> | awk '{print $3;}')
The command above will only delete the unused images and not the ones used by running containers.
Conclusion
If you want to run a tight ship in your development environment, you need to be on top of all your precious resources. Cleaning your system periodically will give you a piece of mind and will keep your system performing better. Here’s how much disk space I got back after cleaning up unused resources:
