Docker image optimization

9 November 2026 · 6 MIN READ

Docker image optimization: multi-stage builds, caching, and .dockerignore

Why images get bloated, and the four habits that make builds smaller, faster, and cheaper to ship.

Smaller images are not vanity

Image size is operational cost you pay forever: slower pulls on every deploy, slower pushes from CI, more attack surface, and registry storage bills that grow quietly.

The fix is rarely one clever trick. It is four habits, applied every time a Dockerfile is touched.

Multi-stage builds: leave the toolchain behind

Compilers, package managers, and build caches have no business inside a running container. Build in one stage, copy the artifact into a minimal runtime stage, and ship only that.

Dockerfile · multi-stage pattern
# Stage 1: build
FROM node:22 AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# Stage 2: run
FROM node:22-slim
WORKDIR /app
COPY --from=build /app/dist ./
CMD ["node", "server.js"]

Order layers for cache hits

Docker caches layer by layer. Copying dependency manifests and installing packages before copying application source means an everyday code change rebuilds one fast layer instead of re-downloading everything.

The same reasoning applies in CI: build cache mounts and registry cache imports keep the pipeline from paying full price on every push.

layer order · the change that matters
# Cache-hostile
COPY . .
RUN npm ci

# Cache-friendly
COPY package*.json ./
RUN npm ci
COPY . .

.dockerignore is a security file too

Most people learn .dockerignore as a size feature. It is also a safety feature: without it, .git history, .env files, and local node_modules ride along into the build context, and anything COPY . . picks up can end up in the image.

A minimal ignore file excludes all three, plus documentation and test fixtures that never belong in a runtime image.

.dockerignore · baseline
.git
.env*
node_modules
README*
tests/

Tag images the way you will need to find them

Every image gets the commit SHA as a tag, so the running container traces back to its source. Release versions get an explicit tag too. The mutable “latest” tag is a last-resort fallback, never the thing a deployment points at.

A tag you cannot trace is a rollback you cannot perform — and rolling back at 2am is the moment this habit earns its keep.

Alvin K Sabu ›Docker image optimizationMade to be explored.

alvin — bash — 80 × 24

Welcome to Alvin’s desktop.

Type help to explore. This is a browser simulation.

esc to close

Search this desktop

↑ ↓ to navigate ↵ to openesc to close

A little desktop tour

Click an app in the dock or a folder in the sidebar. The window controls work, too.

Search everything
Ctrl / ⌘ K
Open terminal
`
Overview / Projects / About / Toolbox / Contact
1 — 5
Close a dialog or menu
Esc

Pipeline Lab and Terminal are local demos. They never connect to production infrastructure.