Learning .Net Core with Docker

In this article we will learn basic of docker and will run .net core web api inside docker container.

Step 1

Ensure you must have .net8.0 in your machine

Install from Microsoft site

Step 2

Execute below cli command and create .net core api project


csharp
dotnet new webapi -o MySampleMicroservice - no-https


Open solution.

In .net 8.0 we do not have Startup.cs and everything clubbed into program .cs


Running dotnet run

Step 3

Install docker in machine and check its version

Install Docker Desktop on Windows | Docker Docs



Step 4

Create docker file


csharp
fsutil file createnew Dockerfile 0
csharp


csharp
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's understand what we have done.

docker image contains base files for .net core which need to run .net core project.

To run .net core application we need 2 things

a. Server which contains all base files

b. Build files which required to run using base .net core files.


Step 5

Build docker image

We need to create image from docker file



csharp
docker build -t mymicroservice .
csharp
here . is important for current directory
csharp


Verify docker images.

We can see mymicroservices,

docker images



Step 6

Running images


csharp
docker run -it - rm -p 3000:8080 - name mymicroservicecontainer mymicroservice



Verify

localhost:3000/weatherforecast


Here we successfully created docker image and run.

Running instances of image known as container.

I have docker desktop also installed in my machine and corresponding running container we can see at docker desktop also

Container name: mymicroservicecontainer.


Exploring inside Container.

Using docker terminal we can list files that container have.

These are published files.


same files in local build


Conclusion

We have learnt basic of Docker and how to run .net core api using docker  container

line

Copyrights © 2024 letsupdateskills All rights reserved