How To Delete and Remove All Docker Container Images on a System

Docker images can take up a significant amount of disk space on a system. As you build, test, and deploy containerized applications, old and unused Docker images can accumulate over time. Here are some best practices for deleting and removing Docker images to free up disk space.

View Existing Docker Images

The first step is to view your existing Docker images to determine what you want to delete. Here are some useful Docker commands:

  • docker images – List all Docker images
  • docker images -a – List all images, including intermediate image layers
  • docker images -q – List image IDs only
  • docker images -f dangling=true – List dangling images

Dangling images are layers that have no relationship to any tagged images. They can safely be removed.

Stop Containers Associated With Images

Before removing an image, you must ensure there are no running containers associated with that image. If there are, you must first stop the containers before removing the image.

To stop containers:

docker stop $(docker ps -a -q)

Then remove the stopped containers:

docker rm $(docker ps -a -q)

Remove One or More Images

To remove one or more Docker images by image ID or name:

docker rmi image_ID_or_name

To remove multiple images in one command:

docker rmi image1_ID image2_name image3_ID

Remove Dangling Images

To remove all dangling images:

docker image prune

Remove All Images

To remove ALL images (use with caution!):

docker rmi $(docker images -q)

Additional Tips

  • Use docker system prune to clean up multiple Docker objects like images, containers, volumes and networks
  • Add -a flag to commands to remove images not used by any containers
  • Use -f flag to bypass confirmation prompts
  • Monitor disk usage regularly and prune Docker system as needed

Automating Docker Cleanup

For ongoing management, you can create cronjobs or other scheduled tasks to automatically prune images and perform cleanup on a regular basis.

For example:

0 2 * * * docker system prune -af

This would run every day at 2 AM to remove all unused images. Adjust schedule and flags as needed.

Conclusion

  • View existing Docker images and identify ones to remove
  • Stop any containers using images you want to delete
  • Use docker rmi and other commands to delete images
  • Prune dangling images to clear up space
  • Remove all images with docker rmi $(docker images -q)
  • Automate pruning unused images on a schedule
  • Monitor disk usage and adjust cleanup schedule accordingly

Following these best practices will help keep your Docker host from filling up with old and unused images over time.