Docker with .NET Core
In today’s world, the concept of microservice is growing very fast, but it is very important to understand in which scenario we need this.
In this tutorial, I am following the Microsoft site, which has all the important steps.
Step 1. Ensure you have .net8.0 on your machine
Install from the Microsoft site.

Step 2. Execute the below cli command and create a .netcore api project.
dotnet new webapi -o MySampleMicroservice --no-https

Open solution.
In .NET 8.0, we do not have a startup.cs, and everything is clubbed into the program .cs.

Running dotnet run.

Step 3. Install docker in the machine and check its version.
Install Docker Desktop on Windows | Docker Docs

Step 4. Create a docker file.
fsutil file create new Dockerfile 0.

Paste this content into the docker file.
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY MySampleMicroservice.csproj .
RUN dotnet restore
COPY . .
RUN dotnet publish -c release -o /app
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "MyMicroservice.dll"]
Exploring docker file
Let us understand what we have done.
We created a .net core API, created a docker image, and ran it.
So, the docker image contains base files for the .net core, which is needed to run the .net core project.
To run the .NET core application, we need 2 things.
- Server, which contains all base files
- Build files which required to run using base .net core files.
Docker files have a build phase and run phase as below.

Step 5. Build docker image
We need to create an image from the docker file.
docker build -t my_microservice
here is important for the current directory.

Verify docker images.
We can see my microservices.
docker images

Step 6. Running images
docker run -it --rm \
-p 3000:8080 \
--name mymicroservicecontainer \
mymicroservice

Verify
localhost:3000/weatherforecast

Here we successfully created a docker image and ran it.
Running instances of images known as containers.
I have a docker desktop also installed on my machine and the corresponding running container we can see on the docker desktop also.
Container name: mymicroservicecontainer.

Exploring inside Container
Using the docker terminal, we can list files that the container has.
These are published files.

The same files we have in the local system.


jeffPosted Sep 11, 2024, 2:29 PM
"docker build -t my_microservice ." forgot the ".", "docker run -it --rm -p 3000:8080 --name mymicroservicecontainer my_microservice" if you build with "my_" need to be sure to use that in the run command