Docker Containerization for Production

Docker Containerization for Production in .NET: Multi-stage Docker builds separate the heavy build SDK from the lightweight runtime image, creating secure…

Multi-stage Docker builds separate the heavy build SDK from the lightweight runtime image, creating secure images under 100MB.

# -------------------------------------------------------------
# Stage 1: Build & Publish
# -------------------------------------------------------------
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src

# Cache dependency restoration layer
COPY ["src/OrdersApi/OrdersApi.csproj", "src/OrdersApi/"]
RUN dotnet restore "src/OrdersApi/OrdersApi.csproj"

# Copy source code and publish release binary
COPY . .
WORKDIR "/src/src/OrdersApi"
RUN dotnet publish -c Release -o /app/publish /p:UseAppHost=false

# -------------------------------------------------------------
# Stage 2: Minimal Runtime Environment
# -------------------------------------------------------------
FROM mcr.microsoft.com/dotnet/aspnet:8.0-alpine AS runtime
WORKDIR /app
EXPOSE 8080

# Run as non-root user for cloud security
USER $APP_UID

COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "OrdersApi.dll"]