How does Docker work with .NET applications?

Posted: (EET/GMT+2)

 

Docker lets you package a .NET app with its exact runtime and dependencies, then run it the same way everywhere. For .NET Core, you can build on Linux or Windows compatible image and ship that small image to any Docker host.

Here is a minimal multi-stage Dockerfile for an ASP.NET Core app:

# build stage
FROM microsoft/dotnet:2.1-sdk AS build
WORKDIR /src
COPY . .
RUN dotnet restore
RUN dotnet publish -c Release -o /out

# runtime stage (smaller)
FROM microsoft/dotnet:2.1-aspnetcore-runtime
WORKDIR /app
COPY --from=build /out .
EXPOSE 80
ENTRYPOINT ["dotnet", "MyApp.dll"]

To build the image and run it as a container:

docker build -t myapp .
docker run -it --rm -p 8080:80 myapp

The above command maps port 80 inside the container to 8080 on your machine. If you need Windows containers (such as IIS, or full .NET Framework), use a Windows base image and the appropriate hosting model. But for most new web APIs the .NET Core applications, a Linux-based image is a good default.

Tip: keep images small by copying only the published output and excluding build artifacts with a .dockerignore file. It works quite the same as a "Git ignore" file.