Skip to content

Docker for .NET, Before It Was Normal

Packing a small Nancy API under Mono into a Docker container was a detour via Linux in the spring of 2015 – and it taught me more about .NET deployment than any IIS manual.

≈ 11 min readSoftwarePlatform

Docker for .NET, Before It Was Normal

A good 400 megabytes. That is what docker images reports for an image whose actual application is a single compiled file of a few kilobytes – a small HTTP API written in C#. The number seems absurd, and it is. But the more interesting measurement is a different one: docker start demo1 takes under a second, and then the service responds. A comparable deployment on a Windows server with IIS regularly cost me half an afternoon in projects – check the framework version, create an app pool, set permissions, copy files, pray.

These two numbers side by side – 400 megabytes of space versus one second to start – describe pretty precisely what you get into when you put .NET code into a Docker container in the spring of 2015. You trade disk space for repeatability. I think that is a good trade, and I want to explain why.

Spring 2015: .NET officially means Windows#

Whoever says “.NET” today practically always means Windows, IIS and the Microsoft stack from top to bottom. Docker, on the other hand, is a Linux topic: Docker 1.6 has just been released, on the Mac the Docker daemon runs in a small VirtualBox VM called boot2docker, and Compose has only just emerged from Fig. The two worlds barely touch.

The picture isn’t entirely accurate anymore, though. In November, Microsoft announced that it would develop .NET Core as open source; since February, the CoreCLR has been on GitHub, and the upcoming ASP.NET 5 is explicitly meant to run on Linux and OS X as well. That is a remarkable turn – but in April 2015, it is an announcement with early betas, not a foundation. If you want to run .NET code in a Linux container today, you end up with Mono, the free runtime that has existed for more than ten years and now covers a surprising amount of the .NET Framework.

That is exactly what I wanted to try. Not because a project demanded it, but because the question wouldn’t let go of me: How much of the usual .NET deployment ritual is actually necessary – and how much of it is just habit tied to IIS? One weekend, one repository, a deliberately small service. If the experiment fails, little is lost; if it holds up, I know something that no blog article by others can replace.

The attempt: a Nancy API in a container#

The result is a repository called dotnet-docker on GitHub: a small HTTP API with the Nancy framework, self-hosted via Nancy.Hosting.Self, with LiteDB as an embedded database. No IIS, no Windows service, no installation – a process that opens a port. The README calls it a “Docker + DotNet Microservice”, and it is as small as that sounds: one module, two serious endpoints, one database file.

The heart of it is the Dockerfile. It describes completely what this application needs to run – in a way that leaves no silent assumption behind:

FROM mono:3.10

# Update SSL certs
RUN mozroots --import --sync

# Copy source files
ADD src ./src
WORKDIR /src

# Install dependencies via NuGet
RUN mono /src/NuGet.exe install Nancy
RUN cp /src/Nancy.1.1/lib/net40/Nancy.dll /src

RUN mono /src/NuGet.exe install Nancy.Hosting.Self
RUN cp /src/Nancy.Hosting.Self.1.1/lib/net40/Nancy.Hosting.Self.dll /src

RUN mono /src/NuGet.exe install LiteDB
RUN cp /src/LiteDB.1.0.0/lib/net40/LiteDB.dll /src

# Compile the web service
RUN mcs nancy.cs modules/webhooks.cs \
    -reference:Nancy.dll \
    -reference:Nancy.Hosting.Self.dll \
    -reference:LiteDB.dll
EXPOSE 8080

# Run the web service
CMD ["mono", "/src/nancy.exe"]

You can tell the era from the Dockerfile, and that is intentional. There is no official Microsoft image, so everything starts on mono:3.10. There is no built-in package management in the build, so NuGet.exe sits in the repository and is called via mono. And because NuGet puts the packages into version folders, the DLLs are then copied by hand to the place where the compiler expects them. Compilation happens with mcs, the Mono C# compiler, directly in the image – no Visual Studio, no MSBuild project file, just source files and references.

