Skip to content
Tutorials Center
My learning

Topics

Lesson 88 of 111 ยท Language Recipes

Containerizing a .NET App

Containerize an ASP.NET Core app with Docker: SDK and runtime images, dotnet publish, restore caching, ASPNETCORE_HTTP_PORTS, non-root users and chiseled images.

.NET is a good fit for containers: an ASP.NET Core app is a self-contained web server (Kestrel) that listens on a port, writes logs to the console and shuts down on SIGTERM. Microsoft publishes official images for both halves of the job, a large SDK image that can build your code and a much smaller runtime image that can only run it. The standard recipe is a multi-stage build that uses the first to produce the files and the second to ship them.

In this lesson you will containerize a minimal ASP.NET Core API on .NET 10. You will see how the restore step is cached, what the two images contain, how ports are configured with ASPNETCORE_HTTP_PORTS and why ASPNETCORE_URLS can surprise you, how to run as a non-root user, and how a chiseled image cuts the size by almost half. Everything below was built and run for real. If multi-stage builds are new, read Multi-Stage Builds first.

The sample project

Two files are enough. The project file Hello.csproj uses the Web SDK:

XML
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <InvariantGlobalization>true</InvariantGlobalization>
  </PropertyGroup>

</Project>

InvariantGlobalization tells .NET not to load the ICU culture libraries. Alpine and chiseled images do not include the ICU library, and without this setting .NET stops at startup complaining about it (we ran with the setting on, so we did not see that message). If you need real culture data (date formats for many locales), use an image that includes ICU instead. Program.cs:

C#
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello from .NET in a container");
app.MapGet("/health", () => "ok");
app.MapGet("/info", () => new
{
    Runtime = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription,
    User = Environment.UserName,
    Urls = Environment.GetEnvironmentVariable("ASPNETCORE_URLS"),
    Environment = app.Environment.EnvironmentName,
});

app.Run();

The /info endpoint reports facts we want to check from inside the container: the runtime version, the Linux user and the URL configuration.

SDK image versus runtime image

Microsoft's images live on its own registry, mcr.microsoft.com, under dotnet/:

Image Purpose Size (our pull)
mcr.microsoft.com/dotnet/sdk:10.0 dotnet restore, build, publish, test; compilers, NuGet, MSBuild 1.3 GB
mcr.microsoft.com/dotnet/aspnet:10.0 Runs ASP.NET Core apps; runtime only about 100 MB of .NET plus the base OS
mcr.microsoft.com/dotnet/runtime:10.0 Runs console apps; no ASP.NET Core not pulled here

Shipping the 1.3 GB SDK to production would work, but it adds compilers an attacker could use and a lot of download time. So we use the SDK only in the build stage.

The Dockerfile

DOCKERFILE
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY Hello.csproj ./
RUN dotnet restore
COPY . .
RUN dotnet publish -c Release -o /out --no-restore -p:UseAppHost=false

FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS runtime
WORKDIR /app
COPY --from=build /out .
USER $APP_UID
EXPOSE 8080
ENTRYPOINT ["dotnet", "Hello.dll"]

What each part does:

  • COPY Hello.csproj ./ then dotnet restore. NuGet packages are downloaded in a layer that depends only on the project file. Changing C# code does not invalidate it. In a real solution with several projects, copy every .csproj (and Directory.Packages.props, nuget.config) before restoring. This is the .NET version of "dependencies first, code second" from The Build Cache.
  • dotnet publish -c Release -o /out --no-restore. Compiles in Release mode and writes everything needed to run the app into /out: your DLL, its dependencies and the configuration files. --no-restore reuses the restore layer. -p:UseAppHost=false skips the native launcher executable you do not need, because we start the app with dotnet Hello.dll.
  • FROM ...aspnet:10.0 is the runtime stage. It has the shared framework but no compiler.
  • USER $APP_UID. The Microsoft images define a non-root user named app and the environment variable APP_UID holding its numeric ID. By default the container still runs as root; you opt in with this line. Compare the two runs below.
  • ENTRYPOINT ["dotnet", "Hello.dll"] uses the exec form, so dotnet is PID 1 and receives SIGTERM directly (see CMD and ENTRYPOINT).

