DEV Community

Avinash
Avinash

Posted on

Containerize a .NET Core Web API Project

Hey, As the world is moving towards lighter things so the software's.

In this article you are going to learn, how we can create an image of an basic .net core web API application and run that in a container.

Prerequisites

  1. Docker installed
  2. .net core SDK

Verify that environment is ready by executing below commands in cmd.

dotnet --version 
  3.1.101

docker --version
  Docker version 19.03.8, build afacb8b

Before creating the image of an application. Let us create .net core web API application using below command.

dotnet new webapi -n TestWebAPI

Once the application is created, navigate to folder under which application is created

cd TestWebAPI

Before adding the .NET Core app to the Docker image, first it must
be published.

dotnet publish -c Release

We are ready with Application which needs to be created as a image.

Create a file named Dockerfile in directory containing the .csproj
and open it in a text editor copy below code into that file.
Dockerfile will be used by docker build command to create image


FROM mcr.microsoft.com/dotnet/core/aspnet:3.1

 COPY bin/Release/netcoreapp3.1/publish/ TestWebAPI/
 WORKDIR /TestWebAPI
 ENTRYPOINT ["dotnet", "TestWebAPI.dll"]

Create image of an application.Below command will use the commands
in Dockerfile to create image of an application.

docker build -t testimage -f Dockerfile .

To get the list of images.

docker images

Container is a instance of an image. Create container to run
created image in it.

docker create --name testcontainer testimage

To get the list of container.

docker ps -a

The status of the container will be created and not Up
until we start the container using below command.

Start container

docker start testcontainer

After starting the container we have to run the container in one of the port.

docker run -p 8080:80 testimage

Open in the browser

http://localhost:8080/weatherforecast

Top comments (0)