Skip to main content

Reducing Docker Image Size

Shrink Docker images from gigabytes to megabytes with smaller base images, multi-stage builds, cache cleanup and BuildKit cache mounts.

44 Terms

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.

flowchart TD A[Measure
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.

Bash
docker images payment-api
# Size and instruction for each layer, biggest first
docker 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/dive
brew install dive
dive payment-api:latest
# CI-friendly check that fails when efficiency is too low
CI=true dive payment-api:latest --ci --lowestEfficiency=0.95
Milestone 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.

Bash
# .dockerignore
.git
node_modules
dist
coverage
*.log
*.md
docs/
.env
.env.*
Dockerfile*
compose*.yaml
Security

Excluding .env and .git also 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.

Dockerfile
# BEFORE: single stage, everything ships
FROM node:20
WORKDIR /app
COPY . .
RUN npm install
RUN npm run build
CMD ["node", "dist/server.js"]
Dockerfile
# AFTER: build tools stay in the builder
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY package.json package-lock.json ./
RUN npm ci --omit=dev && npm cache clean --force
COPY --from=builder /app/dist ./dist
USER node
CMD ["node", "dist/server.js"]
Bash
docker build -f Dockerfile.before -t payment-api:before .
docker build -f Dockerfile.after -t payment-api:after .
docker images payment-api
Milestone 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
Bash
docker pull node:20
docker pull node:20-slim
docker pull node:20-alpine
docker images node

Alpine 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:

Bash
trivy image --severity CRITICAL,HIGH node:20 | tail -5
trivy image --severity CRITICAL,HIGH node:20-alpine | tail -5
Milestone 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.

Dockerfile
# WRONG: package lists stay in the first layer
RUN apt-get update && apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*
# RIGHT: nothing is ever committed to a layer
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*
# Alpine: --no-cache never writes the index
RUN apk add --no-cache curl
# pip and npm
RUN pip install --no-cache-dir -r requirements.txt
RUN npm ci --omit=dev && npm cache clean --force

Combine commands that produce temporary files, and delete those files in the same instruction:

Dockerfile
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.tgz
Milestone 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.

Dockerfile
# syntax=docker/dockerfile:1
FROM node:20-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm \
npm ci --omit=dev
COPY . .
Dockerfile
# syntax=docker/dockerfile:1
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt ./
RUN --mount=type=cache,target=/root/.cache/pip \
pip install -r requirements.txt
COPY . .
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.

Bash
docker images myapp
# Look for leftovers inside the image
docker run --rm myapp:v3 sh -c 'ls -la /root/.npm /var/cache 2>/dev/null; find / -name "*.test.js" 2>/dev/null | head'
# Layer efficiency
dive myapp:v3

Production Best Practices & Common Pitfalls

  1. Measure, change, re-measure. Record the size after each change so you know what helped.
  2. Build in one image, ship from another. Multi-stage is the standard pattern for compiled and bundled apps.
  3. Pin base image versions. Use specific tags (node:20.18-alpine) so size and content do not drift silently.
  4. Install only runtime packages in the final stage. Use --no-install-recommends on Debian.
  5. Keep .dockerignore in every repo. It is the cheapest optimization.
  6. Test on the final base. A smaller base that breaks at runtime is not an optimization.
Common Mistake

Running apt-get clean or rm -rf in a separate RUN after 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-trunc plus sort -rh shows the largest layers with the exact Dockerfile line that created each one.

Remember

Layers 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

Resources

Explore More in Docker Images and Registry Management

All 4 Topics

Frequently Asked Questions

Is Reducing Docker Image Size free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Reducing Docker Image Size topic cover?

Shrink Docker images from gigabytes to megabytes with smaller base images, multi-stage builds, cache cleanup and BuildKit cache mounts.

Found a mistake, an outdated step or a broken link?