Create a .dockerignore with bin, obj and the Dockerfile itself. Local bin/ and obj/ folders contain Windows paths and stale build outputs that must not leak into a Linux build. See Build Context and .dockerignore.

Build and look at the result:

CONSOLE
$ docker build -t hello-dotnet .
$ docker images hello-dotnet --format '{{.Size}}'
340MB
$ docker run --rm --entrypoint "" hello-dotnet ls /app
Hello.deps.json
Hello.dll
Hello.pdb
Hello.runtimeconfig.json
Hello.staticwebassets.endpoints.json
web.config

The application itself is about 57 kB (docker history shows the COPY /out . layer at 57.3kB); the other 340 MB is the base image with the .NET runtime (27 MB of it is the ASP.NET Core framework layer, and the shared runtime sits beneath it). That is a fair price for a full web framework.

The restore cache at work

Change one line of Program.cs and rebuild. Only the publish step has to run again:

CONSOLE
$ docker build -t hello-dotnet . 2>&1 | grep -E "CACHED|DONE [0-9]|restore|publish"
#8 CACHED
#9 CACHED
#10 [build 4/6] RUN dotnet restore
#10 CACHED
#11 DONE 0.1s
#12 [build 6/6] RUN dotnet publish -c Release -o /out --no-restore -p:UseAppHost=false
#12 DONE 7.6s
#13 CACHED

dotnet restore was CACHED; only dotnet publish re-ran, in 7.6 seconds. Had we written the usual shortcut COPY . . followed by RUN dotnet publish, every code edit would re-download all NuGet packages.

If your builds are slow because of large package sets, add a BuildKit cache mount for the NuGet folder (read-only example, not run here):

DOCKERFILE
RUN --mount=type=cache,target=/root/.nuget/packages dotnet restore

Running it

CONSOLE
$ docker run -d --name hello-dotnet -p 127.0.0.1:8080:8080 hello-dotnet
$ curl -s 127.0.0.1:8080/
Hello from .NET in a container
$ curl -s 127.0.0.1:8080/info
{"runtime":".NET 10.0.13","user":"app","urls":null,"environment":"Production"}
$ docker logs hello-dotnet | head -4
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://[::]:8080
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.

Three things to notice. The process runs as the non-root user app. The environment is Production (the Microsoft images do not set ASPNETCORE_ENVIRONMENT, and the default is Production, so detailed error pages stay off). And Kestrel listens on port 8080 even though our code never says so: the image does that for us.

For comparison, without USER $APP_UID the same app reports "user":"root". The container is not much less secure for it, but a bug that allows file writes then has far more reach, so always drop root. See Users and Permissions.

Stopping is clean and fast, because ASP.NET Core's host listens for SIGTERM:

CONSOLE
$ docker stop hello-dotnet
hello-dotnet
$ docker inspect -f '{{.State.ExitCode}}' hello-dotnet
0

It took one second and exited with code 0 (graceful shutdown).

Ports: HTTP_PORTS versus URLS

Since .NET 8 the official images no longer listen on port 80. They listen on 8080, so a non-root user can bind without special privileges (ports below 1024 need root or a capability). The mechanism is an environment variable that the image sets:

CONSOLE
$ docker inspect -f '{{json .Config.Env}}' hello-dotnet
["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin","APP_UID=1654","ASPNETCORE_HTTP_PORTS=8080","DOTNET_RUNNING_IN_CONTAINER=true","DOTNET_VERSION=10.0.13","ASPNET_VERSION=10.0.13"]

ASPNETCORE_HTTP_PORTS=8080 is the variable to change. Pass another value and Kestrel follows; remember to publish the matching port:

CONSOLE
$ docker run -d --name hello-dotnet-5000 -e ASPNETCORE_HTTP_PORTS=5000 -p 127.0.0.1:8080:5000 hello-dotnet
$ docker logs hello-dotnet-5000 | head -2
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://[::]:5000