That is uncomfortable. But each of these lines replaces an assumption that would otherwise sit invisibly somewhere on a server: which runtime, which package versions, which certificates, which port. While writing it, I noticed how many of these assumptions I had never written down in Windows projects, but had only ever known.

flowchart LR
  A[mono:3.10<br/>base image] --> B[mozroots<br/>SSL certificates]
  B --> C[NuGet.exe install<br/>Nancy + LiteDB]
  C --> D[mcs<br/>compiles nancy.exe]
  D --> E[Image dotnet<br/>approx. 400 MB]
  E --> F[docker run demo1<br/>mono nancy.exe]

The code: a process that opens a port#

The application itself is deliberately plain. The entry point starts a NancyHost and keeps the process alive:

using System;
using Nancy;
using Nancy.Hosting.Self;

class Program
{
    static void Main()
    {
        using (var host = new NancyHost(new Uri("http://localhost:8080")))
        {
            host.Start();
            Console.WriteLine("Nancy host (http://localhost:8080) started.");
            Console.ReadLine();
        }
    }
}

Plus a Nancy module that stores webhooks in LiteDB – a database that sits next to the application as a single file and needs no server:

public class WebHookModule : NancyModule
{
    public WebHookModule() : base("/webhooks")
    {
        Get["/"] = _ =>
        {
            using (var db = new LiteDatabase(@"MyData.db"))
            {
                return db.GetCollection<WebHook>("webhooks")
                    .FindAll()
                    .ToArray();
            }
        };

        Post["/"] = _ =>
        {
            using (var db = new LiteDatabase(@"MyData.db"))
            {
                db.GetCollection<WebHook>("webhooks").Insert(new WebHook());
                return HttpStatusCode.Created;
            }
        };
    }
}

Building and starting takes three commands, exactly as they appear in the README:

docker build -t dotnet .
docker run --name demo1 -p 8080:8080 -i -t dotnet
docker start demo1

Where it got stuck#

It didn’t go smoothly, and the stumbling blocks are more instructive than the happy path. The first start ended with a container that exited immediately. The reason is right there in the code above: Console.ReadLine() only keeps the process alive as long as there is a stdin. Without the -i -t flags, Docker doesn’t provide one, ReadLine returns immediately, Main runs out, the container is dead. That is why the two flags are in the README – not out of diligence, but as a scar. The real lesson: a container lives exactly as long as its process. There is no IIS holding on to the application in the background; the application itself is responsible for not finishing.

The second stumbling block was reachability. On the Mac, the Docker daemon runs in the boot2docker VM, so the service doesn’t answer on localhost but on the VM’s IP – boot2docker ip reveals it. And the fact that the binding to http://localhost:8080 in the container is reachable from outside at all is thanks to a quirk of Nancy’s self-hosting: the HostConfiguration has an option RewriteLocalhost that is enabled by default and turns localhost into a wildcard binding. I only understood that after reading the Nancy source code. If you bind strictly to 127.0.0.1, you see from outside: nothing.

The rest was small stuff that adds up:

  • Fresh Mono images don’t know any SSL root certificates; without mozroots --import --sync, even NuGet’s access to HTTPS sources fails.
  • The packages have to be available as net40 assemblies so that Mono 3.10 loads them cleanly – no problem with Nancy 1.1 and LiteDB 1.0, but quite possibly with more exotic packages.
  • Every RUN creates an image layer; if you build often while experimenting, you learn to love the build cache and to respect the order of the lines.
  • The 400 megabytes stay. A base image with a complete Mono installation is not a lean foundation, and there is currently no leaner one for .NET code.

What the detour taught: process instead of IIS#

The real gain of the experiment is not in the container, but in what the container enforces. A .NET application running under IIS is not an application but a guest: the web server owns the process, the configuration system, the lifecycle. The IIS XML configuration file describes not so much the application as its relationship to the host. In the container, this flips. The application is an ordinary process that opens a port, writes to standard output and can be terminated without anything to clean up.

