✦ For everyone, free.

Practical knowledge for real and everyday life

Home

4.3.2.5 Build Dependency Removal

A focused guide to Build Dependency Removal, connecting core concepts with practical Docker and container operations.

Build dependency removal is the practice of ensuring that compilers, development headers, and other tools needed only to build an application — not to run it — never end up in the final image, typically achieved through multi-stage builds rather than installing and later attempting to remove them within a single stage.

Why Removal Within a Single Stage Doesn't Work Well

Installing build dependencies and later removing them within the same image stage does not actually reduce the image's size if the installation and removal happen in separate layers, since the earlier layer's content remains regardless of what a later layer removes from the visible filesystem.

RUN apt-get install -y build-essential
RUN pip install -r requirements.txt
RUN apt-get remove -y build-essential

Despite appearing to clean up, this produces an image where the removed package's data still exists in an earlier, unaffected layer.

Combining Install and Removal Within the Same Layer

If avoiding multi-stage builds for some reason, combining installation, use, and removal within a single RUN instruction does achieve genuine size reduction, since the resulting single layer reflects only the final, cleaned-up state.

RUN apt-get install -y build-essential \
    && pip install -r requirements.txt \
    && apt-get remove -y build-essential \
    && rm -rf /var/lib/apt/lists/*
The Cleaner Alternative: Multi-Stage Builds

Multi-stage builds avoid this complexity entirely by never including build dependencies in the final image's layer history at all, rather than installing and then removing them within it.

FROM python:3.12 AS build
RUN apt-get install -y build-essential
RUN pip wheel --wheel-dir=/wheels -r requirements.txt

FROM python:3.12-slim
COPY --from=build /wheels /wheels
RUN pip install --no-index --find-links=/wheels -r requirements.txt

The final image's layer history contains no trace of build-essential at all, since it only ever existed in the discarded build stage.

Why Build Dependency Removal Matters

Build dependencies are often substantial in size and present an unnecessary attack surface if they end up in a final production image — ensuring they are removed correctly (or, better, never included at all through multi-stage builds) is one of the more impactful size and security optimizations available.