Difficulty: Intermediate
What does the docker diff command show, and when is it useful in practice?
docker diff <container> lists the files and directories that have changed in a container's writable layer compared with the image it was created from. Each line is prefixed with A (added), C (changed) or D (deleted). It is useful for finding out what an application writes at runtime, spotting data that should be in a volume, and investigating whether a container was tampered with.
Every container gets a thin writable layer on top of the read-only image layers (the Copy-on-Write model). docker diff simply reports what is in that writable layer:
A /tmp/report.csv: a new file that did not exist in the image.C /etc/nginx/nginx.conf: a file from the image that was modified, so it was copied up into the writable layer.D /var/cache/apk: a file or directory from the image that was removed (stored as a whiteout).Parent directories of changed files also appear as C, so a single new log file shows up as C /var, C /var/log, A /var/log/app.log. The command works on running and stopped containers, since the writable layer persists until the container is removed.
docker diff only lists paths. To see the actual change, docker cp the file out and compare it, or use docker export for a full snapshot.docker diff. If you see /app/uploads/... or SQLite files, that data will be lost on redeploy and needs a volume.--read-only, use docker diff to find every path the app writes to, then give those paths a --tmpfs or volume.A /usr/local/bin/xmrig or a changed /etc/passwd in a public-facing container is a strong sign of compromise. Diff it before you remove it, and keep the evidence.docker commit: see exactly what would be baked into the new image, and then write it into a Dockerfile instead.A quick way to cut noise is to filter: docker diff web | grep -v '^C /tmp', or just look at the A and D lines.
docker run -d --name web nginx:1.27
# Generate some writes
docker exec web sh -c 'echo hi > /usr/share/nginx/html/hello.txt && rm /usr/share/nginx/html/50x.html'
docker diff web
A, C and D mark added, changed and deleted paths. nginx itself also writes a pid file and temp directories at startup, which is useful to know before switching to a read-only root filesystem.
# Only show new files to find runtime write paths
docker diff web | grep '^A'
# Then run with a read-only root and writable tmpfs where needed
docker run -d --read-only \
--tmpfs /var/cache/nginx --tmpfs /run \
nginx:1.27
The added paths tell you exactly which directories need tmpfs or volumes before you lock down the root filesystem.
docker diff, Writable layer, Copy-on-Write, Container forensics