How to Slim Down a Large Docker Image
Diagnose and shrink a bloated Docker image: layer analysis, smaller bases, pruning dev dependencies and removing build leftovers.
On this page
Introduction
A large image is slow to pull, slow to deploy and carries packages you do not need and must patch. The cause is usually visible once you look: the base is too heavy, build tooling and dev dependencies are left in, or a layer includes files it should not. Slimming an image is a diagnosis followed by a few targeted changes, and the result is a smaller attack surface as much as a faster pull.
Measure Before You Change
Start by measuring: the total image size and the size of each layer. A layer analysis shows which instructions add the most, and it is usually one or two layers: a base image, or an install that pulled a toolchain. Guessing without measuring often optimises the wrong layer.
Compare the image size to the size of the application’s actual runtime artifacts. If the artifacts are ten megabytes and the image is a gigabyte, almost all of it is something the runtime does not need. That gap is the target.
Measure the compressed size too, since that is what a pull transfers. A layer of already-compressed artifacts costs nearly its full size to transfer, while a layer of text or source compresses well; knowing which layers are which tells you where a reduction actually helps the pull.
A layer analysis also reveals layers that could be merged: several small installs that each left a cache are often one instruction away from being a single small layer, which is a common source of avoidable size.
# measure total and per-layer sizes
docker image ls --format '{{.Repository}}:{{.Tag}} {{.Size}}' myapp
docker history --no-trunc myapp:latest # per-layer size
# compare to the real runtime artifact:
du -sh dist node_modules # what actually needs to ship
# the gap between the two is what to remove
Choose a Smaller Base
The base image sets the floor. A full OS base can be hundreds of megabytes; an Alpine base is tens; a distroless base is smaller still and has no shell or package manager. Choose the smallest base that provides the runtime the application needs.
Smaller bases also have fewer packages to patch, which reduces the vulnerability surface. Moving from a full distribution base to a slim or distroless one is often the single biggest reduction, and it also removes tools an attacker could use inside the container.
# base choices, roughly smallest to largest
# FROM gcr.io/distroless/nodejs20-debian12 # no shell, no package manager
# FROM node:20-alpine # small, has a shell
# FROM node:20-slim # small Debian
FROM node:20-alpine AS runtime
# the base is the floor: pick the smallest one the app can run on
Remove Build Tooling and Dev Dependencies
The classic bloat is the build toolchain and dev dependencies in the runtime image. A multi-stage build solves it: build in a heavy stage, then copy only production dependencies and the build output into the runtime. If you cannot use multiple stages, prune dev dependencies in the same image after the build.
For Node, prune the development dependencies (pnpm prune –prod, npm prune –omit=dev) so the image does not carry test frameworks, linters and build tools. For compiled languages, the compiler and its headers should not be in the runtime at all.
# strip dev dependencies from the runtime image
FROM node:20-alpine AS runtime
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules # already prod-only
# builder ran: pnpm install && pnpm build && pnpm prune --prod
Clean Up in the Same Layer
Docker layers are additive: deleting a file in a later instruction does not shrink the image, because the earlier layer still holds it. Package-manager caches, downloaded archives and temporary files must be removed in the same RUN that created them, not in a separate instruction.
Chain the install and the cleanup with && in one RUN so the cache and archives never become a layer. This is the reason a single-instruction install that leaves its cache looks huge while a chained install-and-clean of the same packages is small.
# WRONG: the cache is in an earlier layer and still counts
RUN apt-get update && apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/* # too late: the layer above still has it
# RIGHT: install and clean in the SAME layer
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*
Tighten the Build Context
The build context affects what can be copied into the image, and a large context slows the build and can leak files. A .dockerignore that excludes node_modules, .git, tests, docs and build output keeps the context small and prevents accidental inclusion of secrets or stale artifacts.
Also avoid CAPTURE-and-copy of the whole directory when you only need a few files: COPY . . copies everything not ignored, including local build output that then overrides the fresh build. Copy only what the stage needs.
# .dockerignore keeps the context small AND prevents leakage
.git
node_modules
dist
coverage
*.log
.env
.env.*
test
docs
# also: avoid COPY . . where possible; copy only the files each stage needs
Compression, Squash and Registry Effects
The image size on a registry is compressed, so the transfer size differs from the uncompressed size. Removing a big layer reduces both, but a layer of incompressible data (already-compressed artifacts) benefits little from compression. Measure both sizes to understand what a pull costs.
Some tools can squash layers into one to remove duplicates across layers, but this sacrifices layer caching and can be a marginal gain. Prefer removing the bloat from the layers themselves over squashing, and treat squashing as a last resort for a specific case.
# size on the registry is compressed; local size is uncompressed
# removing a big layer helps both; already-compressed data compresses little
# squashing layers: removes cross-layer duplication but loses layer caching
# prefer fixing the layers over squashing (squash = last resort)
Common Pitfalls and Conclusion
Do not optimise without measuring; you will shrink the wrong layer. Do not delete files in a later instruction, which does not shrink the image. Do not leave dev dependencies or build tooling in the runtime. Do not copy the whole context when a few files suffice. And do not squash layers to hide bloat that should be removed.
A large image is slimmed by measuring the layers, choosing the smallest viable base, moving the build to a multi-stage pipeline and copying only production artifacts, chaining installs with their cleanup, and keeping the build context tight. Each of those is a targeted change, and together they turn a gigabyte image into one that pulls in seconds and carries only what runs.
Sources: Docker: Multi-stage builds, Google: Distroless images, Docker: .dockerignore.
FAQ
- Why does deleting a file not shrink my image?
- Because layers are additive. Deleting a file in a later instruction leaves it in the earlier layer that created it, so the image still contains it. Remove files in the same RUN that created them, using && to chain.
- What is usually the biggest reduction?
- Moving to a smaller base image and splitting the build into stages so the runtime carries no build tooling or dev dependencies. For many Node images, those two changes alone remove most of the size.
Report a problem with this articleOpens a pre-filled issue on GitHub.