Advertisement
Intermediate .NET, Docker & Containerization

How does a multi-stage Dockerfile reduce the final image size for a .NET application, and what does each stage typically do?

Short answer

A multi-stage Dockerfile uses a build stage (based on the full SDK image) to restore, compile, and publish the application, then a separate, final stage (based on a minimal runtime image) copies only the published output artifacts from the build stage, discarding the SDK…

Save .NET mock interview
Advertisement
AModel answer
A multi-stage Dockerfile uses a build stage (based on the full SDK image) to restore, compile, and publish the application, then a separate, final stage (based on a minimal runtime image) copies only the published output artifacts from the build stage, discarding the SDK, intermediate build files, and source code entirely from the final image -- resulting in a dramatically smaller, more secure production image containing only what's needed to run the application.
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY *.csproj .
RUN dotnet restore
COPY . .
RUN dotnet publish -c Release -o /app/publish

FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS final
WORKDIR /app
COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "MyApp.dll"]
Real-world example
A team reduces their production image from 1.1GB (accidentally including the full SDK) to 210MB by properly separating build and final stages, directly improving deployment speed and reducing the attack surface.
Likely follow-ups
  • Why copy the .csproj file separately before the rest of the source code?
  • How many stages can a Dockerfile have, and when would you need more than two?
Related topics