dockerfiledocker-multi-stage-build

Why Multistage Image build? Why not Basic images?


Below is a sample Docker Multistage build file I am working for a documentation.

'''

FROM mcr.microsoft.com/dotnet/sdk:7.0 AS Dev
COPY *.csproj ./
WORKDIR /crud/
COPY . .
RUN dotnet publish -c Release -o output
        
FROM mcr.microsoft.com/dotnet/sdk:7.0 AS runtime
ENTRYPOINT ["dotnet", "Asp.netCoreMvcCrud.dll"]
COPY --from=Dev /crud/output .

'''

So this copies, builds on stage one and

Copies the published binaries from stage one in final to create a skimmed image.

We should be able to manually build the image in a dev environment and copy the published binaries in a basic image and achieve the same skimmed size right?

like this

'''

FROM mcr.microsoft.com/dotnet/sdk:7.0
WORKDIR /crud
COPY publishedfolder ./
ENTRYPOINT ["dotnet", "Asp.netCoreMvcCrud.dll"]

'''

What else Multistage build gives as a advantage beyond Basic Image build and Builder Pattern?


Solution

  • What I would see as the main benefit of building within an image is consistency - you could build the application 'outside' the image, but building inside an image gives you a consistent environment every time. For example, if each dev on a team has a different machine they may have different versions of all the tooling required (JDKs, node, maven, .Net, etc, etc) and so the artifact they build could be subtly different each time meaning the artifact copied into the final image will differ each time. The same applies to building in a CI environment - you may not have the same control over the tooling on the build machine that you have on the build-stage image. When selecting a build image you can specify the exact image you want or build your own with the exact tooling required in it.