Reduce Docker Image Size

The way to reduce Docker image size is to build your image in multiple stages. Copy the results of the previous stage to the next stage. Only the results of the last stage are included in the final image, the previous stages are discarded, resulting in a smaller image size.

However, these intermediate stages will take up space on your local machine and will become dangling images if they are not used by any other image.

For example, if you are building a Node.js application, you can use the following multi-stage Dockerfile.

# Stage 1: The Build (History created here stays here)
FROM node:18 AS builder
WORKDIR /app
COPY . .
RUN npm install && npm run build  # Large layers created

# Stage 2: The Final Image (Clean history)
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
# Only the files in /dist exist; all 'npm install' layers are gone.
  1. In stage 1, npm install will download all the packages into node_modules, which is huge. npm run build will create a dist folder with your production-ready code, which is much smaller.
  2. In stage 2, you only copy the dist folder to the final image, and all the files in stage 1 are discarded, resulting in a much smaller image size.

Clean Up Intermediate Layers

There are multiple ways to clean up intermediate layers after building your image:

  • You can use docker build --rm .... to automatically remove intermediate containers after a successful build.
  • Or, you can also use system-wide docker builder prune to remove all dangling images and build cache, which will free up space on your local machine.