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.
![Microsoft Site]()
Step 2. Execute the below cli command and create a .netcore api project.
dotnet new webapi -o MySampleMicroservice --no-https
![Command]()
Open solution.
In .NET 8.0, we do not have a startup.cs, and everything is clubbed into the program .cs.
![Open solution]()
Running dotnet run.
![Dotnet]()
Step 3. Install docker in the machine and check its version.
Install Docker Desktop on Windows | Docker Docs
![Install Docker]()
Step 4. Create a docker file.
fsutil file create new Dockerfile 0.
![Docker File]()
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.
![Run Phase]()
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.
![Docker image]()
Verify docker images.
We can see my microservices.
docker images
![Mymicroservices]()
Step 6. Running images
docker run -it --rm \
-p 3000:8080 \
--name mymicroservicecontainer \
mymicroservice
![Running image]()
Verify
localhost:3000/weatherforecast
![Localhost]()
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.
![Docker Desktop]()
Exploring inside Container
Using the docker terminal, we can list files that the container has.
These are published files.
![Docker terminal]()
The same files we have in the local system.
![Local system]()