Overview and What You Will Learn
To reduce a Docker image's size you remove everything the running application does not need: build tools, dev dependencies, package manager caches and unused files. The biggest wins, in order, are a multi-stage build, a smaller base image, a .dockerignore file and cleaning caches in the same layer that creates them. Always measure first, because guessing wastes time.
In this lab you will:
- Find exactly which layers and files make an image large
- Apply the four highest-impact techniques and measure each one
- Choose between full, slim, Alpine and distroless bases
- Use BuildKit cache mounts for fast rebuilds without bloating the image
Why This Matters in Production
Image size affects pull time, registry storage cost, scan noise and cold-start speed. When a platform like Grab or Swiggy scales out for a dinner-hour surge, every new node pulls the image before it can serve traffic, so the image size is part of how quickly capacity arrives. A smaller image is also a smaller attack surface, because every package you do not ship is a package that cannot be exploited.
Core Principles
An image is a stack of read-only layers, and a layer can only add data. Deleting a file in a later layer hides it but the bytes remain in the earlier layer, so cleanup must happen in the same RUN that created the files.
docker history and dive] --> B[Multi-stage build] B --> C[Smaller base image] C --> D[.dockerignore] D --> E[Clean caches in same RUN] E --> F([Re-measure and stop]) classDef step fill:#DBEAFE,color:#1E293B classDef done fill:#10B981,color:#FFFFFF class A,B,C,D,E step class F done
| Technique | Typical impact |
|---|---|
| Multi-stage build | Largest, often hundreds of MB |
| Smaller base image | Large, hundreds of MB |
.dockerignore |
Medium, depends on repo contents |
| Cache cleanup in same layer | Small to medium |
Detailed Step-by-Step Practical Lab
Milestone 1: Measure Before You Change Anything
Find which layers are large and what is inside them, then fix the largest thing first.
docker images payment-api # Size and instruction for each layer, biggest firstdocker history payment-api:latest --no-trunc \ --format '{{.Size}}\t{{.CreatedBy}}' | sort -rh | head -10 # Interactive explorer showing files added per layer and wasted space# https://github.com/wagoodman/divebrew install divedive payment-api:latest # CI-friendly check that fails when efficiency is too lowCI=true dive payment-api:latest --ci --lowestEfficiency=0.95Milestone 2: Add a .dockerignore
COPY . . sends your whole build context to the daemon and into the image. A .dockerignore keeps junk out and makes builds faster.
# .dockerignore.gitnode_modulesdistcoverage*.log*.mddocs/.env.env.*Dockerfile*compose*.yamlSecurityExcluding
.envand.gitalso keeps secrets and history out of the image. Anything copied into a layer can be extracted by anyone who can pull the image.
Milestone 3: Switch to a Multi-Stage Build
This is usually the single biggest reduction. Build in a full image and ship only the output.
# BEFORE: single stage, everything shipsFROM node:20WORKDIR /appCOPY . .RUN npm installRUN npm run buildCMD ["node", "dist/server.js"]# AFTER: build tools stay in the builderFROM node:20-alpine AS builderWORKDIR /appCOPY package.json package-lock.json ./RUN npm ciCOPY . .RUN npm run build FROM node:20-alpineWORKDIR /appENV NODE_ENV=productionCOPY package.json package-lock.json ./RUN npm ci --omit=dev && npm cache clean --forceCOPY --from=builder /app/dist ./distUSER nodeCMD ["node", "dist/server.js"]docker build -f Dockerfile.before -t payment-api:before .docker build -f Dockerfile.after -t payment-api:after .docker images payment-apiMilestone 4: Pick the Right Base Image
The base image is often most of the final size. Choose the smallest one your application actually runs on.
| Base | Notes |
|---|---|
Full (node:20) |
Debian with build tools, use only in builder stages |
Slim (node:20-slim) |
Debian without extras, glibc compatible |
Alpine (node:20-alpine) |
Smallest common base, uses musl libc |
| Distroless | No shell or package manager, best for security |
docker pull node:20docker pull node:20-slimdocker pull node:20-alpinedocker images nodeAlpine uses musl instead of glibc, so native modules (for example some builds of bcrypt, sharp or canvas) can fail or behave differently. Test thoroughly before switching, and fall back to -slim if native dependencies break. Compare vulnerability counts yourself rather than trusting a rule of thumb:
trivy image --severity CRITICAL,HIGH node:20 | tail -5trivy image --severity CRITICAL,HIGH node:20-alpine | tail -5Milestone 5: Clean Caches in the Same Layer
A cleanup in a separate RUN does nothing for image size, because the earlier layer still holds the files.
# WRONG: package lists stay in the first layerRUN apt-get update && apt-get install -y curlRUN rm -rf /var/lib/apt/lists/* # RIGHT: nothing is ever committed to a layerRUN apt-get update \ && apt-get install -y --no-install-recommends curl \ && rm -rf /var/lib/apt/lists/* # Alpine: --no-cache never writes the indexRUN apk add --no-cache curl # pip and npmRUN pip install --no-cache-dir -r requirements.txtRUN npm ci --omit=dev && npm cache clean --forceCombine commands that produce temporary files, and delete those files in the same instruction:
RUN curl -fsSL https://downloads.devops.in/tool-1.4.2.tar.gz -o /tmp/tool.tgz \ && tar -xzf /tmp/tool.tgz -C /usr/local/bin \ && rm /tmp/tool.tgzMilestone 6: Use BuildKit Cache Mounts
A cache mount keeps the package manager cache on the build host between builds but never stores it in the image, so rebuilds are fast and the image stays small.
# syntax=docker/dockerfile:1FROM node:20-alpineWORKDIR /appCOPY package.json package-lock.json ./RUN --mount=type=cache,target=/root/.npm \ npm ci --omit=devCOPY . .# syntax=docker/dockerfile:1FROM python:3.12-slimWORKDIR /appCOPY requirements.txt ./RUN --mount=type=cache,target=/root/.cache/pip \ pip install -r requirements.txtCOPY . .CMD ["python", "app.py"]BuildKit is the default builder in current Docker releases. If your CI uses an old Docker, enable it with DOCKER_BUILDKIT=1 or use docker buildx build.
Milestone 7: Verify and Stop
Check the result, confirm nothing unwanted remains, then stop. Going from 2 GB to 200 MB is worth real effort, going from 200 MB to 180 MB usually is not.
docker images myapp# Look for leftovers inside the imagedocker run --rm myapp:v3 sh -c 'ls -la /root/.npm /var/cache 2>/dev/null; find / -name "*.test.js" 2>/dev/null | head' # Layer efficiencydive myapp:v3Production Best Practices & Common Pitfalls
- Measure, change, re-measure. Record the size after each change so you know what helped.
- Build in one image, ship from another. Multi-stage is the standard pattern for compiled and bundled apps.
- Pin base image versions. Use specific tags (
node:20.18-alpine) so size and content do not drift silently. - Install only runtime packages in the final stage. Use
--no-install-recommendson Debian. - Keep
.dockerignorein every repo. It is the cheapest optimization. - Test on the final base. A smaller base that breaks at runtime is not an optimization.
Common MistakeRunning
apt-get cleanorrm -rfin a separateRUNafter installing packages. The files are still in the previous layer, so the image does not shrink. Install and clean in one instruction.
Tip
docker history IMAGE --no-truncplussort -rhshows the largest layers with the exact Dockerfile line that created each one.
RememberLayers only add. The only ways to keep data out of an image are to never write it into a layer, or to leave it in a stage you do not copy from.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
docker images |
List image sizes |
docker history IMG |
Show layer sizes |
dive IMG |
Explore layer contents |
docker build --target STAGE . |
Build a single stage |
docker builder prune |
Clear build cache on the host |
| Symptom | Likely cause and fix |
|---|---|
| Still large after multi-stage | A COPY pulls too much, copy specific paths |
| Alpine native module fails | musl incompatibility, use slim or add build deps in builder |
| Cache mount has no effect | BuildKit disabled or wrong target path |
Distroless container exits with exec format error |
Entrypoint is a script, use a compiled binary or a shell-capable base |
| Build context is huge | Missing .dockerignore, exclude node_modules and .git |