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.

App

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

Dockerfile

See https://docs.docker.com/engine/reference/builder/ 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.

# https://hub.docker.com/_/microsoft-dotnet-core
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 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
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1
WORKDIR /app
COPY --from=build-env /app .
EXPOSE 80
ENTRYPOINT ["dotnet", "WebApi.dll"]

.dockerignore

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.

bin
obj

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

© 2024 ALL RIGHTS RESERVED