Dockerize Asp.Net Core Web App With Multiple Layers/Projects (Part1).
Assumptions
- Docker is working in your machine
- Your project has a solution (.sln) file
Note: If your project does not have a solution file, read the part 2 of this post (Part 2 is coming soon).
I’ll try to be as direct as possible, lets begin :) .
I created a simple project with multiple layers, github link here .
The Experiment project has reference to the Experiment.Procedure and Experiment.Sample only.
The Experiment.UnitTest has reference to the Experiment.Procedure and Experiment. Check the projet in github, here.
Note: I created the project with vscode-solution-explorer extension, i didn't use the dotnet new command because i need the .sln file.
I created a Dockerfile in the “Experiment” project.
FROM mcr.microsoft.com/dotnet/core/sdk:3.0 AS build
WORKDIR /app
#
# copy csproj and restore as distinct layers
COPY *.sln .
COPY Experiment/*.csproj ./Experiment/
COPY Experiment.Procedure/*.csproj ./Experiment.Procedure/
COPY Experiment.Sample/*.csproj ./Experiment.Sample/
COPY Experiment.UnitTest/*.csproj ./Experiment.UnitTest/
#
RUN dotnet restore
#
# copy everything else and build app
COPY Experiment/. ./Experiment/
COPY Experiment.Procedure/. ./Experiment.Procedure/
COPY Experiment.Sample/. ./Experiment.Sample/
#
WORKDIR /app/Experiment
RUN dotnet publish -c Release -o out
#
FROM mcr.microsoft.com/dotnet/core/aspnet:3.0 AS runtime
WORKDIR /app
#
COPY --from=build /app/Experiment/out ./
ENTRYPOINT ["dotnet", "Experiment.dll"]
Observe the following
Line 1 -11 builds the project
Line 14 -16 copies the build files . I did not include the Experiment.UnitTest because the Experiment project didn't reference it.
Line 16 -24 Copies the build files where it can run using the runtime.
Line 25 runs the build files with the runtime once the container is started.
To create an image, run the next command in the root of project.
docker build -f Experiment/Dockerfile -t the_experiment .
A docker image is created with a repository name “the_experiment”. To see a list of images, run:
docker image ls
Spin up a container form the image, and bind the pc port 5000 with the container port 80, run:
docker run -d -p 5000:80 — name the_experiment_container the_experiment
You can test the app by making a get request to this endpoint using postman or browser.
http://localhost:5000/Experiment/CarryOutExperiment1
or
I hope this helps ;) .