Volume 5 · Chapter 2 — Advanced .NET Cloud Native Architecture
Containerization with Docker
2.1 Introduction
Containers package an application with its dependencies so it runs consistently across development, testing, and production - eliminating “works on my machine.” For .NET, containers provide portability, scalability, and simplified deployment, and are the foundation of every orchestration and cloud-native platform. The key engineering practices are multi-stage builds (small, secure images) and running containers with least privilege.
2.2 Containers vs Virtual Machines
A VM includes a full guest operating system, so it is heavyweight and slow to start. A container shares the host kernel and packages only the application and its dependencies, so it is lightweight and starts in seconds. This efficiency is what enables high container density and fast autoscaling.
| Virtual Machine | Container |
|---|---|
| Full guest OS per VM | Shares host kernel |
| Heavy, slow to start | Lightweight, fast start |
| Coarse-grained isolation unit | Fine-grained, dense packing |
2.3 Images and the Multi-Stage Build
A Dockerfile defines how the app is built and packaged into an image; a container is a running instance of an image. The essential practice for .NET is the multi-stage build: use the SDK image to build and publish, then copy only the published output into a minimal runtime image - producing a small, fast-starting, more secure final image without the build tools.
flowchart TB DF["Dockerfile"] --> Build["Build stage (SDK image)\nrestore + publish"] Build --> Runtime["Runtime stage (small runtime image)\ncopy published output only"] Runtime --> Img["Small, secure image"] Img --> Cont["Running container"]
// Dockerfile (multi-stage): build with the SDK, run on a minimal runtime image, as non-root.
// FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
// WORKDIR /src
// COPY . .
// RUN dotnet publish -c Release -o /app
//
// FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS final
// WORKDIR /app
// COPY --from=build /app .
// USER app # run as non-root (least privilege)
// ENTRYPOINT ["dotnet", "Payments.Api.dll"]
2.4 Security and Compose
Container security means using minimal official base images, scanning images for vulnerabilities, running as a non-root user, and never baking secrets into images. Docker Compose defines and runs multiple containers together (app, database, cache) for local development, but orchestration in production is Kubernetes or Container Apps (next chapters).
What is the difference between a container and a virtual machine, and why do containers suit cloud-native apps?
The fundamental difference is what they virtualize and how much they carry. A virtual machine virtualizes hardware and runs a complete guest operating system on top of a hypervisor, so each VM includes its own OS kernel, is large (gigabytes), and is slow to boot (tens of seconds to minutes) - it provides strong isolation but is heavyweight. A container virtualizes at the OS level: it shares the host’s kernel and packages only the application plus its dependencies and libraries, isolated via kernel features (namespaces, cgroups), so it’s lightweight (megabytes), starts in seconds or less, and many containers pack densely onto one host. Both give consistency and isolation, but containers achieve it far more efficiently because they don’t duplicate an entire OS per instance. Containers suit cloud-native applications precisely because of that efficiency and speed. Fast startup enables rapid autoscaling and quick rolling deployments - you can spin up new instances in seconds to meet load and replace them without disruption, which stateless cloud-native services rely on. Small footprint enables high density - many containers per node - which improves resource utilization and lowers cost, and produces small images that deploy quickly. Consistency (the container carries its dependencies) delivers the same behavior across dev, test, and production, eliminating environment drift. Portability means the same image runs on any container platform (local, any cloud, Kubernetes). And containers are the natural unit of deployment for orchestrators like Kubernetes, which schedule, scale, and self-heal them. So while VMs give heavier, OS-level isolation suited to running whole different operating systems or strong multi-tenant boundaries, containers give lightweight, fast, dense, portable packaging of applications - which is exactly what cloud-native architecture needs for elastic scaling, fast deployment, efficient resource use, and orchestration. That’s why containers, not VMs, are the deployment unit of cloud-native systems, though the two are often combined (containers running on VM-based nodes).
What are the most important practices for building production-ready .NET container images?
Production-ready container images should be small, secure, fast-starting, and correctly configured, and I’d call out several practices. First, use multi-stage builds: build and publish the app in a full SDK image, then copy only the published output into a minimal runtime image, so the final image contains just what’s needed to run - no SDK, no build tools, no source - which makes it smaller (faster pulls, denser packing), faster to start, and more secure (smaller attack surface). Second, use official, minimal, and pinned base images (the Microsoft .NET runtime images, and consider chiseled/distroless variants for an even smaller surface), pinned to specific versions for reproducibility, and keep them updated for security patches. Third, run as a non-root user - modern .NET images support this - and apply least privilege (read-only filesystem where possible, dropped capabilities), so a compromised container has limited power. Fourth, never bake secrets into images - no connection strings, keys, or certificates in the Dockerfile or layers, because image layers are inspectable and images get shared; secrets come from the platform at runtime (environment, mounted secrets, Key Vault via workload identity). Fifth, scan images for vulnerabilities in the CI pipeline (base image and dependency CVEs) and fail the build on critical findings, and ideally sign images and verify signatures so only trusted images are deployed - securing the supply chain. Sixth, optimize the build for layer caching and small size (order Dockerfile steps so dependencies restore in a cached layer, use .dockerignore to exclude junk) so builds are fast and images lean. Seventh, make the image cloud-native-ready: externalize configuration (read from environment, not baked in), expose health check endpoints, handle the shutdown signal for graceful termination, and set sensible resource expectations - so the orchestrator can manage it. Eighth, consider startup performance (ReadyToRun or Native AOT, and trimming) where cold-start or footprint matters, to shrink the image and speed startup for autoscaling. And produce reproducible builds through CI rather than ad hoc local builds, tagging images with a version/commit for traceability. So the priorities are: multi-stage builds for small/secure images, minimal pinned official base images, non-root least-privilege execution, no secrets in images, vulnerability scanning and signing in the pipeline, build optimization for size and caching, and cloud-native readiness (externalized config, health checks, graceful shutdown) - which together yield images that are lean, secure, fast, and safe to run at scale in production, rather than the bloated, root-running, secret-laden images that naive Dockerfiles produce.
2.5 Enterprise Scenario
A bank modernizes a legacy .NET service by packaging it into a Docker container with a multi-stage build - the final image runs on a minimal runtime base as a non-root user, contains no secrets, and is scanned and signed in CI. Development, testing, and production now deploy the same immutable artifact, eliminating environment drift, and the small, fast-starting image packs densely and autoscales quickly on the container platform.
Chapter Revision Notes
- Containers share the host kernel - lightweight and fast vs heavyweight VMs.
- A Dockerfile builds an image; a container is a running instance.
- Use multi-stage builds: SDK to build, minimal runtime image to run - small and secure.
- Run as non-root, use minimal pinned base images, scan/sign images, and never bake in secrets.
- Compose for local multi-container dev; Kubernetes/Container Apps for production orchestration.