Multi-stage Docker builds helps reduce the size of Docker images. It is supported in Docker versions 17+.
Using multi-stage builds, we can ensure that only the application and its necessary components are shipped. Previously a lot of complicated manipulation with shell scripts was required to clean up the shippable image.
Below is an example with a ASP.NET.
The sample ASP.NET code. It can be found at https://github.com/dotnet/dotnet-docker/tree/master/samples
1 — Use aspnetcore-build as base image for the first stage. This stage is named as build-env
2 — Set working directory for all further instructions
3 and 4 — Copy all csproj files and restore all project dependencies
5 — Copy all the other files
6 — Start build and output it to out directory
7 — Use aspnetcore as base imagefor the second and final stage
8 — Set working directory for all further instructions
9 — Using the name of the first stage ( build-env) to reference it in this stage
and copy the build artifacts
10 — Run the application using the artifact
Build the image using current directory as build context
Listing images, notice the reduced image size