How to Use Dive to Analyze Docker Image Layers and Optimize Size

Docker tutorial - IT technology blog
Docker tutorial - IT technology blog

At 2:00 AM, my phone wouldn’t stop buzzing with a Disk Usage 98% alert on the production server. I dragged myself out of bed, SSH’d into the machine, and quickly ran df -h—only to see the /var/lib/docker partition ballooning abnormally. Checking further with docker images left me stunned. A Python API service with just a few dozen MB of code had ballooned into a 1.85 GB image.

The weird part? The dev team had already added cache-cleaning and temp-file deletion commands in the Dockerfile. So where was all that massive data hiding?

Why Is the Image Still Huge After Deleting Temp Files?

When an incident hits in the middle of the night, an ops engineer’s reflex is to run docker system prune -a to free up disk space and let the system breathe. But that’s just firefighting. The next morning, CI/CD runs the pipeline again, pulls the new image, and the disk fills right back up.

The docker images command only shows you the 1.85 GB total. It gives you zero clues about which line in the Dockerfile spawned that bloated data, or which junk directory is hiding inside.

The Docker Layer Trap and “Ghost” Files

A Docker Image isn’t a single monolithic file. It is built from multiple read-only Layers stacked on top of each other.

Every instruction that modifies files—like RUN, COPY, or ADD in a Dockerfile—creates a new Layer. Suppose you write this:

FROM ubuntu:22.04
RUN apt-get update && apt-get install -y build-essential curl git
RUN curl -sL https://example.com/big-archive.tar.gz -o /tmp/archive.tar.gz
RUN tar -xzf /tmp/archive.tar.gz -C /app
RUN rm -rf /tmp/archive.tar.gz /var/lib/apt/lists/*

Looks completely reasonable, right? Reality works differently. In Layer 3, the 500 MB archive.tar.gz file is permanently written into the image history. By Layer 5, the rm -rf command doesn’t actually delete that file from Layer 3. It simply creates a “deletion marker” (whiteout file) in Layer 5 to hide the old file when the container runs.

You’ve just wasted 500 MB of storage on a file you can’t even use anymore. Build a few dozen services like this, and your disk space vanishes in no time. To bring these “ghost” files to light, I use Dive.

Using Dive to Inspect Every Layer in Detail

Dive is a CLI tool with an interactive visual interface right in your terminal. It dissects each layer of a Docker Image and automatically calculates the percentage of wasted space.

1. Installing Dive

On Ubuntu/Debian, download the latest release and install it via the .deb package:

wget https://github.com/wagoodman/dive/releases/download/v0.12.0/dive_0.12.0_linux_amd64.deb
sudo apt install ./dive_0.12.0_linux_amd64.deb

Installing on macOS is even simpler:

brew install dive

If you’re working on a production server and don’t want to install extra tools, you can run Dive directly using a temporary container:

docker run --rm -it \
  -v /var/run/docker.sock:/var/run/docker.sock \
  wagoodman/dive:latest my-api:latest

2. Reading the Metrics in Dive’s Interface

Run dive my-api:latest, and your terminal screen splits into three main panes:

  • Top-left pane – Layers: Lists all layers from bottom to top along with each layer’s size. Use the up/down arrow keys to select a layer to inspect.
  • Bottom-left pane – Image Details: This is the first place to look. Dive displays the Image efficiency score (closer to 100% is better) and Potential wasted space. When I inspected that 1.85 GB image, the efficiency score was only 62%, with 685 MB of wasted space.
  • Right pane – Current Layer Contents: Displays the entire directory tree for the currently selected layer.

Pro tip: press Tab to switch to the right pane, then press Ctrl + U to hide unchanged files. You can also use Ctrl + A, Ctrl + M, and Ctrl + R to quickly filter by color status:

  • Green: New files added in this layer.
  • Yellow: Files modified or overwritten from a previous layer.
  • Red: Files deleted in this layer (the culprit behind image bloat, since the original data still lives in an earlier layer).

3. Integrating Dive into CI/CD to Block Bloated Images

Instead of inspecting images manually every time, you can run Dive in headless mode inside your CI/CD pipeline. The build will automatically fail if someone accidentally introduces junk files into the image:

CI=true dive my-api:latest --lowestEfficiency=0.95 --highestWastedBytes=20MB

With this configuration, if the efficiency score drops below 95% or wasted space exceeds 20 MB, Dive returns a non-zero exit code and blocks the push to the registry immediately.

Optimizing the Dockerfile Based on Dive’s Findings

Dive pinpointed the exact three culprits eating up space in my image: /root/.cache/pip (420 MB), /var/lib/apt/lists (45 MB), and an accidentally copied .git directory (220 MB). To clean all of this up, I applied three steps:

  1. Combine installation and cleanup into a single RUN command: Download, extract, and delete in the same RUN instruction chained with &&. Temporary files are removed before Docker commits the Layer.
  2. Create a .dockerignore file: Exclude .git, node_modules, __pycache__, log files, and .env from the build context when running COPY . ..
  3. Use Multi-stage Builds: Separate the build stage (containing gcc and heavy compilation libraries) from the runtime stage. The final image only copies the built artifacts into a lightweight base image like python:3.11-slim.

Here is the rewritten Dockerfile:

# Stage 1: Build dependencies
FROM python:3.11-slim AS builder
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends gcc \
    && rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt

# Stage 2: Ultra-lightweight runtime
FROM python:3.11-slim
WORKDIR /app
COPY --from=builder /install /usr/local
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

After rebuilding and checking with Dive, the image size plummeted from 1.85 GB down to 165 MB. The efficiency score jumped to 98.7%, leaving just 2.1 MB of wasted space.

Applying this across a production cluster running over 30 containers cut disk consumption on our nodes by about 40%. Image pull times during auto-scaling also dropped from over 2 minutes to under 10 seconds, noticeably reducing network bandwidth and disk I/O.

Next time before pushing a new image to production, run a quick dive <image-name>. Spending just 30 seconds on this check will save you from plenty of midnight production headaches.

Share: