Keywords: Docker image cleanup | docker image prune | dangling images | unused images | filters | garbage collection
Abstract: This article provides an in-depth exploration of Docker image cleanup methodologies, focusing on the docker image prune command and its advanced applications. It systematically categorizes image cleanup strategies and offers detailed guidance on safely removing dangling images, unused images, and time-filtered old images. Through practical examples of filter usage and command combinations, it delivers complete solutions ranging from basic cleanup to production environment optimization, covering container-first cleanup principles, batch operation techniques, and third-party tool integration to help users effectively manage Docker storage space.
Overview of Docker Image Cleanup
During extended Docker usage, systems accumulate numerous image files that consume significant disk space. Docker employs a conservative garbage collection approach that does not automatically remove unused objects, necessitating user-initiated cleanup operations. Image cleanup extends beyond removing untagged dangling images to include tagged images not referenced by any containers, as well as time-based filtering of old images.
Core Cleanup Commands Analysis
Docker version 1.13 introduced systematic pruning commands specifically designed for cleaning various types of unused Docker objects. The docker image prune command serves as the foundation for image cleanup strategies, with its basic usage and advanced options forming the core of effective space management.
Basic Image Cleanup
By default, docker image prune removes only dangling images—those that are untagged and not referenced by any containers. When executing this command, the system displays warning messages and requires user confirmation:
$ docker image prune
WARNING! This will remove all dangling images.
Are you sure you want to continue? [y/N] y
To remove all images not used by containers (including tagged images), the -a or --all option must be used:
$ docker image prune -a
WARNING! This will remove all images without at least one container associated to them.
Are you sure you want to continue? [y/N] y
Force Execution and Automation
In production environments or scripts, the confirmation prompt can be bypassed using the -f or --force option:
$ docker image prune -a -f
Advanced Filtering Strategies
Docker provides powerful filtering mechanisms that enable precise image selection based on timestamps and labels, which is particularly valuable for cleaning specific time ranges or particular types of images.
Time Range Filtering
Using --filter "until=<timestamp>" removes images created before the specified timestamp. The timestamp supports multiple formats, including Unix timestamps, RFC3339 format, and Go duration strings:
# Remove images created more than 24 hours ago
$ docker image prune -a --filter "until=24h"
# Remove images created before January 4, 2017
$ docker image prune -a --filter "until=2017-01-04T00:00:00"
# Remove images created more than 10 days (240 hours) ago
$ docker image prune -a --filter "until=240h"
Label-Based Filtering
Label-based filtering provides granular control, supporting both positive and negative selection:
# Remove images with the deprecated label
$ docker image prune --filter="label=deprecated"
# Remove images where maintainer label equals john
$ docker image prune --filter="label=maintainer=john"
# Remove images without a maintainer label
$ docker image prune --filter="label!=maintainer"
# Remove images where maintainer label does not equal john
$ docker image prune --filter="label!=maintainer=john"
System-Level Cleanup Strategies
For comprehensive storage space optimization, Docker provides the docker system prune command, which can clean multiple types of unused objects in a single operation.
System Pruning Command
docker system prune by default removes: stopped containers, networks not used by any containers, dangling images, and unused build cache:
$ docker system prune
WARNING! This will remove:
- all stopped containers
- all networks not used by at least one container
- all dangling images
- unused build cache
Are you sure you want to continue? [y/N] y
Comprehensive Cleanup Including Volumes
To simultaneously clean unused volumes, the --volumes option must be added:
$ docker system prune --volumes
WARNING! This will remove:
- all stopped containers
- all networks not used by at least one container
- all volumes not used by at least one container
- all dangling images
- all build cache
Are you sure you want to continue? [y/N] y
Combined Cleanup and Best Practices
Effective image cleanup requires following specific execution sequences and strategy combinations to maximize space recovery while avoiding accidental deletion of important images.
Container-First Cleanup Principle
Technical practice demonstrates that stopped containers should be cleaned first, followed by image cleanup. This sequence captures more dangling images and reduces errors:
# First clean exited containers
docker rm $(docker ps -qa --no-trunc --filter "status=exited")
# Then clean dangling images
docker rmi $(docker images --filter "dangling=true" -q --no-trunc)
Practical Alias Functions
For frequently executed cleanup operations, Shell aliases or functions can simplify the workflow:
# Function for cleaning exited containers and dangling images
dcleanup(){
docker rm -v $(docker ps --filter status=exited -q 2>/dev/null) 2>/dev/null
docker rmi $(docker images --filter dangling=true -q 2>/dev/null) 2>/dev/null
}
# Specialized dangling image cleanup alias
alias drmi='docker rmi $(docker images --filter "dangling=true" -q --no-trunc)'
# Exited container cleanup alias
alias drmae='docker rm $(docker ps -qa --no-trunc --filter "status=exited")'
Third-Party Tool Integration
Beyond Docker's native commands, the community has developed specialized garbage collection tools that provide more intelligent cleanup strategies.
Docker GC Tool
Spotify's docker-gc is a simple Docker container and image garbage collection script with the following characteristics:
- Automatically removes containers that exited more than an hour ago
- Removes images that don't belong to any remaining containers
- Specifically avoids removing image tags currently in use by containers
Yelp Docker Custodian
Another implementation of the same concept is Yelp's docker-custodian, which offers richer configuration options and policy definitions.
Considerations and Limitations
When performing image cleanup, several critical issues require special attention to prevent data loss or system problems.
Lack of Preview Functionality
Currently, Docker's pruning commands lack --dry-run or preview options, increasing the risk of erroneous operations. This feature has been proposed in the moby/moby project since 2017 but remains unimplemented due to the following technical challenges:
- Race Conditions: Containers/images/volumes/networks may be unused during "dry run" but become used when actual pruning executes
- Object Dependencies: Complex dependencies exist between Docker objects, with image deletion requiring specific sequences (remove unused containers first, then unused images)
- Architectural Changes: With containerd snapshotter integration and multi-arch image support, cleanup calculations have become more complex
Predictive Filtering Limitations
When using negative filtering (such as label!=...), it's impossible to predict which images will be removed using docker image ls, increasing operational uncertainty.
Production Environment Optimization Recommendations
For the specific requirements of production environments, more cautious and automated cleanup strategies need to be established.
Regular Cleanup Scheduling
It's recommended to set up periodic cleanup tasks combined with time filters to remove old unused images:
# Weekly cleanup of unused images older than 30 days
docker image prune -a --filter "until=720h" -f
Critical Image Protection
Add protection labels to base images and critical business images to prevent accidental deletion:
# Add protection labels to important images
docker image tag important-image:latest important-image:protected
docker image tag important-image:protected important-image:latest
Through systematic image cleanup strategies, combining Docker's native commands with third-party tools, users can effectively manage Docker storage space, ensuring system performance and production environment stability. It's recommended to establish appropriate cleanup frequencies and strategies based on actual usage scenarios, finding the optimal balance between space recovery and system stability.