Sysadmin

Docker Disk Space: Prune, Logs, and Unused Images

Docker Disk Space: Prune, Logs, and Unused Images

Reclaiming disk space is one of the most common and critical maintenance tasks for anyone managing Docker environments. Obsolete images, stopped containers, orphaned volumes, and especially unmanaged logs can rapidly saturate storage, leading to slowdowns, build errors, and, in the worst cases, complete service outages. I’ve seen servers crash due to full disks in enterprise environments with hundreds of containers, resulting in crucial service interruptions and hours of work to restore normalcy. The key is prevention and proactive, not reactive, cleanup. This article will show you how to achieve this effectively, using the right commands and configuring Docker for optimal space management.

Tested on: Ubuntu 24.04 LTS · Docker Engine 26.1 · October 2026

Prerequisites / Test Environment

To follow this guide, you will need a Linux system with Docker installed and running. SSH access with sudo privileges is necessary for some configuration operations and restarting the Docker daemon. Ensure you are familiar with basic Docker concepts such as images, containers, and volumes.

Understanding Space Consumption: docker system df

The first step to freeing up space is understanding where it’s being consumed. Docker offers a specific command that provides a detailed overview of disk usage for its components. This is the starting point for any cleanup strategy.

docker system df -v

The output of this command will show you disk usage for images, containers, volumes, and build cache, distinguishing between active elements and those that can be reclaimed. The -v (verbose) flag provides additional details, including volume data.

Component Description
Images Docker images downloaded or created locally
Containers Space occupied by containers (writable layers)
Local Volumes Persistent data mounted by containers
Build Cache Cache used by the Docker builder to speed up subsequent builds

Read also: Certctl and Docker Compose: Simplified Self-Hosted TLS Management

Unused and Dangling Images

Docker images can occupy a significant amount of space. Often, after updates or rebuilds, obsolete or “dangling” images (no longer associated with a tag or container) remain on the system. docker image prune is the command to manage them.

To remove all unused images (those not associated with any container):

docker image prune

To remove all unused images, including those not associated with containers or tags (so-called “dangling” images), add the -a flag:

docker image prune -a

If you want to be more selective and remove only images older than a certain period, you can use the until filter:

docker image prune -a --filter "until=168h" # Removes images older than 7 days (168 hours)

Stopped Containers and Orphaned Volumes

Stopped containers and no-longer-used volumes can also accumulate. A stopped container retains its writable layer on disk, while an orphaned volume is a persistent volume no longer connected to any active container.

To remove all stopped containers:

docker container prune

To identify and remove orphaned volumes, which often contain data no longer needed:

docker volume ls -f dangling=true

After verifying that these volumes are no longer needed, you can remove them with:

docker volume prune

The Build Cache

During the Docker image build process, intermediate layers are created that can remain as cache. This cache is useful for speeding up subsequent builds, but it can take up a lot of space, especially in development or CI/CD environments with many builds.

To clean the build cache:

docker builder prune

This command removes intermediate layers no longer referenced by any image. Read also: Container Runtimes: Docker vs Podman in 2026

Uncontrolled Container Log Growth

A frequently underestimated problem is the uncontrolled growth of container logs. By default, Docker does not impose limits on log file sizes, which can reach considerable dimensions and saturate the disk in environments with very “verbose” containers.

To find the largest log files, you can use this command:

sudo du -sh /var/lib/docker/containers/*/*-json.log | sort -h | tail

This will show you the 10 largest Docker log files, allowing you to identify which containers are generating the most output.

Configure Log Rotation in daemon.json

The definitive solution for logs is to configure rotation directly in the Docker daemon. This prevents logs from growing indefinitely by limiting their size and the number of files retained. You need to modify the /etc/docker/daemon.json file.

If the file does not exist, create it. Add or modify the log-driver and log-opts sections as follows:

{
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  }
}

In this example:

  • "max-size": "10m": each log file will have a maximum size of 10 megabytes.
  • "max-file": "3": a maximum of 3 log files will be kept per container. When the first file reaches 10MB, it is rotated, and the oldest of the 3 is deleted.

After modifying the daemon.json file, you must restart the Docker service to apply the changes:

sudo systemctl restart docker

Read also: systemd Service Creation: Auto-Restart & Dependencies

What NOT to Delete: Volumes with Data

It is crucial to be careful when removing volumes. Volumes are designed for data persistence. If a volume contains important data (e.g., a database, application configurations, user-uploaded files), deleting it will result in irreversible data loss. Always use docker volume ls to list volumes and docker volume inspect to examine their content or association with containers before proceeding with removal. The command docker volume ls -f dangling=true is safe because it only shows volumes no longer associated with any active container, indicating they are likely orphaned and no longer in use.

Scheduled Automatic Cleanup

The best strategy is to automate cleanup. You can create a script and schedule it with cron or systemd timers to regularly execute docker system prune and docker builder prune commands. For example, to perform a cleanup every Sunday night:

Create a shell script, for example, /usr/local/bin/docker-cleanup.sh:

#!/bin/bash

echo "$(date): Starting Docker cleanup..."

docker system prune -af --filter "until=168h" # Removes images/containers/volumes unused for 7 days
docker builder prune -f # Cleans the build cache

echo "$(date): Docker cleanup complete."

Make the script executable:

sudo chmod +x /usr/local/bin/docker-cleanup.sh

Then, add an entry to crontab (e.g., sudo crontab -e for the root user) to run it weekly:

0 3 * * 0 /usr/local/bin/docker-cleanup.sh >> /var/log/docker-cleanup.log 2>&1

This will execute the script every Sunday at 03:00 AM, redirecting the output to a log file. The -f (force) flag in prune is crucial for automation, as it suppresses interactive confirmation prompts. Read also: Linux find Command: 20 Practical Examples

Common Errors and Troubleshooting

  • “Cannot connect to the Docker daemon”: Ensure the Docker service is running (sudo systemctl status docker) and that your user has the correct permissions (is in the docker group).
  • Insufficient cleanup: If, after running the commands, space is not significantly freed, review the output of docker system df -v. There might be a very large data volume that was not identified or cannot be removed. Also, check manually unmanaged logs before configuring rotation.
  • Data loss: Indiscriminate removal of volumes can lead to data loss. Always back up or carefully verify the use of a volume before deleting it. docker volume ls -f dangling=true is your friend.

FAQ — Frequently Asked Questions

How often should I clean up Docker?

It depends on the intensity of your Docker usage. For development or CI/CD environments with frequent builds, daily or weekly cleanup might be appropriate. For stable production servers, monthly or bi-monthly cleanup might suffice. The important thing is to regularly monitor disk space with docker system df and adjust the frequency accordingly.

Does docker system prune also remove running containers?

No, docker system prune and its subcommands (image prune, container prune, volume prune, builder prune) are designed to remove only unused or stopped elements. Running containers, images used by running containers, and volumes mounted by active containers will not be touched by these commands, unless flags like -a or -f are used in specific and well-understood contexts.

Can I undo a Docker cleanup?

Generally, no. Once an image, container, or volume is removed with prune commands, the associated data is permanently deleted. It is essential to be sure of what you are removing before executing these commands, especially in production. Regular backups are your only true insurance against data loss.

Does log rotation in daemon.json also apply to existing containers?

Yes, the log-driver and log-opts settings in the daemon.json file apply to all new containers started after the Docker daemon restarts. For containers already running before the change, the new settings will not take effect until they are restarted. It is good practice to restart all containers after modifying daemon.json to ensure new log rotation rules are universally applied.

Conclusions with Operational Takeaways

Managing disk space in Docker environments is not an option, but a necessity. Ignoring the accumulation of images, containers, and logs can lead to system performance and stability issues, with significant operational costs. Using docker system df -v for in-depth analysis, combining prune commands for effective cleanup, and configuring log rotation via daemon.json are fundamental steps. Automating these operations with cron or systemd timers is the final step for a resilient and performant Docker environment. Always remember to carefully verify what you are removing, especially volumes, to avoid irretrievable data loss.

Sources

Updated: October 2026

Share this article:

Written by

Rosario Giordano

Rosario Giordano is a system administrator and IT consultant specializing in cybersecurity and cloud, with over 20 years of experience managing enterprise Linux infrastructures. His areas of expertise include SSH hardening, Kubernetes platforms, PostgreSQL databases, VMware/ Proxmox virtualization, and compliance with NIS2 and ISO 27001 security frameworks