How to Remove All Docker Images – A Docker Cleanup Guide

If you‘ve been using Docker for a while, you‘ve likely noticed disk space slowly disappearing over time. Before you know it, your system drive is filled to the brim with gigabytes of Docker images, containers, volumes, and more. Where does all this disk usage come from and what can you do about it?

In this guide, we‘ll take a deep dive into analyzing and cleaning up disk space consumed by Docker. I‘ll show you the essential commands to prune unused resources, set up automated cleanup jobs, and adopt best practices to keep your Docker environment lean and mean for the long haul. Let‘s reclaim that precious disk space!

Why Does Docker Consume So Much Disk Space?

To understand why Docker can eat up disk space, it helps to know a bit about how Docker works under the hood. Here are a few key concepts:

Layered images – Docker images are made up of stacked filesystem layers. Each layer contains only the differences from the layer before it. While this saves space compared to having each image be independent, over time you accumulate many layers that add up in size.

Image version sprawl – It‘s easy to build up a collection of images you no longer need. Every time you run docker pull or docker build, a new image is downloaded or created. Old versions stick around even when you‘re no longer using them.

Container storage – Containers that write data consume space in a storage area managed by Docker. Even after the container is deleted, that space isn‘t automatically freed.

Volumes – Volumes allow containers to store persistent data outside the container filesystem. Volumes are not deleted by default when a container is removed.

Build cache – To speed up image building, Docker caches intermediate layers. This cache can grow quite large over many builds.

Together, these factors contribute to Docker using more and more disk space if left unchecked. Thankfully, Docker provides commands to analyze disk usage and clean up unneeded files.

Analyzing Disk Space Usage

Before we start deleting things, let‘s assess how much space Docker is actually using. Run this command:

docker system df

This gives a high-level summary of Docker‘s disk consumption:

TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          15        5         5.33GB    4.92GB (92%)
Containers      5         0         2.55MB    2.55MB (100%)
Local Volumes   7         2         1.44GB    1.29GB (89%)
Build Cache     0         0         0B        0B

Here we see a breakdown of space used by images, containers, local volumes, and the build cache, as well as an estimate of how much space could be reclaimed by deleting unused resources.

For a more detailed view, add the -v (verbose) flag:

docker system df -v

This shows lists of images, containers, and volumes, along with the individual sizes and whether they‘re active (in use) or reclaimable.

Armed with this information, we can now decide what to delete and how much impact it will have.

Pruning Unused Docker Resources

The docker system prune command is a one-stop shop for cleaning up unused Docker files. By default, it removes:

  • All stopped containers
  • All networks not used by at least one container
  • All dangling images (layers that have no relationship to tagged images)
  • All build cache

To also remove all unused images, add the -a flag:

docker system prune -a

Note this will prompt you to confirm deletion. Use -f to bypass the prompt and force deletion.

Here‘s sample output from running docker system prune -a -f:

Deleted Containers:
f7c1462f2faa1203c05c156e36cbb21b7aa9d1b7f5d9df617e8fe621bc8a9025
a3876b2c9d6f7e0691a9bfbe34d631df914f8b235ff182711cdc5ee118153b49
30612606a61f05d072f5baaec9cbc4c5085095ee72b28f727afbcabde7d37824

Deleted Images:
untagged: alpine:latest
untagged: alpine@sha256:e1871801d30885a610511c867de0d6baca7ed4e6a2573d506bbec7fd3b03873f
deleted: sha256:28f6e06c04fc0b2f7402c1ee444e4491c169b9b05f5f47723f657476b2ba92fb
deleted: sha256:77cae8ab23bf486355d1b3191259705374f4a11d483b24964d2f729dd8c076a0

Total reclaimed space: 4.919GB

Wow, nearly 5 GB freed up! However, docker system prune is a sledgehammer, and sometimes you want more fine-grained control over what gets deleted.

Pruning Images

To prune just images, use:

docker image prune

This removes dangling images. To remove all images not in use by any containers, use:

docker image prune -a

You can also filter images by age, using the -a flag with a filter:

docker image prune -a --filter "until=240h"

This deletes images created more than 10 days (240 hours) ago.

Pruning Containers

To delete stopped containers:

docker container prune

There are also several options to filter which containers get pruned. Refer to the docs for details.

Pruning Volumes

To delete volumes not used by any containers:

docker volume prune

This is useful for cleaning up orphaned volumes from deleted containers.

Pruning Networks

While networks don‘t consume disk space, they do clutter the output of docker network ls. To delete all unused networks:

docker network prune  

Setting Up Automated Cleanups

Running cleanup commands manually is a good start, but ideally you want automatic cleanups to run periodically without your intervention. How you do this depends on your operating system and environment.

Linux systemd service

On Linux systems using systemd, you can set up a service to run cleanups. Create a file named `/etc/systemd/system/docker-prune.service` with these contents:

[Unit]
Description=Docker system prune
[Service] 
Type=oneshot
ExecStart=/usr/bin/docker system prune -f
[Install]
WantedBy=multi-user.target

Then create a timer file /etc/systemd/system/docker-prune.timer to run the service daily:

[Unit]
Description=Run docker-prune service daily
[Timer]
OnCalendar=daily
[Install]  
WantedBy=timers.target

Finally, start and enable the timer:

sudo systemctl enable docker-prune.timer
sudo systemctl start docker-prune.timer  

Your system will now automatically clean up Docker every day.

Windows Task Scheduler

On Windows, you can use Task Scheduler to run cleanups. Open Task Scheduler and create a new task. Configure it to run the following command daily:

docker system prune -f  

CI/CD pipelines

If you use Docker in continuous integration and deployment pipelines, add a cleanup step at the end of your workflows. Most CI/CD platforms support running Docker commands. For example, in a Jenkins pipeline:

post {
  always {
    sh ‘docker system prune -f‘
  }
}

This ensures your build servers don‘t accumulate unneeded images and containers over time.

Best Practices for Managing Docker Disk Usage

In addition to setting up automated cleanups, adopt these best practices to proactively minimize Docker‘s disk footprint:

Use small base images – Choose lightweight images like Alpine Linux instead of full-featured distros as your base images.

Minimize layers – Combine related commands into a single layer in your Dockerfile using && to string them together. For example:

RUN apt-get update && \
    apt-get install -y curl && \
    rm -rf /var/lib/apt/lists/*

Use .dockerignore – Exclude unneeded files and directories from your build context using a .dockerignore file. This prevents them from being unnecessarily sent to the Docker daemon and included in images.

Squash layers – The experimental --squash option when building images will collapse all layers into a single layer, at the expense of discarding build cache. Use this sparingly to create minimal images.

Scan and security tools – Periodically use tools like Docker Bench and Clair to scan your images for security vulnerabilities and outdated dependencies. Remove any images that have critical issues.

Following these guidelines will help keep your Docker environment streamlined and make cleanups less impactful when they do run.

Conclusion

We‘ve covered a lot of ground in this deep dive on Docker disk usage. While Docker makes it incredibly easy to work with containers, images and volumes don‘t just magically disappear. It‘s on us as responsible Docker users to keep our systems tidy.

Whether you prefer cleanup by hand or fully automated, remember to:

  1. Monitor disk usage with docker system df
  2. Prune unused resources regularly with docker system prune and targeted prune commands
  3. Set up automatic cleanups appropriate for your environment
  4. Follow Dockerfile best practices to minimize image size

Happy cleaning!

Similar Posts