BeCuriouzLearn something new every day
Why changing one line rebuilds your Docker image in a second
💡 A Docker image is a stack of cached, shareable filesystem layers — so ordering your Dockerfile from least- to most-frequently-changed makes builds dramatically faster.
A Docker image isn't one big blob — it's a stack of read-only layers, each one a frozen snapshot of the filesystem changes made by a single build step. Every instruction in a Dockerfile (COPY, RUN, ADD) produces a new layer on top of the previous ones. When you run a container, Docker adds a thin writable layer on top and presents the whole stack as one unified filesystem using a union filesystem (like OverlayFS).
The magic is the build cache. Because each layer is identified by a hash of its inputs, Docker can reuse a layer unchanged from a previous build. If you edit line 40 of your app, Docker reuses every cached layer up to that point and only rebuilds from the changed step onward — which is why a tiny code change rebuilds in a second instead of re-downloading your whole OS and dependencies.
This is also why layer order matters so much. Put slow-changing things (installing dependencies) before fast-changing things (copying your source code). If you copy your code first, every code edit invalidates the cache for the dependency install below it, forcing a full reinstall every time.
Layers are also shared across images: if ten images all build on ubuntu:22.04, that base layer is stored on disk exactly once and shipped over the network once. This copy-on-write sharing is what makes containers cheap to store and fast to pull.