Docker helps you to run software projects without the need to set up complex development environments.
In this tutorial, How to create a Docker Image of a .NET 5 Web API. You can use Docker image to run the backend from any PC that has Docker installed and front-end web project interact with the API.
Create a .NET Web API
I will create a project named “exdockerapi” use the dotnet CLI with the following command:
dotnet new webapi -o aspdockerapi
If you don’t have .NET 5 installed on your PC. Please, you can download it here.
Now, you can go into the project exdockerapi is created, and run the web API.
cd exdockerapi dotnet run
By default, the application is on port 5001.
Create Docker Image
I will create a new file Dockerfile with the following command:
Now, we will copy and paste the code below into Dockerfile.
FROM mcr.microsoft.com/dotnet/aspnet:5.0-focal AS base WORKDIR /app EXPOSE 80 FROM mcr.microsoft.com/dotnet/sdk:5.0-focal AS build WORKDIR /src COPY ["exdockerapi.csproj", "./"] RUN dotnet restore "./exdockerapi.csproj" COPY . . WORKDIR "/src/." RUN dotnet build "exdockerapi.csproj" -c Release -o /app/build FROM build AS publish RUN dotnet publish "exdockerapi.csproj" -c Release -o /app/publish FROM base AS final WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "exdockerapi.dll"]
How to building the Docker Image
The simply to build the Docker image based on the Dockerfile with the following command:
docker build -t dockerwebapiex -f Dockerfile .
To check Docker image is dockerwebapiex with the following command:
docker images | grep dockerwebapiex
Run the Docker Image
Use the following command.
docker run -ti --rm -p 8080:80 dockerwebapiex
- The -ti option specifies that the image should be run in an interactive terminal mode
- –rm specifies that the container should be removed immediately after it exits.
You have installed Create Docker Image of a .NET Web API. I hope will this your helpful. Thank you for reading the DevopsRoles page!