# Running .NET 5 in Linux containers - and measuring its memory

> A complete multi-stage build, an unprivileged process, and a repeatable memory experiment. Image size, managed heap, and container memory are different numbers.

- Author: Deyan Peev (https://deyanpeev.com)
- Published: 2021-06-27
- URL: https://deyanpeev.com/posts/dotnet-five-linux-containers-memory

For a new ASP.NET Core service with portable dependencies, Linux is my
starting point. Kestrel runs the application, configuration comes from the
environment, and Docker packages the result. You don't need IIS or a Windows
guest to serve an HTTP request written in C#.

The more useful question comes after the first successful request. What does
this service need to run? A small download is nice, but it doesn't tell me how
many replicas fit on a host, and an idle process can look cheap until traffic
builds a cache or starts several expensive requests together.

The rest of this post is a complete .NET 5 example, and then the measurements
I'd take before choosing its memory limit. The build uses SDK
5.0.301 and ASP.NET Core 5.0.7, both available in the
[June servicing release](https://devblogs.microsoft.com/dotnet/net-june-2021/).

# A service small enough to understand

In an empty `Probe` directory, create `Probe.csproj`:

```xml
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
    <LangVersion>9.0</LangVersion>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>
```

Create `Program.cs` with the .NET 5 host and startup model:

```csharp
using System;
using System.Diagnostics;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;

Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(web => web.UseStartup<Startup>())
    .Build()
    .Run();

public sealed class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGet("/health", context =>
                context.Response.WriteAsync("ok"));

            endpoints.MapGet("/work", async context =>
            {
                var payload = new byte[64 * 1024];
                Array.Fill(payload, (byte)42);
                context.Response.ContentType = "application/octet-stream";
                await context.Response.Body.WriteAsync(
                    payload, 0, payload.Length, context.RequestAborted);
            });

            endpoints.MapGet("/memory", async context =>
            {
                using var process = Process.GetCurrentProcess();
                await context.Response.WriteAsJsonAsync(new
                {
                    managedBytes = GC.GetTotalMemory(false),
                    workingSetBytes = process.WorkingSet64,
                    allocatedBytes = GC.GetTotalAllocatedBytes(),
                    gen0Collections = GC.CollectionCount(0),
                    gen2Collections = GC.CollectionCount(2)
                });
            });
        });
    }
}
```

The work endpoint allocates and sends a 64 KiB buffer on each request. It's
only there to give the experiment some repeatable activity, it isn't meant to
look like a useful business endpoint. The diagnostic response exposes process
information, so keep this sample on a local test port and don't publish that
endpoint as an unauthenticated production feature.

# Keep the build tools out of the final image

Create this `Dockerfile` beside the project:

```dockerfile
FROM mcr.microsoft.com/dotnet/sdk:5.0.301-buster-slim AS build
WORKDIR /src
COPY Probe.csproj ./
RUN dotnet restore Probe.csproj
COPY Program.cs ./
RUN dotnet publish Probe.csproj -c Release -o /out --no-restore /p:UseAppHost=false

FROM mcr.microsoft.com/dotnet/aspnet:5.0.7-buster-slim AS final
RUN groupadd --gid 10001 app \
    && useradd --uid 10001 --gid app --no-create-home --shell /usr/sbin/nologin app
WORKDIR /app
COPY --from=build /out ./
ENV ASPNETCORE_URLS=http://+:8080
ENV ASPNETCORE_ENVIRONMENT=Production
USER 10001:10001
EXPOSE 8080
ENTRYPOINT ["dotnet", "Probe.dll"]
```

The historical [image manifest](https://github.com/dotnet/dotnet-docker/blob/d121e88133484c53f12e2837a4751033085a0d1b/manifest.json)
and [version definitions](https://github.com/dotnet/dotnet-docker/blob/d121e88133484c53f12e2837a4751033085a0d1b/manifest.versions.json)
identify these Debian Buster images. Explicit versions make the example
reviewable, but tags can still be rebuilt for base-image updates, so record the
resolved digest if you want to reproduce an experiment exactly.

The SDK stage restores and compiles. The ASP.NET image contains the runtime
this web application needs. A plain `runtime` image suits a framework-dependent
application that is not a web app, because it doesn't contain the ASP.NET
shared framework. `runtime-deps` is a different choice again, it only supplies
the native dependencies for a self-contained deployment.

I'm starting with Debian here and not chasing the smallest Alpine image.
Alpine's musl environment changes the native compatibility question, and native
libraries and globalization requirements need checking before the smaller image
is a sensible trade.

The application user is created explicitly. The final process can read the
published files but does not own them, and it listens on port 8080. `EXPOSE`
only documents that port. The environment variable is what tells Kestrel where
to listen, and publishing the port is a separate Docker setting again.

For a larger project I would add the other source files to the copy steps
and use a `.dockerignore` excluding `.git`, `bin`, and `obj`. This tiny build
copies just the two files it needs, so host-generated binaries can't end up in
the image.

# Run it with explicit resources

On a Linux Docker host, build and start it:

```bash
docker build -t probe:net5 .
docker run -d --name probe \
  --memory=256m --memory-swap=256m --cpus=1 \
  -p 127.0.0.1:8080:8080 probe:net5
curl --fail http://127.0.0.1:8080/health
docker exec probe id
```

The last command should show UID and GID 10001. Setting the memory limit and
the total memory-plus-swap limit to the same value disables container swap,
where the host supports that accounting. That makes a memory-pressure
experiment easier to read. Otherwise the service can page its way through the
test and you won't notice.

The 256 MiB limit is a setting for the experiment, I'm not claiming anything
about capacity with it. CPU is constrained too, because available processing
time affects how quickly requests and garbage collections finish. On a Mac or
Windows development machine Linux containers run inside a Linux VM, and the
VM's own budget is one more layer to write down when comparing results.

Environment variables work for ordinary application settings too (a nested
configuration key uses double underscores in its environment-variable form).
Secrets belong in the deployment system's secret mechanism and never in a
Dockerfile layer. Log to standard output so the hosting system can collect it.

# Ask which memory number you are looking at

There are several useful measurements here, and no single one stands in for
the others:

- **Image size** describes filesystem layers. Compressed transfer size and
  local uncompressed size differ, and layers can be shared across images.
- **Working set** describes resident process memory. It includes more than
  managed objects and it isn't the container's full accounting boundary.
- **Managed memory** from `GC.GetTotalMemory(false)` estimates allocated
  managed bytes without forcing a collection. It is not a reserved-heap or
  whole-process measurement, and some unreachable objects may await collection.
- **Allocated bytes** accumulate over the process lifetime. How much they
  change over an interval tells you about allocation activity. It says nothing
  about retained memory.
- **Container memory** includes charges at the cgroup level. The Docker CLI
  applies cache-accounting adjustments, so its display need not equal a raw
  cgroup counter or the process working set.

That last distinction is documented in Docker's
[stats reference](https://github.com/docker/cli/blob/e34c407516eeed9ade6084048c546068c84cc847/docs/reference/commandline/stats.md).
Use the same collection method on both sides of a comparison, and keep the
host and Docker version with the result.

# A repeatable first experiment

Record the image identity and a baseline after the service answers:

```bash
docker image inspect probe:net5 --format '{{.Id}} {{.Size}}'
docker stats --no-stream probe
curl --fail http://127.0.0.1:8080/memory
```

In a second terminal leave `docker stats probe` running. Warm the work
endpoint, then apply a bounded load from the first terminal:

```bash
for i in $(seq 1 100); do
  curl --fail --silent --show-error http://127.0.0.1:8080/work -o /dev/null || break
done

curl --fail http://127.0.0.1:8080/memory
seq 1 1000 | xargs -P 8 -I '{}' \
  curl --fail --silent --show-error http://127.0.0.1:8080/work -o /dev/null
curl --fail http://127.0.0.1:8080/memory
docker stats --no-stream probe
docker inspect probe --format '{{.State.OOMKilled}} {{.State.ExitCode}}'
```

This launches up to eight concurrent curl processes. Treat it as an allocation
exercise. It is no throughput benchmark, because starting curl over and over
has its own cost and the driver can become the bottleneck. Keep the request
count, concurrency, payload, CPU limit, and host the same between runs. And
check the driver's exit status and the server logs, so that failed requests
don't get counted as completed work.

After traffic stops, sample again after a fixed idle interval, and repeat all
of it from a fresh container several times. Keep the peak during traffic as
well as the idle value. A snapshot taken after the work can miss the number
that decides whether a container survives.

For a production decision, repeat with the real route mix, realistic data,
and latency measurements. This toy endpoint has no database pool, no TLS work,
no application cache and no downstream queue, so it can't give you a universal
“.NET uses this much RAM” figure.

# Give the GC room, then investigate the application

Container awareness predates .NET 5. Microsoft's
[container runtime explanation](https://devblogs.microsoft.com/dotnet/using-net-and-docker-together-dockercon-2019-update/)
describes the resource-limit work introduced with .NET Core 3.0. The GC
responds to container constraints, but it cannot make an unbounded cache fit
inside a bounded process.

The [GC heap hard-limit discussion](https://devblogs.microsoft.com/dotnet/running-with-server-gc-in-a-small-container-scenario-part-1-hard-limit-for-the-gc-heap/)
also explains why heap and process limits differ. Threads, native libraries,
generated code, and runtime bookkeeping need memory too, and if the managed
heap got the entire container budget there would be no room left for them.

I'd look first for retained objects, excessive buffering, and work arriving faster
than it completes. Only after that would I compare GC settings, and only if the
the measurements suggest a reason. Workstation GC might be something to try for
a small service, but a flatter memory graph isn't a win if latency or throughput
becomes unacceptable. Forcing collections in request handlers would distort the
experiment too, and it would not fix the cause.

For deployment, what I want out of all this is an image digest, a repeatable
workload, observed peaks and latency, and a limit with room for variation. The
image size is useful packaging information, but it's only one of the inputs.
When the test is finished, `docker rm -f probe` removes the sample container.