This also changes where configuration belongs. An image that has to be rebuilt for every environment because the settings are compiled in misses the point. Configuration has to come from outside, and the natural way to do that is environment variables – docker run -e then provides both the capability and the discipline. In the next iteration of the entry point, it looked like this:

static void Main()
{
    var port = Environment.GetEnvironmentVariable("PORT") ?? "8080";
    var uri = new Uri("http://localhost:" + port);

    using (var host = new NancyHost(uri))
    {
        host.Start();
        Console.WriteLine("Nancy host ({0}) started.", uri);
        Console.ReadLine();
    }
}

That seems trivial, but it is a break with years of IIS configuration transformations and registry entries. Interestingly, Heroku’s Twelve-Factor list – public since 2011 – describes exactly this way of thinking: configuration in the environment, stateless processes, logs as an event stream to standard output, explicitly declared dependencies. I had read the manifesto and taken it for a Heroku marketing document. Only the container showed me that it describes what remains when you take the host away from an application.

flowchart TD
  subgraph W[Familiar Windows path]
    W1[Prepare server<br/>with IIS] --> W2[Configure framework<br/>+ app pool]
    W2 --> W3[Transform XML<br/>configuration]
    W3 --> W4[Copy files<br/>and hope]
  end
  subgraph C[Container path]
    C1[Dockerfile<br/>describes everything] --> C2[docker build<br/>reproducible]
    C2 --> C3[docker run -e PORT=8080<br/>configuration from outside]
  end

Then there is repeatability. The image built on my machine is, bit for bit, what runs on any other Docker host. “Works on my machine” stops being an argument, because “my machine” is now a file you can pass on. For someone who has known .NET deployments as a series of manual steps on carefully tended servers, that is the real culture shock – not the technology, but losing the excuses.

An honest assessment#

Still, you have to stay sober. Mono is not the .NET Framework. For Nancy, LiteDB and a manageable API, it holds up without problems; if you bring WCF legacy, WPF or deep Windows dependencies, you won’t get far. If you ship to Windows servers in operations, a Mono container also means testing a different runtime than the production one – that is something you need to know and price in. And the toolchain is noticeably second-tier: no debugging in the container, package management by hand, error messages that assume basic Linux knowledge.

That is why I wouldn’t take this setup into a customer project today. There is too much manual work involved, and a team that has run Windows servers for years doesn’t change its operating model because of one successful prototype. As a learning vehicle, on the other hand, it is hard to beat: every step the Dockerfile makes visible is a step that IIS used to hide.

The direction is right, though. Microsoft apparently means the opening seriously: CoreCLR and the compiler are publicly on GitHub, ASP.NET 5 is explicitly being developed for Linux, and the early betas already run on Mono today. If that delivers on its promise, the Mono detour is a transitional path – but a viable one, today, not someday. I suspect that the skills from this experiment will transfer one to one: writing Dockerfiles, thinking in processes instead of hosts, passing configuration through the environment. The runtime underneath is interchangeable; the way of thinking is not.

What stuck#

The repository is a throwaway experiment, and that is how I treat it. Still, it has permanently shifted my view of .NET deployment, in three places:

  • A Dockerfile is the complete, executable list of all of an application’s runtime assumptions – whatever isn’t in it is silently borrowed from the host.
  • An application that can run as a plain process is the more flexible application – any host, from IIS to a container, can be put on top of it; the reverse is not true.
  • Configuration belongs in the environment, not in the artifact – one build, many deployments.

None of this requires Docker. But Docker forced me to write it down instead of just knowing it, and written-down assumptions can be discussed, checked and passed on. I gladly pay the 400 megabytes for that – disk space is cheap, lost afternoons in front of IIS Manager are not.

Further reading#

Revised and translated from German with the help of AI.