Docker is a popular container management platform that allows developers to build and deploy applications quickly and easily. However, Docker images can be difficult to clean up and delete. Here are some tips to help clean up and delete Docker images:
- Remove any unnecessary files from the image. This can include files that are not needed for the application or files that are no longer used.
- Delete any outdated or unused containers. This can include containers that have been deleted or have been removed from the image.
- Remove any logs and data that may be associated with the image. This may include logs from when the image was created or from when it was used in a previous run.
- Delete any images that are no longer needed or that have been superseded by newer versions of Docker.
Docker images can be very large, and if you work with containers often, it may be taking up a lot of your storage. We’ll discuss how to clean up your downloaded images and delete old files that you don’t need.
Docker Images vs. Docker Containers
Docker Images handle their data differently than containers. Images are read-only files that are built from Dockerfiles and pushed to the Docker Hub. Each time you download a new version, Docker must download the files for that new version. Old versions are still stored on your local drive.
Containers are made from images, and usually have their own filesystem and volumes attached to them. When you stop the container, any data not stored on a volume will be deleted. So, to clean up data used by containers, you simply need to stop them and delete their volumes.
To clean up images, Docker provides a few commands for running garbage collection.
Pruning Images
You will inevitably end up with images that aren’t in use, whether those are old versions of images, or images from containers that aren’t actively running. In any case, deleting an image usually presents no issue—if you need it again, Docker can just fetch it from the remote repository.
To view all images stored on your system, you can use the following command:
Despite looking like all these versions take up a bunch of space in this output, different versions are stored incrementally, so only the changes from the new version are actually stored on disk.
You can remove an image manually given it’s image ID:
However, a much safer method is to use the built-in prune command, which will search through all images to find and delete the ones without active references:
Ommitting the -a tag will keep images that are tagged but not in use. With the flag, only images you’re actively using will remain.
The prune command will tell you how much space was freed, but if you want to manually check how much storage Docker is using before and after, you can use du -sh on the Docker storage directory:
This directory will be located at C:ProgramDataDockerDesktop on Windows and ~/Library/Containers/com.docker.docker/Data/vms/0/ on macOS.