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.<p>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:<p><pre><code>    RUN ./install-foo
    RUN ./cleanup-foo
</code></pre>
Instead, you need to do them in the same RUN command:<p><pre><code>    RUN ./insall-foo && ./cleanup-foo
</code></pre>
This creates a single layer which has only the foo artifacts you need.<p>This why the official Dockerfile best practices show[1] the apt cache being cleaned up in the same RUN command:<p><pre><code>    RUN apt-get update && apt-get install -y \
        package-bar \
        package-baz \
        package-foo  \
        && rm -rf /var/lib/apt/lists/*
</code></pre>
[1] <a href="https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#run" rel="nofollow">https://docs.docker.com/develop/develop-images/dockerfile_be...</a>