DEV Community

Cover image for Web API in NET 6 + Docker
Bervianto Leo Pratama
Bervianto Leo Pratama

Posted on • Edited on

Web API in NET 6 + Docker

Hello!

How are you? I hope all of you are stay safe and having a great day!

If you want to follow this step-by-step. Please install some tools that will be required here.

  1. .NET 6: https://dotnet.microsoft.com/download/dotnet/6.0
  2. Docker: https://docs.docker.com/get-docker/

Project Preparation

  • Create the Web API from template.


dotnet new webapi -o DockerNetExample


Enter fullscreen mode Exit fullscreen mode
  • Create the solution to link the project and link the project.


dotnet new sln


Enter fullscreen mode Exit fullscreen mode


dotnet sln add DockerNetExample


Enter fullscreen mode Exit fullscreen mode
  • Your project is ready now. :)

Prepare for Dockerfile

  • Create your Dockerfile at the root, similar place with the .sln file.


FROM mcr.microsoft.com/dotnet/sdk:6.0-alpine as build
WORKDIR /app
COPY . .
RUN dotnet restore
RUN dotnet publish -o /app/published-app

FROM mcr.microsoft.com/dotnet/aspnet:6.0-alpine as runtime
WORKDIR /app
COPY --from=build /app/published-app /app
ENTRYPOINT [ "dotnet", "/app/DockerNetExample.dll" ]


Enter fullscreen mode Exit fullscreen mode

Build the Image and Run the Container

  • Build your image use docker build . -t dotnetexample

  • Run a container with previous image. docker run --name dotnetexample -p 8081:80 -d dotnetexample

  • Check your container. docker ps. You would see like this.

Docker PS

  • Check your API use browser or another things.

Note: If you use Firefox, the return will be like this, the value maybe will be different, since it returns randomly.
Browser Firefox

  • Congrats. You are done. :)

Repository






Thank you

Thank you for visiting this tutorial. If you have any questions or suggestions, please comment in here.

Thank you

Top comments (4)

Collapse
 
evangelinabonzano profile image
Evangelina Bonzano • Edited

I have a suggestion so that the same does not happen to another:
This command: dotnet sln add DocketNetExample
Has an incorrect project name. It should be dotnet sln add DockerNetExample
It took me more than 5 minutes to realize haha

Thank you for the tutorial!

Collapse
 
berviantoleo profile image
Bervianto Leo Pratama • Edited

OMG. You're right. I also just realize that is typo.

Thank you. I've updated the post.

Collapse
 
cesar31mr profile image
CesarMtz

Thank's a lot for this tutorial, I'm learning about webapi and docker and this is perfect to understand a lot.
PD sorry for my English, I'm learning it to n.n'

Collapse
 
berviantoleo profile image
Bervianto Leo Pratama

Thank you. Let's learn together.