The older variable ASPNETCORE_URLS (for example http://+:80) still works, and it wins over the newer one. Many tutorials, Visual Studio-generated Dockerfiles from years ago and some Helm charts still set it, which can silently move your port. The app prints a warning:

CONSOLE
$ docker run -d --name hello-dotnet-urls -e ASPNETCORE_URLS=http://+:9090 -p 127.0.0.1:8080:9090 hello-dotnet
$ docker logs hello-dotnet-urls | head -2
warn: Microsoft.AspNetCore.Hosting.Diagnostics[15]
      Overriding HTTP_PORTS '8080' and HTTPS_PORTS ''. Binding to values defined by URLS instead 'http://+:9090'.

Prefer ASPNETCORE_HTTP_PORTS, and keep EXPOSE equal to it (EXPOSE is only documentation, see Publishing Ports).

HTTPS is normally terminated in front of the container (a reverse proxy, a load balancer, a cloud ingress), and the container serves plain HTTP on a private network. If you must serve HTTPS from Kestrel itself, mount a certificate and set ASPNETCORE_HTTPS_PORTS and Kestrel__Certificates__Default__Path. For local development the old dotnet dev-certs flow does not work inside a Linux container as-is. Behind a proxy, also configure forwarded headers (ASPNETCORE_FORWARDEDHEADERS_ENABLED=true) so the app sees the real client scheme and IP.

Configuration through the environment

ASP.NET Core maps environment variables onto its configuration system. A double underscore means a colon (a nested key), which is how you set connection strings and options at run time:

CONSOLE
$ docker run -d -e ASPNETCORE_ENVIRONMENT=Development -e ConnectionStrings__Default="Host=db;Database=app" hello-dotnet

The first sets the environment name (and, in Development, enables the detailed error page); the second becomes Configuration["ConnectionStrings:Default"]. Never bake production secrets into appsettings.json inside the image. See Configuring Containers and Managing Secrets.

Chiseled images: smaller and safer

Ubuntu offers chiseled images: the distribution is cut down to the exact files the runtime needs. There is no shell, no package manager, and the default user is already non-root. Microsoft publishes aspnet:10.0-noble-chiseled (and variants with extra libraries). Only the runtime stage of the Dockerfile changes:

DOCKERFILE
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble-chiseled AS runtime
WORKDIR /app
COPY --from=build /out .
EXPOSE 8080
ENTRYPOINT ["dotnet", "Hello.dll"]
CONSOLE
$ docker images --format '{{.Repository}} {{.Size}}'
hello-dotnet-chiseled 180MB
hello-dotnet 340MB
$ docker run -d --name hello-chiseled -p 127.0.0.1:8080:8080 hello-dotnet-chiseled
$ curl -s 127.0.0.1:8080/info
{"runtime":".NET 10.0.13","user":"app","urls":null,"environment":"Production"}
$ docker exec hello-chiseled sh
OCI runtime exec failed: exec failed: unable to start container process: exec: "sh": executable file not found in $PATH
$ docker inspect -f '{{.Config.User}}' hello-chiseled
1654

It is 180 MB against 340 MB, runs as user app (UID 1654) without any USER line, and offers no shell for an intruder, or for you. That makes debugging harder (see Debugging Containers) and means HEALTHCHECK commands that call curl or sh cannot work. The usual answers are an orchestrator-level HTTP probe, or a tiny health mode in your own program. Chiseled images need InvariantGlobalization unless you pick the ICU-enabled variant (the -extra tag).

Health checks in the regular image

The regular aspnet image has bash but no curl and no wget, so the familiar curl -f health check fails. Bash can open a TCP socket by itself, which is enough for a check against /health:

CONSOLE
$ docker run -d --name hello-health \
    --health-cmd "bash -c 'exec 3<>/dev/tcp/127.0.0.1/8080 && printf \"GET /health HTTP/1.0\r\n\r\n\" >&3 && grep -q ok <&3'" \
    --health-interval 3s hello-dotnet
$ docker ps --filter name=hello-health --format '{{.Status}}'
Up 10 seconds (healthy)

For a long-lived service you would write that into a HEALTHCHECK instruction or a Compose healthcheck: block (see HEALTHCHECK). ASP.NET Core also has a built-in health-check middleware (AddHealthChecks() and MapHealthChecks("/health")) that can report on the database and other dependencies.

Compose and the rest of the stack

An API needs a database. In Compose the connection string uses the service name as host:

YAML
services:
  api:
    build: .
    ports:
      - "127.0.0.1:8080:8080"
    environment:
      ConnectionStrings__Default: "Host=db;Database=app;Username=app;Password=${DB_PASSWORD}"
    depends_on:
      db:
        condition: service_healthy
  db:
    image: postgres:17-alpine
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: ${DB_PASSWORD}
      POSTGRES_DB: app
    volumes:
      - dbdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app"]
      interval: 5s
volumes:
  dbdata:

(Read-only example. A complete, verified Compose stack with a database is in Project: A Node.js API with a Database; the ideas carry over.) Run Entity Framework migrations as a one-off step, for example a separate migrate service or a dotnet ef database update run from the SDK image, not at the start of every replica.

Pitfalls checklist

  • Windows paths and line endings. A bin/ or obj/ folder from Windows in the build context breaks the Linux build; use .dockerignore.
  • Port 80 in old samples. Dockerfiles for .NET 6 or earlier assumed port 80; a non-root process cannot bind a port below 1024 by default, so the current images moved to 8080. Use 8080.
  • ASPNETCORE_URLS overriding the port, as shown above.
  • Missing ICU in Alpine and chiseled images: set InvariantGlobalization or install ICU.
  • Memory limits. .NET reads the cgroup limit, so docker run --memory=256m makes the garbage collector size itself accordingly. Still leave headroom (see Resource Limits).
  • Tag drift. aspnet:10.0 follows the latest servicing release and may change its base distribution over time (our pull of it was based on Ubuntu 24.04). Pin a full version such as 10.0.13 when you need repeatable builds.
  • Alpine or native AOT. The -alpine variants and Native AOT publishing shrink images further but bring musl and trimming restrictions. Measure and test before switching.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why do we copy only the .csproj file before running dotnet restore?

    A layer is reused only if its inputs are unchanged. Restoring from the project file alone keeps the NuGet download cached while you edit C# files. In our rebuild the restore step showed CACHED and only publish ran again.
  2. 2. What is the difference between the sdk and aspnet images?

    Build in the SDK image and ship the runtime image. Shipping the SDK would add about a gigabyte and tools an attacker could use.
  3. 3. Which environment variable should you change to move Kestrel to another port in a current official image?

    The image sets ASPNETCORE_HTTP_PORTS=8080. ASPNETCORE_URLS still works but overrides it and prints a warning. EXPOSE is only documentation and PORT is not read by ASP.NET Core.
  4. 4. What does USER $APP_UID do in the runtime stage?

    The image already defines the user and exports its numeric ID in APP_UID. Without the USER line the container runs as root; with it, /info reports user app.
  5. 5. Why can a HEALTHCHECK that calls curl fail in a chiseled .NET image?

    Chiseled images are cut down to the runtime's needs: no shell, no package manager. Our docker exec sh failed with executable file not found. Use an external probe or a health mode inside your own binary.

Summary

  • Build with mcr.microsoft.com/dotnet/sdk and run with dotnet/aspnet: 1.3 GB toolchain, 340 MB runtime image for our API.
  • Copy the .csproj first and dotnet restore in its own layer, so editing code only re-runs dotnet publish (7.6 s in our test).
  • Use dotnet publish -c Release -o /out --no-restore and an exec-form ENTRYPOINT ["dotnet", "App.dll"].
  • Current images listen on port 8080 (ASPNETCORE_HTTP_PORTS); the older ASPNETCORE_URLS overrides it and prints a warning.
  • Drop root with USER $APP_UID; chiseled images do it by default, shrink to 180 MB and remove the shell.
  • Configure through environment variables with __ for nested keys; set InvariantGlobalization when the image has no ICU.
  • The runtime image has no curl; use bash sockets, a probe from outside, or the chiseled-friendly approach of an in-app check.

Next: Running Databases in Containers