CloudDevOpsDockerFeatured

Docker Image Size Optimization: Multi-Stage Builds and Layer Caching

6 Mins read

Build Leaner Docker Images Without Slowing Down Development

Large Docker images take longer to build, push, pull, scan, and deploy. The good news is that slimming an image does not have to mean making your development workflow slower or sacrificing useful tools during compilation. The most reliable approach combines multi-stage builds, careful layer ordering, and a minimal—but compatible—runtime base image.

This guide walks through a practical Docker image size optimization workflow, including a multi-stage Node.js example, build-cache techniques, measurement steps, and trade-offs to check before shipping.

Why Docker Image Size Matters

A Docker image is made from layers. Each instruction that changes files can add data to the image, and files copied into a later layer are not erased from earlier layers merely because a subsequent instruction deletes them. A cleanup command may therefore make the final filesystem look tidy without reducing the bytes stored in the image.

Smaller images can reduce registry storage and network transfer, and they can make deployments faster—especially when hosts need to pull an image from scratch. They may also contain fewer packages to patch and scan. Actual security depends on what is included, how it is maintained, and how the application is configured; a smaller image is not automatically a secure one.

Start by Measuring the Image

Optimize based on evidence rather than guessing. Build your current image and record its size:

docker build -t demo-app:before .
docker image ls demo-app

For more detail, inspect the layers:

docker history demo-app:before

Image size can be reported in different ways. The size shown by Docker is not necessarily the same as the compressed size transferred from a registry, because layers may be compressed during transfer and shared between images on the same machine. Compare images using the same tool and measurement method.

Use Multi-Stage Builds to Separate Building from Running

Compilers, development dependencies, test tools, and package managers are often needed to create an application but not to run it. A multi-stage Dockerfile lets you install and build in one stage, then copy only the required output into a separate runtime stage.

Example: Multi-Stage Dockerfile for Node.js

This example assumes the project has a lockfile and a build script that produces a self-contained dist directory. Adjust the output directory and runtime requirements for your application.

# syntax=docker/dockerfile:1

FROM node:22-bookworm-slim AS build
WORKDIR /app

# Copy dependency manifests first to preserve the dependency-install cache.
COPY package.json package-lock.json ./
RUN npm ci

# Copy source only after dependencies are installed.
COPY . .
RUN npm run build

FROM node:22-bookworm-slim AS runtime
ENV NODE_ENV=production
WORKDIR /app

# Copy only the files required at runtime.
COPY --from=build --chown=node:node /app/dist ./dist
COPY --from=build --chown=node:node /app/package.json ./package.json

USER node
CMD ["node", "dist/server.js"]

The first stage contains installed dependencies and build tools. The final stage starts from a clean base and receives only selected files. Those build-stage files do not become part of the final image unless they are explicitly copied into the runtime stage.

Check the application’s actual runtime needs before using this pattern. If the app imports production packages from node_modules, the example must also provide those packages in the final image. One option is to install production dependencies in a dedicated stage and copy them into the runtime stage. Do not assume that copying compiled output alone is sufficient.

Build and inspect a specific stage

docker build --target build -t demo-app:build .
docker build --target runtime -t demo-app:runtime .
docker image ls demo-app

The --target flag is useful for debugging or running checks against a named stage. For release, build the intended final target and test the resulting image—not only the builder.

Improve Build Cache Reuse

Docker can reuse the result of a build step when the instruction and the files it depends on have not changed. Once a step changes, later steps may need to run again. Ordering instructions thoughtfully can keep frequently reused work cached.

Copy dependency manifests before source code

In the example, package.json and package-lock.json are copied before the rest of the source. Editing an application file then does not invalidate the dependency-install step. Changing the lockfile does, as it should.

This is an example of build caching: Docker reuses previous work when its inputs remain the same. For a general introduction, see FromDev’s guide to what caching is and why it is used.

Keep the build context small

