Deploying a dotnet api with docker container

May 24, 2020

With Services like Netlify and Zeit, deploying a front end app has become easier than ever. However, deploying a microservice has been a huge hassle for me because of all the dependencies I have to manually install.

Luckily, with the help of docker, a lot of the hassle can be avoided, allowing you to run your backend app basically like a portable binary! So today I will show you how to build a docker image, push it to docker hub, and run it anywhere any time. Let's jump into it.

Note that although the example I will be a dotnet app, this works with any kind of app you wish to deploy. You'd just need to find the right docker images to use and change the dockerfile accordingly.


Skip this part if you already have an app ready to run.

If you don't have an app and just want to play with docker, run dotnet new webapi -o webapi to create a template app.

Install dependencies with dotnet restore

Test run the application: dotnet run

If the app is running, you should see some json response if you visit https://localhost:5001/WeatherForecast


See for info about docker.

First, create a file named Dockerfile in the root directory of your project and copy paste the following content into it.

FROM AS build-env
WORKDIR /source

# copy csproj and restore as distinct layers
COPY *.csproj .
RUN dotnet restore

# copy and publish app and libraries
COPY . .
RUN dotnet publish -c release -o /app --no-restore

# final stage/image
COPY --from=build-env /app .
ENTRYPOINT ["dotnet", "WebApi.dll"]


Since we want to keep the docker container lightweight, we want to ignore the bin and obj folders. .dockerignore works similarly to .gitignore.

Create .dockerignore and put the following content.


Build and Run

Now we can build our docker image by running docker build -t <your docker hub user id>/<your project name>:<tag name> . For example: docker build -t jamesku/webapi . (I did not use a tag name here)

And then push your image to docker hub(You need to login first with docker login) docker push <your docker hub user id>/<your project name>:<tag name>

You image has been built! Now you can run the container anywhere, be it a VPS( Get $100 of free credit on digital ocean HERE) or managed container services such as AWS or Azure as long as you have docker installed.

To run the container docker run -p 80:80 jamesku/webapi(replace the image name with yours)

Subscribe to my email list