How To Delete Unused and Dangling Docker Images in Linux
This guide shows how to delete unused and dangling Docker images on a Linux system. But first, why should you do it? There are several reasons why it is a good idea to delete unused Docker images:
- To save storage space: Docker images might consume a significant amount of disk space on your PC or server. If you have a high number of unused images, they might quickly fill up your disk space.
- To reduce security risks: Unused Docker images may include vulnerabilities that endanger your system’s security. Keeping them on your system expands the attack surface and makes it easier for attackers to exploit these vulnerabilities.
- To improve performance: Docker must load the required image into memory when you execute a Docker container. If you have a high number of unused images, the process of loading images and starting containers may be slowed.
- To keep your Docker environment clean: Deleting unwanted Docker images contributes to a clean and structured Docker environment. This makes managing and maintaining your Docker environment easier over time.
Run the following command to remove any unused Docker images. This command will clear your local Docker environment of all unused images. Unused images are those that are not currently being used by any container and can thus be deleted:
$docker image prune
You can also use the -a flag to erase all unwanted images, even those labeled as intermediate or dangling images:
$docker image prune -a
It should be noted that deleting an image will also destroy all containers based on that image. If you have any running containers that are utilizing the image you want to delete, you must first stop and remove them with the docker container stop and docker container rm commands.
For further information, execute this command (docker image prune -h) to see more usage options.