Docker sends the build context—the files available to the build—to the builder. Exclude irrelevant files with a .dockerignore file:

node_modules
.git
dist
coverage
.env
*.log

Do not exclude files the Dockerfile needs. In particular, a lockfile required by npm ci must remain in the context. Keep secrets out of the context rather than copying them into an image and trying to delete them later.

Use BuildKit cache mounts where they help

For package managers that support it, BuildKit cache mounts can preserve downloaded package data between builds without adding that cache to the resulting image:

# syntax=docker/dockerfile:1
RUN --mount=type=cache,target=/root/.npm \
    npm ci

Cache mounts are a build-time optimization, not a substitute for correct layer ordering. They require BuildKit, and the cache may not be available on a new builder or in every CI environment. Treat it as disposable: the build must still work when the cache is empty.

Choose a Minimal, Compatible Runtime Base

Once build tools are excluded, the runtime base is often the next major source of image size. Compare official slim or minimal variants, but choose based on compatibility rather than the smallest label alone.

  • Full distribution images include more system packages and familiar debugging tools, but can add considerable size.
  • Slim variants remove many nonessential packages while retaining a conventional distribution environment. They are often a practical starting point.
  • Alpine images use musl rather than glibc. Some native modules or prebuilt binaries expect glibc and may fail or require rebuilding.
  • Distroless images can omit shells and package managers. This reduces what is available inside the container but changes debugging and operational workflows.

Pin a deliberate base-image version and update it regularly. A tag such as node:22-bookworm-slim is clearer than relying on an unqualified latest tag, but tags can still move. For stronger reproducibility, teams can pin an image digest and update it through a controlled process.

Common Size-Optimization Pitfalls

Deleting files in a later layer

This pattern does not reliably shrink an image:

RUN apt-get update && apt-get install -y build-essential
RUN apt-get purge -y build-essential

The installed files were recorded in an earlier layer. If you must install and remove packages in one stage, do both in the same RUN instruction and remove package-manager metadata there. Better still, keep build-only packages in a builder stage.

Using a base image that is too minimal

A smaller base can introduce missing certificates, shared libraries, timezone data, or other runtime requirements. Native code adds another compatibility concern: compiled extensions must match the operating system and libraries in the final stage. Build and run tests using the same compatible family of base images, and verify the final container starts in a production-like environment.

Copying too much into the runtime stage

A broad instruction such as COPY . . in the final stage can bring source maps, tests, local configuration, or development files along for the ride. Prefer explicit copies of required artifacts and use .dockerignore as a second line of defense.

Removing useful diagnostics without a plan

A stripped-down image can be harder to investigate when a production issue occurs. Decide how your team will collect logs, inspect health, and debug containers before removing shells or tools. Debugging a container should not depend on adding secrets or untrusted utilities to the production image.

A Practical Optimization Checklist

  1. Measure the current image and inspect its largest layers.
  2. Add a .dockerignore file to exclude local and unnecessary files.
  3. Order dependency manifests before frequently changing source files.
  4. Move compilation and development tools into a builder stage.
  5. Copy only runtime artifacts and required production dependencies into the final stage.
  6. Compare compatible base images, then test native modules and system-library requirements.
  7. Rebuild, inspect the final image, and run the same tests and startup checks you use for release.
  8. Track image size in CI if regressions are costly, while treating size thresholds as signals to investigate—not proof of quality.

Conclusion

The most dependable way to reduce Docker image size is to keep the runtime image focused: build in a separate stage, copy only what the application needs, and choose a compatible minimal base. Good layer ordering and BuildKit caches make that workflow faster to repeat, while measurement confirms whether a change actually helped.

Optimize for the image you can safely build, run, debug, and maintain—not just the smallest number. Validate the final stage, watch for dependency and native-library surprises, and keep updating the base image so size improvements do not come at the cost of reliability.

Leave a Reply

Your email address will not be published. Required fields are marked *