Italian (IT)

Build a Simple .NET Core App on Docker

This is a short step-by-step tutorial to distribute a .NET Core application in a docker image.
I’ll cover how you can use Docker to run your application in an isolated, minimal environment with fewer moving parts.

To build and distribute a .NET Core application in Docker, first we need an application to Dockerize and some prerequisites.

In this tutorial, we'll perform the steps from a Terminal, like Windows command prompt.

First, create a working folder for our exercise

mkdir NetCoreDocker

Check .NET Core version installed on your computer

dotnet --info

Check Docker version installed on your computer

docker version

Place a file named global.json in exercise directory with the following content

    "sdk": { 
        "version": "3.0.100" 

This will force the compiler to use 3.0 version of the SDK

Then create .NET Core console application

dotnet new console -o app -n myapp

The folder structure will be similar to the following example

│   global.json 
    │   myapp.csproj 
    │   Program.cs 

.NET Core creates a console application that is executed, then terminated.
We modify the application that runs continuously instead.

Modify Program.cs as below

using System; 
namespace myapp 
    class Program 
        static void Main(string[] args) 
            var counter = 0; 
            var max = args.Length != 0 ? Convert.ToInt32(args[0]) : -1; 
            while(max == -1 || counter < max) 
                Console.WriteLine($"Counter: {counter}"); 

Move in app sub-folder and test application

dotnet run

Finally, publish the application

dotnet publish -c Release

Application will be published in this folder


Place a file named Dockerfile in the working folder with the following content

COPY app\bin\Release\netcoreapp3.0\publish app/ 
ENTRYPOINT ["dotnet", "app/myapp.dll"]

Now we can build Docker image of our application

docker build -t myimage -f Dockerfile .

Finally, verify the right build of the image

docker images

Final notice

If you want to try starting from the source code of your application (contained in the /src folder, not in the /app folder like now) and compile directly on a Docker image, change the Dockerfile contents with this multistage builds

FROM AS build
COPY ["myapp.csproj", "./"]
RUN dotnet restore "./myapp.csproj"
COPY . .
RUN dotnet build "myapp.csproj" -c Release -o /app
FROM build AS publish
RUN dotnet publish "myapp.csproj" -c Release -o /app
FROM AS base
FROM base AS final
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "myapp.dll"]

This website uses cookies to ensure you get the best experience on our website.