.NET Core Docker Tutorial

← Back to .NET Core Docs
Table of Contents

Introduction

This tutorial guides you through containerizing a .NET 8 application using Docker. You'll learn how to write a Dockerfile, build an image, run it locally, and push it to a container registry.

Prerequisites

Verify the installations:

$ dotnet --version
8.0.100

$ docker --version
Docker version 24.0.6, build abcdefg

Creating a Dockerfile

In the root of your project, add a Dockerfile:

# Dockerfile
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
WORKDIR /app
EXPOSE 80

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

FROM build AS publish
RUN dotnet publish "MyApp.csproj" -c Release -o /app/publish

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

Build & Run the Container

Execute the following commands from the project root:

# Build the image
docker build -t myapp:latest .

# Run the container
docker run -d -p 8080:80 --name myappcontainer myapp:latest

# Verify it's running
docker ps

Open http://localhost:8080 in your browser to see the app.

Publishing to a Registry

Tag and push the image to Docker Hub (replace yourusername with your Docker Hub account):

# Tag the image
docker tag myapp:latest yourusername/myapp:latest

# Push to Docker Hub
docker push yourusername/myapp:latest

Cleaning Up

Stop and remove the running container and the local image:

# Stop and remove container
docker stop myappcontainer
docker rm myappcontainer

# Remove image
docker rmi myapp:latest