Dockerize an ASP.NET Core Application

Spread the love

In this tutorial we are going to see how to dockerize an Asp.NET Core Application.

Prerequisites

  1. An ASP.NET Core application. If  you don’t you can create one using Visual Studio 2017 or download a sample application from my github repository.
  2. A Docker Installation in your Linux or Windows Machine. If you don’t come here to get the desired edition

Dockerize your ASP.NET Core Application

Create a Dockerfile in your project folder. If you downloaded the sample there is one there already.

Add the text below to your Dockerfile for either Linux or Windows Containers.

FROM microsoft/dotnet:sdk AS build-env
WORKDIR /app

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

# Copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out

# Build runtime image
FROM microsoft/dotnet:aspnetcore-runtime
WORKDIR /app
COPY --from=build-env /app/out .
ENTRYPOINT ["dotnet", "<yourapplication>.dll"]

Replace <yourapplication> with your project dll.

Build and run the Docker image

Add a .dockerignore file to your project folder and copy the following into it. If you downloaded the sample there is one there already.

bin\
obj\

Open a terminal/ PowerShell and navigate to your project folder. Use the following commands to build and run your Docker image:

docker build -t <yourapplication> 
docker run -d -p 8080:80 --name myapp <yourapplication>

Replace <yourapplication> with your project name again and run them.

Go to localhost:8080 to access your app in a web browser.

Leave a Reply

Your email address will not be published. Required fields are marked *