Docker multi-stage builds with .NET Core


In my previous article we've created a container for a .NET Core app and today I'd like to talk about Docker Multi-Stage builds. As you will see further there is no rocket science, consider this article as a sequel :)

What is Docker Multi-Stage builds?

 Docker Multi-Stage builds is a new feature of Docker that was introduced in 17.05 version and allows us to create a single minimalistic docker container that can build from sources and run our app. Basically you could create an image with .NET Core SDK preinstalled and compile and run the app with it. But with such approach the size of your container increases. For example microsoft-dotnet-sdk image is about ~900mb size while microsoft-net-runtime ~250mb. To take the best from both worlds Multi-Stage builds was introduced.

Using Multi-Stage builds

 With multi-stage builds, you use multiple FROM statements in your Dockerfile. Each FROM instruction can use a different base, and each of them begins a new stage of the build. You can selectively copy artifacts from one stage to another, leaving behind everything you don’t want in the final image. So enough words, and get down to business (:

Dockerfile

 For this article I'll use a sample app from my previous article. I'll create new Dockerfile that looks like this: 

#first stage, use SDK image
FROM microsoft/dotnet:1.1.1-sdk AS builder

#create and open working directory
WORKDIR /build

#copy sources
COPY . .

#restore packages and build app
RUN dotnet restore && dotnet publish -c Release -o out

#second stage, use runtime image
FROM microsoft/dotnet:1.1.1-runtime
WORKDIR /app

#this command runs on docker run
CMD export ASPNETCORE_URLS=http://*:$PORT && dotnet SampleApp.dll

#copy artifacts from build
COPY --from=builder /build/out /app/

Deployment

Now we ready to deploy it to Heroku. Actually nothing changed in that process and it's still a set of commands.

docker build -t aspnet-sample-app:v0.1 .

docker tag aspnet-sample-app:v0.1 registry.heroku.com/artd-sample-app/web

docker push registry.heroku.com/artd-sample-app/web

After running that commands our app is successfully deployed to Heroku (:

Conclusion

Docker Multi-Stage builds is very comfortable feature. It helps you build small efficient containers and builds your app the same way in different environments (remember this "works on my machine" problem?). Is there any alternatives? What if you use an older Docker version? Well in that case you can create a bash script (or Powershell) that builds your app on your machine and builds docker image. 

Thank for reading this article! If you have any questions you can always contact me on Twitter

Helpful links:


Comments

Popular Posts