Optimizing Docker image size and why it matters
A common mistake that's not covered in this article is the need to perform your add & remove operations in the same RUN command. Doing them separately creates two separate layers which inflates the image size.This creates two image layers - the first layer has all the added foo, including any intermediate artifacts. Then the second layer removes the intermediate artifacts, but that's saved as a diff against the previous layer:    RUN ./install-foo
    RUN ./cleanup-foo

Instead, you need to do them in the same RUN command:    RUN ./insall-foo && ./cleanup-foo

This creates a single layer which has only the foo artifacts you need.This why the official Dockerfile best practices show[1] the apt cache being cleaned up in the same RUN command:    RUN apt-get update && apt-get install -y \
        package-bar \
        package-baz \
        package-foo  \
        && rm -rf /var/lib/apt/lists/*

[1] https://docs.docker.com/develop/develop-images/dockerfile_be...