Multi-Stage Dockerfiles

In this lesson, we will learn how to handle large images using multi-stage Dockerfiles.

The problem with the image we created above is that it’s massive; it’s 1730 MB! This is because it contains the build tools we don’t need, tools like dotnet restore and dotnet publish. Also, it contains the source code and intermediate build artifacts.

We could use the RUN command to try and clean the image; delete intermediate build artifacts, uninstall build tools, and delete source code, but that would be tedious. Remember that containers are like cheap, disposable machines; let’s dispose of the build machine and grab a brand new one that has only the runtime installed!

Docker has a neat way to do this; use a single Dockerfile file with distinct sections. An image can be named simply by adding AS at the end of the FROM instruction. Consider the following simplified Dockerfile file:

Get hands-on with 1200+ tech skills courses.