dotnet publish \
-c Release \
-r linux-x64 \
--self-contained true \
/p:PublishSingleFile=true \
/p:PublishTrimmed=false
Here is the step-by-step guide to building a production-ready, secure, and optimized amd64 Ubuntu 22.04 Docker image for a C# ASP.NET Core application.
dockerfile
# Stage 1: Build and publish the C# application
# Use the official .NET SDK image for building
FROM mcr.microsoft.com AS build
WORKDIR /app
# Copy and restore dependencies
COPY *.sln ./
COPY MyCSharpProject/*.csproj ./MyCSharpProject/
RUN dotnet restore MyCSharpProject/
# Copy the rest of the application code
COPY MyCSharpProject/. ./MyCSharpProject/
WORKDIR /app/MyCSharpProject
RUN dotnet publish -c Release -o /app/publish
# Stage 2: Run the application
# Use the smaller, optimized runtime image (Ubuntu 22.04 "jammy")
FROM mcr.microsoft.com AS final
WORKDIR /app
COPY --from=build /app/publish .
# Default port for ASP.NET Core apps is 8080 starting with .NET 8
ENTRYPOINT ["dotnet", "MyCSharpProject.dll"]
