One changed line in a Dockerfile invalidates every layer after it. Ordering your Dockerfile with this in mind cuts rebuild times dramatically.
Docker layer caching is one of those things that seems obvious once you understand it, but wastes a lot of time before you do.
Every instruction in a Dockerfile creates a layer. If a layer changes, every subsequent layer is invalidated and must be rebuilt.
FROM node:20-alpine
WORKDIR /app
COPY . . # copies everything — changes constantly
RUN npm install # always re-runs, even if package.json didn't change
RUN npm run buildEvery time any source file changes, npm install re-runs. On a project with hundreds of dependencies, this is painful.
Karanveer Singh Shaktawat
Full Stack Engineer & Infrastructure Architect
Building portfolio, contributing to open source, and seeking remote full-time roles with significant technical ownership.
Pick what you want to hear about — I'll only email when it's worth it.
Did this resonate?
How to use Docker multi-stage builds to go from a 2GB Rust build image to a 12MB production image.
Without keepalive on Nginx upstream blocks, every proxied request opens a new TCP connection to your backend. One directive fixes this.
FROM node:20-alpine
WORKDIR /app
COPY package.json package-lock.json ./ # only these files
RUN npm install # only re-runs when package.json changes
COPY . . # source files copied after deps
RUN npm run buildNow npm install only re-runs when package.json or package-lock.json changes. Source code changes only trigger the COPY . . and npm run build layers.
Order layers from least frequently changing to most frequently changing:
apt-get install)package.json, Cargo.toml, requirements.txt)npm install, cargo fetch, pip install)This pattern cut rebuild times on the Mailcow monitoring container from ~4 minutes to under 30 seconds. Same image, different Dockerfile ordering.
With DOCKER_BUILDKIT=1, you can also use multi-stage builds where independent stages run in parallel. But fixing layer ordering should come first — it's simpler and often enough.