TExcelTAD
Home › Docker › Image Size Optimisation

Image Size Optimisation

A 1.2 GB image works, but every deploy pulls it, every new server stores it, every scan inspects it, and every unneeded package in it is something that may need a security patch. Small images are faster to ship and safer to run. The good news: most of the savings come from a handful of habits.

Where the bytes come from

bash
docker image ls shop-api
docker history --format 'table {{.Size}}\t{{.CreatedBy}}' shop-api:1.4

Sample output:

text
REPOSITORY   TAG   IMAGE ID       CREATED          SIZE
shop-api     1.4   5c2b8e1f0a3d   10 minutes ago   1.21GB

SIZE      CREATED BY
0B        CMD ["python" "app.py"]
4.1MB     COPY . . # buildkit
612MB     RUN /bin/sh -c pip install -r requirements.txt
188MB     RUN /bin/sh -c apt-get update && apt-get install -y build-essential
0B        WORKDIR /app
406MB     # debian.sh --arch 'amd64' out/ 'bookworm' (python:3.12 base)

The tool dive (dive shop-api:1.4) shows each layer's files and estimates "wasted space": files that a later layer overwrote or deleted, but which still take up room in the image.

A wasted-space analyser

The model replays the layers' file operations and reports the final size, the visible content and the waste, like dive's summary:

python · try it yourself
layers = [
    ("FROM python:3.12",                {"add": {"/usr": 406}}),
    ("RUN apt-get install build-essential", {"add": {"/usr/lib/gcc": 150, "/var/lib/apt/lists": 38}}),
    ("RUN pip install -r requirements.txt", {"add": {"/usr/local/lib/python3.12": 540, "/root/.cache/pip": 72}}),
    ("RUN rm -rf /root/.cache/pip /var/lib/apt/lists", {"delete": ["/root/.cache/pip", "/var/lib/apt/lists"]}),
    ("COPY . .",                        {"add": {"/app": 4, "/app/.git": 35}}),
]

files, total = {}, 0
for step, ops in layers:
    added = sum(ops.get("add", {}).values())
    total += added
    files.update(ops.get("add", {}))
    for path in ops.get("delete", []):
        files.pop(path)
    print(f"{added:>4} MB  {step}")

visible = sum(files.values())
print(f"image size     {total} MB")
print(f"visible files  {visible} MB")
print(f"wasted         {total - visible} MB (deleted in a later layer)")
print("also suspicious:", [p for p in files if p.endswith((".git", "gcc"))])
 406 MB  FROM python:3.12
 188 MB  RUN apt-get install build-essential
 612 MB  RUN pip install -r requirements.txt
   0 MB  RUN rm -rf /root/.cache/pip /var/lib/apt/lists
  39 MB  COPY . .
image size     1245 MB
visible files  1135 MB
wasted         110 MB (deleted in a later layer)
also suspicious: ['/usr/lib/gcc', '/app/.git']

The deletion step saved nothing, .git was copied in, and a compiler sits in the runtime image. Each has a standard fix.

The habits that matter

Habit Typical saving
Use a -slim (or distroless/alpine) base instead of the full image hundreds of MB
Multi-stage builds: compile in one stage, copy only artefacts into a small runtime stage build tools and caches disappear
Clean up in the same RUN that created the mess (rm -rf /var/lib/apt/lists/*, pip --no-cache-dir, npm cache clean) tens of MB
--no-install-recommends for apt, apk add --no-cache for Alpine tens of MB
A .dockerignore (.git, node_modules, tests, data) anything from KB to GB
Production dependencies only (npm ci --omit=dev, no test extras) often 30-60 % of node_modules

Applying them one at a time to the image above:

python · try it yourself
steps = [
    ("starting point (python:3.12, build tools, cache, .git)", 1245),
    ("switch base to python:3.12-slim", -361),
    ("multi-stage: build-essential only in the build stage", -150),
    ("pip --no-cache-dir and apt lists removed in the same RUN", -110),
    (".dockerignore excludes .git and tests", -35),
    ("only production requirements (no pytest, linters)", -95),
]

size = 0
for label, delta in steps:
    size += delta
    change = f"{delta:+5d} MB" if delta < 0 else "        "
    print(f"{change}  {size:>5} MB  {label}")
first = steps[0][1]
print(f"total reduction: {first - size} MB ({100 * (first - size) / first:.0f}%)")
           1245 MB  starting point (python:3.12, build tools, cache, .git)
 -361 MB    884 MB  switch base to python:3.12-slim
 -150 MB    734 MB  multi-stage: build-essential only in the build stage
 -110 MB    624 MB  pip --no-cache-dir and apt lists removed in the same RUN
  -35 MB    589 MB  .dockerignore excludes .git and tests
  -95 MB    494 MB  only production requirements (no pytest, linters)
total reduction: 751 MB (60%)

Measure, don't guess

bash
docker image ls                                  # uncompressed size on disk
docker buildx imagetools inspect ghcr.io/acme/shop-api:1.4   # manifest + per-platform sizes
docker scout quickview shop-api:1.4              # size + vulnerability summary
dive shop-api:1.4                                # layer-by-layer explorer

Note that registries store layers compressed, so the "pull" size is typically 30-50 % of what docker image ls shows.

When smaller is not better

  • Alpine and musl: some Python wheels and prebuilt binaries target glibc. On Alpine pip may compile from source (slow builds, bigger images), or programs may fail in odd ways. -slim is usually the safer choice for Python and Node.
  • Distroless and scratch have no shell, which makes docker exec ... sh impossible. Use docker debug or an ephemeral debug container (see Debugging Containers).
  • Fewer layers is not the goal. Merging every step into one giant RUN hurts caching. Order steps for cache hits first; combine only steps that create and delete the same files.

Test yourself

Why doesn't RUN rm -rf /root/.cache/pip in its own step make the image smaller?

  1. rm doesn't work in Docker
  2. The files remain in the earlier layer; the new layer only hides them
  3. pip recreates them
  4. It does make the image smaller

Which technique keeps a C compiler out of the final image while still compiling native extensions?

  1. Using LABEL
  2. A multi-stage build that compiles in a builder stage and copies only the results
  3. Running apt-get remove gcc at the end
  4. Using docker commit

Why might python:3.12-alpine produce a bigger or slower build than python:3.12-slim?

  1. Alpine is bigger than Debian
  2. Many wheels are built for glibc; on musl-based Alpine pip may have to compile packages from source
  3. Alpine has no Python
  4. Alpine disables the cache