Diagnosing Docker overlay2 disk bloat, logs, and safe cleanup
Pinpoint what fills /var/lib/docker across overlay2 layers and container logs, cap log growth with rotation, and choose safe prune commands on Docker 29.
When
/var/lib/dockerfills up, runningdocker system pruneblindly often wipes useful build caches while leaving the real culprit intact. This note walks through verified Docker Engine 29 measurements coveringoverlay2writable layers, three cases where deleted files still hold disk space, unbounded container logs, and safepruneboundaries.
File-system paths and
prunesteps were measured inside an isolated Linux Docker Engine29.10.1instance (docker:29-dind,--storage-driver=overlay2, defaultjson-filelogging). Writable-layer vs. Named Volume behavior and label-filtered cleanup were also cross-checked on macOS Docker Desktop4.100.1(Engine29.9.3,overlayfs).
Diagnosing disk usage and two measurement traps
Before deleting anything on a full host, separate which subsystem actually owns the bytes. A quick top-down sequence narrows down the cause without guesswork.
flowchart TD
A["Host disk alert (df -h)"] --> B["docker system df -v"]
B --> C{"Large container size?"}
C -->|"Yes"| D["Check overlay2 UpperDir"]
C -->|"No"| E["Check container log files"]
E --> F["Check build cache & open FDs"]
Run these three commands in order to inspect both Docker-tracked objects and host log files:
1
2
3
4
5
6
7
8
# 1. Inspect images, containers, volumes, and build cache
docker system df -v
# 2. Check writable-layer size per container
docker ps -a -s --format 'table {{.Names}}\t{{.Status}}\t{{.Size}}'
# 3. Check container stdout/stderr log files (requires host root)
du -sh /var/lib/docker/containers/*/*-json.log 2>/dev/null | sort -hr | head -n 10
Two measurement traps distort this diagnosis if you aren’t watching for them.
First, running du -sh /var/lib/docker/overlay2 double-counts space for running containers. Each active container exposes both its diff/ directory and its mounted merged/ view under overlay2. In my test after writing a 50MiB file inside a container, UpperDir (diff/) measured 50.0M, while du -sh /var/lib/docker/overlay2 jumped from 8.4M to 116.9M—roughly double the real footprint. Always measure the exact UpperDir path returned by docker inspect.
Second, docker ps -a -s and docker system df exclude container log files completely. In the logging test below, a container holding a 5.2M *-json.log file still reported 0B in both docker ps -a -s and docker system df. When system df looks small on a full disk, inspect /var/lib/docker/containers/ first.
Why overlay2 keeps disk space after deleting files
Writing temporary files, uploads, or file logs inside a container without a mounted volume sends every byte to the container’s overlay2 writable layer (UpperDir).
I compared writing 50MiB to /tmp/blob.bin inside an unmounted alpine:3.21 container against writing the same 50MiB to /data/blob.bin backed by a Named Volume (cn-d11-vol). For a broader breakdown of Named Volumes, bind mounts, and UID permissions, see Docker volumes vs. bind mounts and fixing permission issues.
1
2
3
4
5
6
7
8
9
10
11
12
# 1) Write 50MiB into the container writable layer
docker run -d --name cn-d11-rw alpine:3.21 sleep 3600
UPPER_DIR=$(docker inspect --format '{{.GraphDriver.Data.UpperDir}}' cn-d11-rw)
docker exec cn-d11-rw dd if=/dev/zero of=/tmp/blob.bin bs=1M count=50
docker ps -s --filter name=cn-d11-rw --format 'table {{.Names}}\t{{.Status}}\t{{.Size}}'
du -sh "$UPPER_DIR"
# 2) Control: write 50MiB into a Named Volume
docker volume create cn-d11-vol
docker run -d --name cn-d11-vol-app -v cn-d11-vol:/data alpine:3.21 sleep 3600
docker exec cn-d11-vol-app dd if=/dev/zero of=/data/blob.bin bs=1M count=50
docker ps -s --filter name=cn-d11-vol-app --format 'table {{.Names}}\t{{.Status}}\t{{.Size}}'
The difference is immediate:
1
2
3
4
5
6
7
8
9
# Without a volume (after writing 50MiB)
NAMES STATUS SIZE
cn-d11-rw Up Less than a second 52.4MB (virtual 60.6MB)
50.0M /var/lib/docker/overlay2/6c1a2a79.../diff
# With a Named Volume (after writing 50MiB)
NAMES STATUS SIZE
cn-d11-vol-app Up Less than a second 0B (virtual 8.13MB)
# UpperDir: 8.0K | /var/lib/docker/volumes/cn-d11-vol/_data: 50.0M
Removing a newly created file in UpperDir with rm does reclaim space immediately—down to 8.0K—as long as nothing holds it open. The classic “I deleted the file, why is the disk still full?” incident comes from three specific conditions.
1. Deleted open file descriptors
Unlinking a file while a process still holds an open file descriptor removes only the directory entry; the kernel keeps the disk blocks allocated until the descriptor closes. I reproduced this by running tail -f /tmp/leak.bin before deleting the file:
1
2
3
4
5
6
7
8
docker exec cn-d11-rw rm -f /tmp/blob.bin
docker exec cn-d11-rw sh -c \
'dd if=/dev/zero of=/tmp/leak.bin bs=1M count=50 2>/dev/null; \
tail -f /tmp/leak.bin >/dev/null 2>&1 & sleep 1; rm /tmp/leak.bin'
docker ps -s --filter name=cn-d11-rw --format 'table {{.Names}}\t{{.Size}}'
df -m /var/lib/docker
docker exec cn-d11-rw pkill tail
df -m /var/lib/docker
Right after rm, docker ps -s drops to 0B and du -sh "$UPPER_DIR" shows 8.0K. Yet df -m /var/lib/docker stays at 42997 MB because /proc/26/fd/3 -> /tmp/leak.bin (deleted) still pins the blocks. Stopping tail immediately drops usage to 42947 MB, freeing the exact 50MB. When an active log file won’t release space after rm, restart the owning process or clear it with truncate -s 0 instead.
2. Copy-up and whiteouts on image-layer files
Modifying a file baked into a read-only image layer (LowerDir) triggers OverlayFS copy-up: the kernel copies the entire file into UpperDir before applying your edit.
Appending 1 byte to a 30MB file (/seed.bin) in the base image grew UpperDir from 4.0K to 30.0M (31.5MB in docker ps -s). Running rm /seed.bin afterwards did not reclaim the image’s 39.6MB; it only wrote a 0, 0 character device (whiteout) into UpperDir to hide the file:
1
c--------- 2 root root 0, 0 Dec 5 05:31 seed.bin
3. Stopped containers retaining writable layers
docker stop halts the process, not the filesystem layer. A stopped container that wrote 50MiB keeps 52.43MB on disk (Containers RECLAIMABLE 100% in docker system df) until you run docker rm or docker container prune.
Capping container logs with rotation and the local driver
On Linux, Docker Engine defaults to the json-file logging driver with no size or file-count limit. Every line sent to stdout or stderr appends forever to /var/lib/docker/containers/<id>/<id>-json.log.
I sent the same 30,000-line payload (~3.15MB raw text) through three logging configurations to measure real disk usage:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
GEN_CMD='awk "BEGIN { s=sprintf(\"%090d\", 0); for(i=1;i<=30000;i++) printf \"line=%05d payload=%s\n\", i, s }"'
# 1) Default json-file (unbounded)
docker run --name cn-d11-log-unlim alpine:3.21 sh -c "$GEN_CMD" >/dev/null
# 2) json-file with rotation
docker run --name cn-d11-log-rot \
--log-driver=json-file --log-opt max-size=1m --log-opt max-file=2 \
alpine:3.21 sh -c "$GEN_CMD" >/dev/null
# 3) local driver with rotation and built-in gzip compression
docker run --name cn-d11-log-local \
--log-driver=local --log-opt max-size=1m --log-opt max-file=2 \
alpine:3.21 sh -c "$GEN_CMD" >/dev/null
| Logging config | docker inspect .LogPath | Files created on disk | Actual disk usage | docker ps -a -s |
|---|---|---|---|---|
json-file default | .../<id>-json.log | 1 file (5,400,000B) | 5.2M | 0B |
json-file (1m, 2) | .../<id>-json.log | 2 files (399,600B + 1,000,080B) | 1.3M | 0B |
local (1m, 2) | "" (empty string) | 2 files (container.log + .1.gz) | 156.0K | 0B |
xychart-beta
title "Disk usage for 30,000 log lines by driver (KB)"
x-axis ["json-file default", "json-file rotated", "local (repetitive)"]
y-axis "Disk Usage (KB)" 0 --> 6000
bar [5400, 1400, 151]
All three containers returned the final lines cleanly via docker logs --tail 2, yet all three showed 0B in docker ps -a -s and docker system df.
With default json-file, JSON metadata (log, stream, time) inflated 3.15MB of text to 5.2M. Enabling max-size=1m and max-file=2 capped disk usage at 1.3M (a 74% reduction). Switching to local dropped it to 156.0K thanks to its binary format and default gzip compression on rotated files. Keep in mind this payload used zero-padded repetitive lines; higher-entropy production JSON logs won’t compress quite that aggressively.
Set global defaults in /etc/docker/daemon.json so new containers always inherit a ceiling:
1
2
3
4
5
6
7
{
"log-driver": "json-file",
"log-opts": {
"max-size": "50m",
"max-file": "3"
}
}
Reload or restart the daemon (sudo systemctl reload docker) to apply the change.
Changes in
daemon.jsonapply only to newly created containers. Existing containers keep their originalLogConfig. Check them withdocker inspect --format '{{json .HostConfig.LogConfig}}' <container>and recreate any that still run unbounded.
When not to switch to the local driver
Even though local saves disk space and I/O, don’t adopt it blindly. As the table shows, local stores binary files under local-logs/ and leaves docker inspect .LogPath empty (""). If your host runs Filebeat, Promtail, Fluent Bit, or custom scripts that tail /var/lib/docker/containers/*/*-json.log directly, switching to local breaks log shipping. In those setups, stay on json-file with explicit max-size and max-file limits.
Safe prune commands and volume deletion rules in Docker 29
Once you know what grew and have log rotation in place, pick the narrowest prune command that matches the target. On Docker Engine 29.10.1, I seeded stopped containers, locally built images, pulled images, BuildKit cache, an anonymous volume, and Named Volumes, then ran each cleanup step in sequence.
| Step | Command | Objects removed | Reclaimed | Named Volumes |
|---|---|---|---|---|
| 1 | docker container prune -f | Stopped container layer (20MiB) | 20.97MB | Preserved |
| 2 | docker image prune -f | 1 dangling <none> image | 0B (BuildKit ref) | Preserved |
| 3 | docker image prune -a -f | 2 unused tagged images | 0B (pulled: 4.105MB) | Preserved |
| 4 | docker builder prune -f | 5 BuildKit cache objects | 47.19MB | Preserved |
| 5 | docker system prune -f | Stopped container (15MiB) | 15.73MB | Preserved |
| 6 | docker system prune -f --volumes | 1 unused anonymous volume | 10.49MB | Preserved |
| 7 | docker system prune -a -f --volumes | Stopped DB container, images, cache | 0B (no anon vols) | Preserved |
| 8 | docker volume prune -a -f | Unused Named Volume (25MiB) | 26.21MB | Deleted |
Two findings here catch engineers off guard in production.
First, locally built BuildKit images often report Total reclaimed space: 0B under docker image prune -a. Deleting the image tag leaves the underlying layers pinned by BuildKit’s cache until you run docker builder prune (47.19MB reclaimed in step 4). By contrast, unused images pulled from a registry (busybox:1.36, alpine:3.21) reclaimed 4.105MB immediately under docker image prune -a. If you want to manage BuildKit cache intentionally on CI runners, see Speeding up Gradle builds with Docker BuildKit cache mounts.
Second, on Docker Engine 23+ (including 29.x), docker system prune --volumes and docker system prune -a --volumes remove only anonymous volumes (com.docker.volume.anonymous=) and preserve Named Volumes. Even with a database container stopped, cn-d11-db-data survived step 7 untouched. Only docker volume prune -a deleted the unused Named Volume (26.21MB in step 8).
Older hosts running Docker Engine 20.10 or earlier may delete Named Volumes on
docker volume pruneorsystem prune --volumes. Always checkdocker versionanddocker volume lsbefore pruning volumes on legacy servers.
Choosing the right command and when not to automate
| Goal | Recommended command | What to avoid |
|---|---|---|
| Clear old stopped containers | docker container prune --filter "until=24h" | Unfiltered prune while debugging a recent crash |
| Trim stale build cache | docker builder prune --filter "until=168h" | Running builder prune -a on CI runners (kills cache hit rate) |
| Remove unused images | docker image prune -a --filter "until=168h" | Using -a if you keep previous release tags for rollback |
| Remove orphan anonymous volumes | docker volume prune | Adding -a unless you verified every unattached Named Volume |
Avoid scheduling aggressive prune commands in cron without filters. If a database container happens to be stopped for maintenance when docker volume prune -a -f runs, Docker treats its Named Volume as unused and deletes it permanently. Pair automated cleanup with --filter "until=168h" or --filter "label=...", and keep Named Volume deletion strictly manual.
Production checklist
Before calling a Docker host disk-safe, verify these five items:
- Global log caps:
/etc/docker/daemon.jsondefinesmax-sizeandmax-file, and pre-existing containers have been recreated to pick up the newLogConfig. - Complete diagnostics: Incident runbooks check
/var/lib/docker/containers/*/*-json.logandlsof +L1alongsidedocker system df, rather than trustingsystem dfalone. - Volume separation: Uploads, temporary blobs, and file logs write to Named Volumes or external object storage instead of the container’s
overlay2writable layer. - Separate image and cache cleanup: Hosts that run
docker buildschedulebuilder prune --filter "until=168h"separately fromimage prune. - Safe volume boundaries: Automated jobs never call
docker volume prune -a, and volume-prune behavior is checked against the host’s Docker Engine version.