Dockerizing a .NET Application: Multi-Stage Builds Done Right
Dockerizing a .NET application properly: SDK vs runtime images, a cached multi-stage Dockerfile, .dockerignore, non-root user, and chiseled images.
.dockerignore keeps build contexts small and bin/obj out, the image runs as a non-root user on port 8080 by default, and tags are versioned, never latest.The image that motivates this page is the one everybody builds first: FROM mcr.microsoft.com/dotnet/sdk:10.0, copy the source in, run the app inside the SDK. Ship the result as a 1.5 GB image carrying the compiler, your source code, and the NuGet cache to every server. It works, and it is wrong in the three ways that matter in production: size, security surface, and secret leakage (the source it contains includes committed configuration).
Dockerizing a .NET application means building a two-stage image where the final stage contains only what the published app needs: the official .NET container documentation is the reference. This page is the working Dockerfile. The deep theory of multi-stage builds, secret handling, and container security has its own series: deep coverage of multi-stage patterns, environment variables and secrets, and container security belongs in my Docker guide.
The examples build the TaskApi on .NET SDK 10.0. Version your base images with your runtime version, which is the version decision covered by the LTS vs STS guide: the tag 10.0 below pins the current LTS.
Shrinking a few of those first-day images showed me this: the .NET base images are unusually good. Most “slow Docker builds” and “huge images” are self-inflicted. The Dockerfile below is the one that fixes both.
Two images: the SDK builds, the runtime runs
Microsoft publishes a family of .NET images, and the split that matters is build versus run:
| Image | Contains | Role in the build | Typical size class |
|---|---|---|---|
mcr.microsoft.com/dotnet/sdk:10.0 |
SDK: MSBuild, compilers, NuGet tooling | Build and publish stage only | Largest |
mcr.microsoft.com/dotnet/aspnet:10.0 |
ASP.NET Core runtime | Final stage for web APIs and sites | Much smaller |
mcr.microsoft.com/dotnet/runtime:10.0 |
Base .NET runtime, no ASP.NET Core | Final stage for console apps and workers | Smallest standard |
...:10.0-noble-chiseled variants |
Same runtimes on a stripped Ubuntu base, no shell or package manager | Hardened final stage | Smallest overall |
The final stage should be the smallest image that can run your published app: aspnet for web apps, runtime for workers and consoles, and the -chiseled variants when you want a minimal surface with no shell. The MCR catalog lists the current tags for every image. Check it before pinning, because the available tags evolve with each release.
The Dockerfile, line by line
# TaskApi.Dockerfile
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
# 1. copy project files only: restores are cached per project
COPY TaskApi/TaskApi.csproj TaskApi/
COPY TaskApi.Tests/TaskApi.Tests.csproj TaskApi.Tests/
# 2. restore runs BEFORE source is copied
RUN dotnet restore TaskApi/TaskApi.csproj
# 3. now the source, which changes often
COPY TaskApi/ TaskApi/
# 4. publish into a clean folder
RUN dotnet publish TaskApi/TaskApi.csproj -c Release -o /app
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final
WORKDIR /app
# 5. only the published output crosses the stage boundary
COPY --from=build /app .
# 6. the runtime image runs as non-root by default; this just makes it explicit
USER $APP_UID
EXPOSE 8080
ENTRYPOINT ["dotnet", "TaskApi.dll"]
Read it top down as a handoff: the build stage compiles and publishes into /app. The final stage starts from the small runtime image and copies only that folder. The SDK, the source code, and the NuGet cache stay behind. The USER $APP_UID line pins the non-root user the images define by default (a distinct account, not UID 0), and EXPOSE 8080 documents the port the runtime images already listen on by default.
Build it and check the size
docker build -f TaskApi.Dockerfile -t taskapi:1.0.0 .
docker images taskapi
# output shape (your size depends on the app and base image):
REPOSITORY TAG IMAGE ID SIZE
taskapi 1.0.0 2f5c9d8a1111 2xxMB
Measure yours with docker images before and after: a simple web API published into the aspnet runtime image lands in the low hundreds of megabytes. By contrast, the same app shipped from the SDK stage carries the compiler and lands roughly a gigabyte heavier. That difference is the whole technique in one number.
docker run --rm -p 8080:8080 taskapi:1.0.0
# expected (trimmed):
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://[::]:8080
Why the restore layer saves your rebuilds
Docker caches layers, and the order of COPY instructions decides what a change invalidates. Copying project files and running dotnet restore before copying source means an edit to a controller invalidates only the layers after the restore: the cached restore layer is reused. The rebuild takes seconds instead of a full dependency download. Change the csproj (add a package), and the restore layer finally rebuilds.
edit Program.cs -> layers 3-4 rerun, layers 1-2 cached
add a NuGet package -> layer 1 changes, restore and everything after reruns
That is the entire game: order the Dockerfile from stable to volatile, and Docker’s cache does the rest. The deeper mechanics of layer caching, BuildKit cache mounts, and registry caching belong in my Docker guide’s multi-stage build guide.
.dockerignore: the file everyone forgets
.git
.gitignore
bin/
obj/
node_modules/
*.user
.idea/
.vs/
logs/
Two consequences come from one missing file. First, the build context upload: docker build sends every non-ignored file to the daemon. A repository with build output and Git history can transfer hundreds of megabytes per build (watch the “transferring context” line in the build output). Second, and worse: copying bin and obj into the image can interfere with dotnet publish, because stale local output leaks into the publish result. The file above costs one minute to write and prevents both.
Ports, users, and the chiseled option
- Port: since .NET 8, the runtime images listen on port
8080by default (theASPNETCORE_HTTP_PORTSenvironment variable), not the historical5000/5001. Publish with-p 8080:8080as above. Configuring ports via environment variables is the standard pattern. The details of passing secrets the same way belong in my Docker guide’s environment variables and secrets guide. - User: the .NET images define a non-root
appuser, exposed as the$APP_UIDenvironment variable. The images run as that user by default. The explicitUSER $APP_UIDline documents the guarantee and survives future base image changes. Running containers as root is a finding in every security review, and the hardening checklist is longer than this page: deep coverage belongs in my Docker guide’s security best practices guide. - Chiseled images: the
10.0-noble-chiseledvariants strip the OS to the files the runtime needs: no shell, no package manager, a much smaller surface. They are the right default for hardened production images; verify the exact tag on the MCR catalog for your release.
Publishing an image without a Dockerfile
For simple cases, the .NET SDK can produce the container image directly, configured through MSBuild properties in the csproj:
<PropertyGroup>
<ContainerImageName>taskapi</ContainerImageName>
<ContainerBaseImage>mcr.microsoft.com/dotnet/aspnet:10.0</ContainerBaseImage>
</PropertyGroup>
dotnet publish TaskApi/TaskApi.csproj -c Release -t:PublishContainer
The container publish configuration reference documents the full property set (ContainerImageTag for versions, ContainerRegistry for the destination, ContainerFamily for variants such as chiseled). The Dockerfile remains the right tool when the build needs custom steps (installing certificates, extra files, multi-project orchestration). SDK publishing is the lighter path when the image is exactly “this project, that base”.
How real systems do this
- One Dockerfile, built by CI. The same Dockerfile builds locally and in the pipeline. As a result, the image on the registry is reproducible from a commit hash. The CI/CD guide covers the build-and-push stage (its general shape lives in the Docker guide’s image build and push guide).
- Tags are versions, never latest. Deployments reference immutable tags (a version, a commit SHA) so a rollback is a tag change. The versioning itself is the LTS-vs-STS cadence from the versions guide.
- The image is the unit that runs everywhere. The same artifact that ran locally runs on Kubernetes with health checks and graceful shutdown, the platform side covered by the .NET in Kubernetes guide.
A first-week image I helped debug was the textbook case. A team had copied the whole repository into the SDK image and run the app there. Their “Docker build” worked but shipped 2 GB per push, with the Git directory and a test certificate accidentally inside. The fix was the two-stage Dockerfile from this page, and the image dropped to a fraction of the size. The lesson nobody warns you about: the working container is the dangerous one, because nothing fails until you count the megabytes or the vulnerabilities.
Decision framework: building your image
- What runs in production? A web API or site: the
aspnetruntime image. A console app or worker service: theruntimeimage. Never the SDK. - Standard or chiseled? Hardened production and smallest surface:
-noble-chiseled. You need a shell for debugging or extra OS packages during setup: standard tags plus a copy step from a-extrabuild stage. - Dockerfile or SDK publish? Custom build steps or multi-project orchestration: Dockerfile. Straight “publish this project onto that base”: the MSBuild container properties, one command, no Dockerfile to maintain.
- What invalidates the cache? Copy csproj files first, restore, then source. Anything volatile belongs as late in the Dockerfile as possible.
- What is in the context? Write
.dockerignorebefore the first build, not after the first slow build.
When NOT to use a multi-stage Dockerfile
- Development environments. A dev container or a local run with the SDK should include the SDK, source watching, and tooling. The runtime-only image is for shipping, not for development.
- Jobs that genuinely need the SDK at runtime. A service that compiles code on demand is the rare case that needs the SDK image in production; document why, and treat it as an exception.
- When your platform builds images for you. App Service code deployments and platform buildpacks produce the runtime artifact without a Dockerfile. A custom one earns its place when you need it, not before.
Common mistakes
- Shipping the SDK stage. Copying the app from the build stage’s filesystem instead of the published
/appfolder lands a gigabyte image with your source inside; only published output crosses. - The latest tag.
FROM ...:latestand-t myapp:latestmake builds irreproducible and rollbacks impossible; pin the runtime major and version the output. - Restoring after copying source. Every source edit then reinstalls every package; the csproj-first, restore-second order is what keeps rebuilds fast.
- No .dockerignore. Huge context transfers and stale
bin/objleaking into the publish output; both are one file away from fixed. - Running as root. The images ship a non-root user by default. An explicit
USER $APP_UIDkeeps the guarantee if the base image changes. - Assuming port 5000. The runtime images listen on 8080 by default since .NET 8. Publishing with
-p 5000:8080(or the right pair) matters more than the port number itself.
Key takeaways
- Two stages: the SDK image builds and publishes; the smallest runtime image (
aspnet,runtime, or chiseled) runs; only published output crosses. - Order the Dockerfile stable-to-volatile: project files, restore, source, publish, so code edits reuse the cached restore layer.
.dockerignorekeeps the context small and build output out of the image.- Runtime images listen on port 8080 by default and run as the non-root
appuser. Both are defaults worth keeping explicit. - Chiseled tags (
10.0-noble-chiseled) strip the shell and package manager for hardened production images; verify current tags on the MCR catalog. - Version your image tags and never use
latest. The CI/CD guide builds and pushes the same Dockerfile, and general Docker topics continue in the Docker guide.
FAQ
Which .NET Docker image should the final stage use?
The smallest image that can run your published app: aspnet for web APIs and sites, the base runtime image for console apps and worker services, and the chiseled variants when you want a minimal OS surface with no shell. The SDK image stays in the build stage and never ships, because the compiler and NuGet cache are dead weight at runtime.
Why use a multi-stage Dockerfile for .NET?
Because the build needs a large image and production needs a small one. The first stage uses the SDK to restore and publish. The second stage starts from the small runtime image and copies only the published folder. The result is an image hundreds of megabytes smaller, with no source code or toolchain inside, and rebuilds that reuse the cached restore layer whenever only source changed.
What port does a .NET container listen on?
Port 8080, since .NET 8: the runtime images set the ASPNETCORE_HTTP_PORTS environment variable to 8080, and Kestrel binds it by default. The historical ports 5000 and 5001 are pre-.NET 8 defaults that no longer apply unless you configure them yourself. Map it when you run: docker run -p 8080:8080.
Do .NET containers run as root?
No: the Microsoft images define a dedicated non-root user and run as it by default. The USER line with the $APP_UID variable makes the choice explicit in your Dockerfile and protects it from base image changes. Running as root is flagged by every container security scanner, so keeping the default is the free, correct choice.
What are chiseled .NET container images?
Hardened variants of the runtime images built on a stripped Ubuntu base, tagged like 10.0-noble-chiseled: no shell, no package manager, only the files the runtime needs. They reduce both image size and attack surface, and they are the recommended final stage for production images. Check the MCR catalog for the exact tags available for your release.
Build with the SDK, ship the runtime
The whole technique is one sentence: the build image and the run image are different, and the publish step is the bridge between them. Get the stage order right, keep the context clean, stay non-root, tag versions, and the same image that built in seconds on your laptop runs hardened in production. The deployment track continues with deploying .NET apps to Azure App Service, and every guide in the series lives on the .NET series index. The rule of thumb: if the compiler is in your runtime image, the Dockerfile is not done.
Last updated on 28 November 2026