How to Run a .NET App in Docker

0
256

Docker is a containerization service, used for running applications in isolated environments packaged with all the dependencies and code it needs to function. It can run all kinds of applications, including .NET-based programs using Microsoft-provided runtime images.

Dockerizing .NET

Microsoft provides prebuilt base images for running .NET applications. You won’t need to handle installing the .NET runtime or SDK in your Docker container, as you can simply extend from Microsoft’s base image for the version of .NET that your application uses.

Unless you plan on deploying Windows containers on a Windows server, you will need to be using either .NET Core or .NET 5. The older .NET Framework runtime is not cross-platform and will not run on Linux-ased containers.

If you don’t have Docker installed on your development machine, you’ll need to install Docker Desktop to have access to the CLI. If you’re using WSL on Windows, you’ll want to enable the WSL 2-based engine, which provides better performance.

To test things out, we’ll create a new ASP.NET API application. The same general procedure will apply for any kind of application, as all Docker is doing is running a build whenever you build the container, and starting your application with an entrypoint command.

Create a new file called Dockerfile at the root of your project, where your solution is located. 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 Dockerfile pulls the .NET Core SDK image to perform the build. It copies the .csproj over and restores, then copies everything else and runs a build. Then, it builds a new image from the .NET Runtime image and copies the build artifacts over.

Finally, the entrypoint is defined here as dotnet DockerTest.dll. This will start the ASP.NET web server, though you may need to change the parameters for your application, or specify an entirely different entrypoint command.

You can test run your container with docker container run, passing it in the ID of the build container:

docker container run containerid

For an ASP.NET application, you’ll need to 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.