How to Free Disk Space by Cleaning Docker Cache and Orphaned Containers
Unchecked growth of /var/lib/docker on Linux hosts frequently results in catastrophic no space left on device errors. Docker retains unreferenced intermediate build layers, cached BuildKit state, stopped containers, and unattached anonymous volumes by default.
Quick Diagnostics
docker system prune -a --volumes to reclaim unallocated storage/etc/docker/daemon.json and truncate logsUnchecked growth of /var/lib/docker on Linux hosts frequently results in catastrophic no space left on device errors. Docker retains unreferenced intermediate build layers, cached BuildKit state, stopped containers, and unattached anonymous volumes by default.
Step-by-Step Solution
-
1
Step 1: Inspect Docker Storage Footprint
Examine the breakdown of disk usage across your Docker engine:
BASH# Display summary of images, containers, and volumes docker system df # Display itemized consumption breakdown docker system df -v -
2
Step 2: Prune Unused Images, Containers, and Build State
Execute a comprehensive cleanup of resources not actively tied to running containers:
BASH# Remove stopped containers, unreferenced networks, and all unused images docker system prune -a --force # Purge legacy BuildKit build cache specifically docker builder prune -a --force -
3
Step 3: Remove Orphaned (Dangling) Volumes
Anonymous storage volumes detached from deleted containers persist indefinitely unless explicitly cleaned:
BASH# List dangling volumes docker volume ls -qf dangling=true # Purge all detached volumes docker volume prune --force -
4
Step 4: Truncate and Constrain Container Log Files
If container logging has accumulated gigabytes of raw JSON logs:
BASH# Truncate active JSON log files without taking down services sudo sh -c 'truncate -s 0 /var/lib/docker/containers/*/*-json.log'Enforce automatic log rotation in
/etc/docker/daemon.json:JSON{ "log-driver": "json-file", "log-opts": { "max-size": "50m", "max-file": "3" } }Reload the Docker daemon to activate log capping:
BASHsudo systemctl restart docker
❓ Frequently Asked Questions (FAQ)
Will docker system prune -a delete databases in active containers?
No. Actively running containers and their attached volumes are completely safe. Always use named volumes for critical persistent data.
How do I relocate /var/lib/docker to a dedicated drive?
Set the "data-root": "/mnt/storage/docker" parameter in /etc/docker/daemon.json and restart the service after copying existing files.
Prevention Advice
Recommended security practices:
- Schedule periodic maintenance: Set up a weekly cron task running
docker system prune -fon development and CI/CD servers. - Always invoke --rm on one-off containers: Run testing containers with
docker run --rmso they self-destruct upon termination.