Creating (ASP) .NET Core Docker containers that can be built anywhere

When you create a new ASP .NET Core application in Visual Studio and add Docker support (Project -> Docker Support), a nice Dockerfile gets created for you. It will look like this:

FROM microsoft/aspnetcore:2.0
ARG source
WORKDIR /app
EXPOSE 80
COPY ${source:-obj/Docker/publish} .
ENTRYPOINT ["dotnet", "WebApplication.dll"]

Then when you run your container from Visual Studio it will turn out that this Dockerfile indeed works.

That is what I experienced. However, I then wanted to set up continuous integration on Visual Studio Team Services (VSTS) and the build failed in the Docker Build phase. For some reason I couldn’t figure out how to get the build output copied into the container on the VSTS build agent. That’s when I found a different way of building an ASP .NET Core app container: building the app inside the container.

The microsoft/aspnetcore-build Docker image contains the complete .NET Core SDK as well as other common requirements for an ASP.NET Core build environment, for example Node.js. This means this image can be used to build your .NET Core app from source. So I built a Dockerfile that uses two Docker images: one to build the app and one to run the app. Here’s what it looks like. I added comments to explain the steps.

# Use the ASP.NET Core build environment image
FROM microsoft/aspnetcore-build:2.0 AS build-env
WORKDIR /app

# Copy all local source and project files to the container
COPY . .

# Restore packages in the container
RUN dotnet restore

# Create a Release build and publish files to a folder named "out"
RUN dotnet publish -c Release -o out

# Use the ASP.NET Core runtime image
FROM microsoft/aspnetcore:2.0
WORKDIR /app

# Copy the published files from the "out" folder in the build environment image to the runtime image
COPY --from=build-env /app/out .

# Configure the app entrypoint
ENTRYPOINT ["dotnet", "WebApplication.dll"]

You most likely also need to remove the line containing just “*” in your .dockerignore file to allow copying all source files

Now this container can be built on any system that has Docker installed, using only your source files. No need to worry about the state of the build environment on that system.

Posted by Pikedev

Geef een antwoord