CoursesDocker for beginnersBuilding your own images

The layered filesystem & build cache

Why instruction order makes builds fast.

Beginner12 min · lesson 10 of 16
In plain terms
Picture sheets of tracing paper stacked on top of each other, each adding a few marks. Docker builds an image the same way, one sheet per instruction, and it reuses the bottom sheets it already has — so if only the top sheet changed, it redraws just that one.

Every instruction in a Dockerfile that changes the filesystem produces a layer, and an image is just those layers stacked on top of each other, read-only. Layers are content-addressed and shared: if two images start FROM the same base, that base is stored once on disk and pulled once over the network. When you run a container, Docker adds one thin writable layer on top of the image’s read-only stack — that is where the running container’s changes go.

An image is a stack of layers
container (running)
writable layer
per-container, ephemeral
image (read-only, shared)
COPY . .
your source
RUN npm ci
dependencies
FROM node:22-alpine
the base — shared across images
Read bottom-up: each instruction adds a layer. The base is shared; only the writable layer is per-container.

The build cache

Docker caches layers and reuses them on the next build — until it hits the first instruction whose inputs changed, after which every layer below is rebuilt. That single rule dictates how you order a Dockerfile: put the things that change rarely (installing dependencies) before the things that change every commit (copying source). Get the order right and rebuilds drop from minutes to seconds; get it wrong and every one-line code change reinstalls all your dependencies.

Dockerfile
# SLOW: any source change busts the cache for npm ci, reinstalling every build
COPY . .
RUN npm ci
# FAST: deps only reinstall when package.json changes, not on every code edit
COPY package*.json ./
RUN npm ci
COPY . .

Why this matters beyond speed

Layer sharing also makes pulls cheap: when you push a new version, only the changed layers upload, and nodes that already have the base only download the small top layers. Fast, well-ordered builds are not just a convenience — they are what makes it practical to rebuild and redeploy on every commit.

Deleting a file does not remove it from the image
Because layers are stacked, a file added in one layer and deleted in a later one still ships inside the earlier layer — recoverable by anyone with the image. This is why you never COPY a secret in and delete it later, and why it is a recurring theme in the security courses. A secret in any layer is a secret in the image.