Search Sreeni's Insights

Filter by content type
cloud August 2, 2016 6 min read

How to build a Docker image for an ASP.NET Core application?

Building a Docker image for ASP.NET Core explained through Dockerfiles, SDK and runtime images, build commands, containers, configuration and deployment practices.

Share:

How to build a Docker image for an ASP.NET Core application?

For many years, running a .NET web application meant Windows Server and IIS. With .NET Core 1.0 and ASP.NET Core 1.0 (June 2016), it changed. Our ASP.NET Core applications can now run on Linux, and that opens the door to Docker containers, which were mostly a Node.js, Java and Python world till now. For us, the main reason to look at containers was the same “it works on my machine” problem we discussed last year in Getting started with Docker - Part 1, the environment of developer machine, QA and production were never exactly the same.

In the previous article, we discussed how to migrate an ASP.NET MVC 5 app to ASP.NET Core 1.0. In this article, we are going to see how to build a Docker image for an ASP.NET Core application, step by step, and run it as a container.

We can build the image in two ways:

Publish on host, copy into imageBuild inside the image (SDK image)
ApproachRun dotnet publish on the developer machine or build server, then copy the output into a runtime imageCopy the source code into the SDK image and run dotnet restore and dotnet publish inside Docker
Pros+ Small image (runtime only)<br>+ Fast docker build<br>+ Fits our existing VSTS build+ Build environment is also in a container<br>+ No .NET SDK needed on the build agent
Cons− Needs .NET Core SDK on the build machine− Big image with SDK and source code<br>− Slower builds

In our case, we chose the first approach, because the image is smaller and our VSTS build agents already have the .NET Core SDK.

TL;DR Summary

  • A Dockerfile describes how to build an image, step by step.
  • Use microsoft/dotnet runtime image as the base for running, and SDK image only for building.
  • Publish the application with dotnet publish, copy only the publish output into the image.
  • Kestrel must listen on all interfaces inside the container, use ASPNETCORE_URLS=http://+:5000.
  • Use a .dockerignore file to keep the build context small.
  • Tag the images with the version, don’t rely on latest.
  • Configuration and secrets are passed as environment variables at runtime, not baked into the image.

Challenges

Image size

When the image contains the SDK, the source code and NuGet caches, it can be more than 500 MB. Big images are slow to push, slow to pull and have more components with security vulnerabilities.

Localhost inside the container

By default, Kestrel listens on http://localhost:5000. Inside a container, localhost means the container itself, so the application is running but not reachable from outside. It is the most common issue when someone runs ASP.NET Core in Docker for the first time.

Configuration per environment

An image must be the same for all environments, otherwise we lose the main benefit of containers. The connection strings and settings must come from outside.

What is a Dockerfile?

A Dockerfile is a text file which contains the ordered instructions that Docker uses to build an image, each instruction creating a layer on top of the base image.

In simple terms, it is a recipe. The base image is the ingredients we start with, and each instruction is one step in the recipe. Anyone with the same recipe gets the same dish.

The following diagram depicts the flow from source code to a running container.

Docker image build flow for ASP.NET Core
Docker image build flow for ASP.NET Core

Steps to Implement:

Follow the following instructions to build and run the image for an ASP.NET Core 1.0 application.

  • Install Docker for Windows (released in July 2016, requires Windows 10 Pro with Hyper-V) or Docker Toolbox for older Windows versions.

  • Just to pulse check, make sure the Docker client and server are working.

    docker version
  • Make sure the application reads the URLs from the environment. The default Program.cs from the template works, because WebHostBuilder reads the ASPNETCORE_ environment variables. Don’t hard-code UseUrls("http://localhost:5000").

  • Publish the application to a folder.

    dotnet restore
    dotnet publish -c Release -o ./publish
  • Create a Dockerfile in the project folder.

    FROM microsoft/dotnet:1.0.0-core
    
    WORKDIR /app
    COPY ./publish .
    
    ENV ASPNETCORE_URLS http://+:5000
    EXPOSE 5000
    
    ENTRYPOINT ["dotnet", "FundReporting.Api.dll"]

    Note: microsoft/dotnet:1.0.0-core contains only the .NET Core runtime. microsoft/dotnet:1.0.0-preview2-sdk contains the SDK and is needed only when we build inside Docker. Check the Docker Hub page of microsoft/dotnet for the latest tags.

  • Create a .dockerignore file, so only the publish output is sent to the Docker daemon.

    *
    !publish
  • Build the image and tag it with the version. Replace the input place holders with actual values.

    docker build -t <registry>/fund-reporting-api:<version> .
  • List the images and check the size.

    docker images
  • Run the container, map the port and pass the configuration as environment variables.

    docker run -d --name fund-api -p 8080:5000 \
      -e "ASPNETCORE_ENVIRONMENT=Production" \
      -e "ConnectionStrings__FundDb=<connection string>" \
      <registry>/fund-reporting-api:<version>

    Info: In ASP.NET Core configuration, a double underscore (__) in an environment variable name is translated to :, so ConnectionStrings__FundDb overrides ConnectionStrings:FundDb from appsettings.json.

  • Just to pulse check, call the API and look at the logs.

    curl http://localhost:8080/api/funds
    docker logs fund-api

    With Docker Toolbox, use the IP from docker-machine ip default instead of localhost.

  • Push the image to a registry, Docker Hub or a private registry, so the other environments can pull the same image.

    docker login <registry>
    docker push <registry>/fund-reporting-api:<version>

Building inside the image

If you choose the second approach, the Dockerfile uses the SDK image.

FROM microsoft/dotnet:1.0.0-preview2-sdk

WORKDIR /src
COPY project.json .
RUN dotnet restore

COPY . .
RUN dotnet publish -c Release -o /app

WORKDIR /app
ENV ASPNETCORE_URLS http://+:5000
EXPOSE 5000
ENTRYPOINT ["dotnet", "FundReporting.Api.dll"]

Copying project.json first and running dotnet restore before copying the rest of the source code is a small trick. Docker caches the restore layer, so when only the code changes, the NuGet packages are not downloaded again.

Why it is important?

In order to run the same artifact in all environments, to remove the environment drift between developer machines, QA and production, and to make the deployment repeatable, the image must be built once and promoted through the environments. It is the same principle we follow with our build artifacts in VSTS Release Management, build once, deploy many times.

Must Do and Don’ts

  • Must Do: Use the runtime image for running the application, not the SDK image.
  • Must Do: Tag every image with a version (ex: the build number).
  • Must Do: Pass configuration and secrets as environment variables or from a secret store at runtime.
  • Should: Add a health check endpoint (ex: /api/health) which the orchestrator or load balancer can call.
  • Don’t: copy appsettings.Production.json with real secrets into the image.
  • Don’t: run apt-get install of unnecessary tools in the image, every package increases the size and the attack surface.
  • Be mindful: Linux file system is case sensitive. Views/Home/index.cshtml and Index.cshtml are different files in the container, but not on Windows.

Wrap up

In this article, we have looked at the two ways to build a Docker image, the challenges, what is a Dockerfile, the step by step instructions to build and run an ASP.NET Core application in a container, and the practices we follow. Thanks for reading this article and I hope this article provided you some insights into containerizing your ASP.NET Core applications. In the next article, I will walk you through how to store application secrets in Azure Key Vault.

Related Posts