Docker · Containers in practice

How do you reduce Docker image size?

Mediumimage sizebase imagesbuildUpdated Oct 2026
Quiz this track

Short answer

Use a minimal base, a multi-stage build, combined RUN layers and a small .dockerignore. Remove build tooling and package caches from the final stage rather than deleting them later.

Image size affects pull time, cold-start latency and the number of packages that need patching. The biggest wins usually come from choosing a smaller runtime base and not shipping compilers, test frameworks or source code.

sh
docker history --no-trunc api:1.0.0
docker images --format "table {{.Repository}} {{.Tag}} {{.Size}}"
docker run --rm -it --entrypoint sh api:1.0.0
Inspect layer sizes and then look at what is actually installed in the image.

Techniques that work

  • Use a slim or distroless runtime base when compatible
  • Build in one stage and copy only the artifact into the final stage
  • Combine install and cleanup in a single RUN so caches are not left in a layer
  • Exclude node_modules, .git and build output from the context
  • Remove dev dependencies from the production install

Alpine is small but uses musl libc, which can break native modules and cause DNS or certificate differences. Debian slim or distroless is often a safer small base. Measure with docker history rather than assuming the smallest tag is best.

Deleting a file in a later layer does not reduce the image size. The bytes still exist in the earlier layer and are pulled by clients.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Why does deleting files in a later layer not shrink the image?
  2. 2What are the risks of using Alpine?
  3. 3How does docker history help find large layers?
  4. 4How would you verify the final image contains no build tools?

Say it in the interview

I reduce size by choosing a minimal runtime base, using a multi-stage build and copying only the artifact forward. I also combine install and cleanup into one RUN, because deleting files later does not remove them from the earlier layer. I check docker history to find the actual heavy layers instead of guessing.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Docker mock interview and get scored feedback on depth, clarity and confidence.