What is the purpose of a multi-stage Dockerfile for .NET applications, and how does it reduce final image size?
Short answer
A multi-stage Dockerfile uses one stage with the full SDK image to restore, build, and publish the application, then copies only the published output into a second, much smaller stage based on a lightweight runtime-only base image -- discarding the SDK, build tools, intermediate…
Advertisement
AModel answer
A multi-stage Dockerfile uses one stage with the full SDK image to restore, build, and publish the application, then copies only the published output into a second, much smaller stage based on a lightweight runtime-only base image -- discarding the SDK, build tools, intermediate object files, and source code from the final image, significantly reducing image size and attack surface compared to shipping the entire SDK in production.
# Build stage
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish -c Release -o /app/publish
# Final, minimal runtime stage
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "MyApp.dll"]Real-world example
A team reduces their production container image from over 1.2GB (SDK-based) to under 220MB using a multi-stage Dockerfile, speeding up deployment pull times and reducing the surface area for security vulnerabilities.
Likely follow-ups
- What's the difference between the aspnet and runtime-deps base images?
- How does layer caching optimize rebuild times in a multi-stage Dockerfile?
Related topics