Docker is a containerization service used to run applications in isolated environments packed with all the dependencies and code it needs to work. It can run all types of applications, including .NET-based applications with Microsoft-provided runtime images.
Microsoft provides advanced base images for running .NET applications. You do not need to handle the installation of the .NET runtime or SDK in your Docker container, as you can simply expand from Microsoft̵7;s base image for that version of. NET that your application uses.
Unless you plan to deploy Windows containers on a Windows server, you must use either .NET Core or .NET 5. The older .NET Framework runtime is not a platform and will not run on Linux containers.
If you do not have Docker installed on your development machine, you must install Docker Desktop to access the CLI. If you use WSL on Windows, you want to enable WSL 2-based engine, which provides better performance.
To test things out, we are creating a new ASP.NET API application. The same general procedure will apply to all types of applications, because all Docker does is run a build when you build the container and launch your application with a command for the starting point.
Create a new file named
Dockerfile at the root of your project, where your solution lies. Paste in the following configuration:
FROM mcr.microsoft.com/dotnet/core/sdk AS build-env WORKDIR /app # Copy csproj and restore COPY *.csproj ./ RUN dotnet restore # Copy everything else and build COPY . ./ RUN dotnet publish -o out # Build runtime image FROM mcr.microsoft.com/dotnet/core/runtime WORKDIR /app COPY --from=build-env /app/out . ENTRYPOINT ["dotnet", "DockerTest.dll"]
This Docker file pulls the .NET Core SDK image to execute the building. It copies
.csproj over and restore, then copy everything else and run a build. Then it builds a new image from the .NET Runtime image and copies the build artifacts over.
Finally, the entry point is defined here as
dotnet DockerTest.dll. This launches the ASP.NET Web Server, but you may need to change the parameters of your application or enter a completely different input command.
You can test drive your container with
docker container run, send it in ID for the construction container:
docker container run containerid
For an ASP.NET application, you must open ports by mapping a port on the host to a port on the container:
docker run -p 80:80 containerid
You can read our guide to working with Docker and Dockerfiles to learn more.