5 min read

Dockerfile in Practice - Layers, Build Cache and Best Practices

1. Recap: From a Minimal Dockerfile to a Real One

In the second part of this series, a Dockerfile with just a few lines was enough to package a Python application. That works, but a Dockerfile written without thinking about layers and build cache produces images bigger than they need to be and builds that take much longer than they should on every small code change. This article digs into how Docker builds an image under the hood, and how to write a Dockerfile that takes advantage of it.

2. How Layers Work

Every Dockerfile instruction (FROM, RUN, COPY, ADD) that modifies the filesystem produces a layer — a read-only diff stored separately and stacked on top of the previous ones. The final image is simply the sum of all those layers, and the running container adds a writable layer on top (union filesystem).

Container (writable layer)
──────────────────────────
Layer 4: COPY . .
Layer 3: RUN pip install -r requirements.txt
Layer 2: COPY requirements.txt .
Layer 1: FROM python:3.12-slim

Two important practical consequences:

  • Layers are shared between images. If two different images share the same first instructions (for example, the same FROM and the same RUN apt-get install), Docker stores that layer only once on disk, even if several images use it.
  • Layers are cached between builds. When you run docker build again, Docker checks each instruction in order: if the instruction and its input files haven’t changed since the last build, it reuses the already built layer instead of redoing the work. This is the basis for the whole next topic.

3. Build Cache: Order the Dockerfile by How Often Things Change

The build cache is invalidated from the first point of change onward: if instruction N changed (or a file it copies changed), every layer from N on is rebuilt — even if the following instructions are identical to the previous build. This means the order of the instructions in the Dockerfile matters as much as their content.

The most common mistake is copying all the source code before installing dependencies:

# Bad: any code change invalidates the pip install cache
FROM python:3.12-slim
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir -r requirements.txt
CMD ["python3", "app.py"]

Since COPY . . copies the entire codebase, any change to any file — even a README.md — changes that layer’s content and invalidates everything after it, including pip install, which is usually the slowest step of the build.

The fix is to separate what changes often (code) from what rarely changes (the dependency list), copying and installing dependencies first:

# Good: pip install only runs again if requirements.txt changes
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python3", "app.py"]

Now, changing only the application code (the most common case during development) reuses the pip install layer from the cache, and that step of the build drops from tens of seconds (or minutes, in projects with many dependencies) to under a second.

The same principle applies to any package manager — Node.js (package.json before the code), Go (go.mod/go.sum before the code), Ruby (Gemfile before the code): copy the dependency manifest, install, and only then copy the rest.

4. Minimizing the Number and Size of Layers

Every RUN creates a new layer, and layers never “shrink” — if one RUN downloads a temporary file and a later RUN deletes it, the space it took up in the earlier layer still counts toward the final image size. That’s why related steps are usually combined into a single RUN:

# Bad: the apt cache stays stuck in a layer, even after being "removed"
RUN apt-get update
RUN apt-get install -y curl git
RUN rm -rf /var/lib/apt/lists/*

# Good: a single RUN, a single layer, nothing left over
RUN apt-get update && \
    apt-get install -y --no-install-recommends curl git && \
    rm -rf /var/lib/apt/lists/*

--no-install-recommends avoids installing “recommended” packages that apt-get would pull in by default but that are rarely needed inside a container — another common source of unnecessary weight in the image.

5. Choosing the Right Base Image

The base image declared in FROM is the single biggest factor in the final size. For the same language, there are variants with different trade-offs:

Variant Approximate size When to use
python:3.12 ~1 GB You need the full build toolchain
python:3.12-slim ~150 MB Most cases — minimal Debian
python:3.12-alpine ~50 MB Size is critical; watch out for compatibility

alpine uses musl instead of glibc, which occasionally breaks Python dependencies with C-compiled extensions (like numpy or psycopg2) — it’s worth testing before adopting it in production, instead of assuming it’s always the best choice just because it’s the smallest image.

6. .dockerignore: Cutting What Shouldn’t Even Reach the Build

Before any instruction runs, Docker sends the whole build context (the directory passed as the last argument to docker build, for example .) to the daemon. Without a .dockerignore, this usually includes irrelevant — and sometimes sensitive — junk:

# .dockerignore
.git
node_modules
__pycache__
*.pyc
.env
.venv
*.log

Besides speeding up sending the context (relevant in projects with heavy dependencies stored locally, like node_modules), this prevents leaking secrets: a .env with credentials accidentally copied via COPY . . is permanently baked into an image layer, even if a later step deletes it.

7. Conclusion and Next Steps

Understanding layers and the build cache changes how you write Dockerfiles: ordering instructions from least to most volatile, combining related RUNs, choosing the right base image for the use case and keeping an up-to-date .dockerignore are habits that pay off in faster builds and smaller images from day one. In the next article, the subject moves from how images are built to how containers communicate: networks, volumes and data persistence.


References:

  1. Docker Documentation — Dockerfile Best Practices
  2. Docker Documentation — Build Cache