قالب وردپرس درنا توس
Home / Tips and Tricks / How to run a .NET app in Docker – CloudSavvy IT

How to run a .NET app in Docker – CloudSavvy IT



C # logo

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.

Dockerizing .NET

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.

Microsoft .NET Core

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.

If you use WSL in Windows, enable the WSL 2-based engine

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 ASP.NET API application

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

Drive your container with docker container driving and send it in ID for the construction container

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.


Source link