liveBook · Manning

Multistage build

As explained in .NET in Action, Second Edition

A multistage build constructs an image through multiple Dockerfile build stages so that artifacts from an earlier stage can be copied into a later runtime stage.

A multistage build separates image construction from runtime execution. One stage uses the .NET SDK to restore packages and publish the application; a later stage uses the smaller ASP.NET Core runtime image and copies in the published files. The resulting container starts the application without restoring or compiling on startup. section 13.3.1

Build the Dockerfile around these decisions:

  • Add a new stage with each FROM instruction. section 13.3.1
  • Use the SDK image for restore, compilation, and publishing. section 13.3.1
  • Use the aspnet image for the runtime stage, because it contains only what ASP.NET Core applications need. section 13.3.1
  • Copy published output with COPY --from=0, or assign a name such as build-stage and copy with COPY --from=build-stage. section 13.3.1
  • Set the runtime working directory, expose the application port, and launch the published DLL directly. section 13.3.1
Listing 13.6 Dockerfile with two build stages
FROM mcr.microsoft.com/dotnet/sdk:6.0          #1
COPY . /src
WORKDIR /src
RUN dotnet publish -o /publish                 #2
 
FROM mcr.microsoft.com/dotnet/aspnet:6.0       #3
COPY --from=0 /publish /publish                #4
WORKDIR /publish
EXPOSE 80                                      #5
ENTRYPOINT ["dotnet", "AsciiArtSvc.dll"]       #6

Inspect the complete two-stage Dockerfile for the SDK publish stage, ASP.NET Core runtime stage, artifact copy, port, and entry point. section 13.3.1

Named stages improve readability and make artifact references less dependent on numeric stage positions. A production-oriented Dockerfile can therefore restore the project, publish it, and transfer only the publish directory into the final image. section 13.3.1

How .NET in Action, Second Edition covers it

How deep it goes
Explains stages, base images, artifact copying, ports, entry points, and named-stage syntax through complete Dockerfiles.
Examples
Uses the AsciiArtSvc service with SDK and aspnet images, numbered and named stages, published output, port 80, and a DLL entry point.
What it assumes
Assumes familiarity with Dockerfiles, FROM, COPY, WORKDIR, EXPOSE, ENTRYPOINT, and basic .NET application publishing.
What you can do after
Builds a smaller runtime-focused Docker image from a publish stage and configures it to launch the published ASP.NET Core application.
How it connects
Connects Dockerfile stages with Docker images, NuGet restore, .NET publishing, ASP.NET Core runtime images, and container entry points.

Also explained in

Compare how 2 books explain multistage build →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.