Multi-stage builds feature allow you to add multiple FROM instructions in the Dockerfile.
The FROM instructions are basicaly the same as the regular single FROM instructions that we have used previously.
Each FROM instruction define a build stage that has its base image and a set of instructions to build images layers.
A FROM instruction should have a name which can be used by other FROM instructions as a reference.
The FROM instruction that references another one, will be able to copy artifacts created within that staging build.
A staging build can be considered as a temporary build that we can use in the next staging builds to copy only the artifacts that we need and discards everything else.
The goal is to have an optimized final stage (in term of disk space) that in theory will be the one that we will use for the image we want to create.
Let's use this Dokerfile (not a very useful one but it's simple enough to demonstrate the multi-stage builds feature):
Let's build the Dockerfile:
Let's have a look at the image history:
As you can see, the image does contain only the layers of the base image (alpine) and the layer of the COPY instruction.
Notes:
-
Assigning a name to a stage build is recommended but not mandatory.
Instead of using the name of the stage build you can reference it by its number.
The first FROM instruction in the Dockerfile has the number 0 and the following will be numbered 1,2,3, and so on.
To reference the first build stage, you do:
COPY --from=0 ...
-
It's also possible to copy artifacts from external images (kind of using the image as a stage):
-
You can also use a stage build as a base image for the FROM instruction: