How do you write a multi-stage Dockerfile for a .NET API?

IntermediateConcept.NET builds (dotnet CLI)
Answer

Short answer

Build in the large SDK image, run in the small ASP.NET runtime image. Copy the .csproj files and run dotnet restore before copying the rest of the code so the restore layer is cached. Publish in Release, copy only the publish output, run as the non-root app user, and expose 8080.

Example

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY Shop.sln .
COPY src/Shop.Api/Shop.Api.csproj src/Shop.Api/
COPY src/Shop.Domain/Shop.Domain.csproj src/Shop.Domain/
RUN dotnet restore src/Shop.Api/Shop.Api.csproj
COPY . .
RUN dotnet publish src/Shop.Api/Shop.Api.csproj -c Release -o /app/publish --no-restore

FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /app/publish .
USER app
EXPOSE 8080
ENTRYPOINT ["dotnet", "Shop.Api.dll"]

Size comparison

Image Approx. size
sdk:8.0 ~850 MB
aspnet:8.0 ~220 MB
aspnet:8.0-alpine / chiseled ~110 MB or less

What to say in the interview

"SDK image to restore and publish, aspnet runtime image to run. Copying csproj files first gives a cached restore layer, the final image only has the publish output, runs as the built-in non-root app user and listens on 8080."

All Build Tools (Java, Node.js, Python, .NET) questions Roadmap: .NET apps: dotnet build & publish

More on .NET builds (dotnet CLI)