.NET Core Docker Build

Overview

This tutorial walks you through creating a Docker image for a .NET Core application, optimizing it for production, and publishing it to a container registry.

Prerequisites

Step 1 – Create a Sample App

dotnet new webapi -o MyWebApi
cd MyWebApi
dotnet run

Run the API locally to verify it works before containerizing.

Step 2 – Add a Dockerfile

# syntax=docker/dockerfile:1.4
FROM mcr.microsoft.com/dotnet/aspnet:8.0-jammy-amd64 AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:8.0-jammy-amd64 AS build
WORKDIR /src
COPY ["MyWebApi.csproj", "./"]
RUN dotnet restore "MyWebApi.csproj"
COPY . .
RUN dotnet publish "MyWebApi.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "MyWebApi.dll"]

This multi‑stage Dockerfile builds the project in a SDK image, then copies the published output into a lightweight runtime image.

Step 3 – Build the Image

docker build -t mywebapi:latest .

Run the command from the project root directory (where the Dockerfile lives).

Step 4 – Run the Container

docker run -d -p 5000:80 --name mywebapi mywebapi:latest

Access the API at http://localhost:5000/weatherforecast.

Step 5 – Optimize the Image (Optional)

Step 6 – Push to a Registry

docker tag mywebapi:latest ghcr.io/youruser/mywebapi:latest
docker push ghcr.io/youruser/mywebapi:latest

Replace ghcr.io/youruser with your container registry address.