Delivery & OperationsComplete guide

Docker

Docker packages an application, its runtime, and filesystem dependencies into an immutable image executed as isolated containers.

Overview

For .NET, multi-stage builds separate SDK compilation from the smaller ASP.NET or runtime image, keeping source code and compilers out of production. Layer ordering and .dockerignore determine cache efficiency and accidental build inputs. A running container should be replaceable: durable state belongs in external services or deliberate volumes, configuration arrives at runtime, and logs flow to stdout. Production images should run as a non-root user, expose meaningful health signals, honor graceful termination, and be rebuilt, scanned, identified, and promoted immutably whenever application or base-image dependencies change.

What you will learn

  • Explain images, layers, containers, registries, networks, volumes, and Compose.
  • Build a cache-efficient multi-stage .NET image.
  • Run ASP.NET Core as a non-root process with a constrained filesystem.
  • Separate build-time inputs from runtime configuration and secrets.
  • Design container health, logging, shutdown, and external state correctly.
  • Test, scan, publish, and operate immutable images safely.

Prerequisites

  • Basic ASP.NET Core publishing and configuration knowledge.
  • Docker Desktop or another Docker Engine for the container exercises.
  • Familiarity with ports, HTTP health endpoints, and command-line workflows.

When to use Docker

Good fit

  • Portable packaging across developer, CI, and runtime environments.
  • Repeatable service dependencies with Compose for local integration.
  • Immutable deployment units for orchestrators and managed container platforms.

Choose another approach when

  • Treating a container as a durable server with important local state.
  • Baking secrets or environment-specific settings into image layers.
  • Adding containers when a simple process deployment already meets the operational need.

Key concepts

Images and layers

Immutable layers describe a filesystem and startup configuration, enabling caching and content-addressed distribution.

Containers

Running image instances isolate processes and files while sharing the host kernel.

Multi-stage builds

A build stage compiles with the SDK and a final stage carries only publish output and runtime dependencies.

Compose

A declarative local topology coordinates services, networks, volumes, environment, and health dependencies.

Registries and identity

Registries distribute images while tags, digests, signatures, and provenance identify exactly what was built and approved.

Runtime boundaries

Ports, networks, mounts, resource limits, users, capabilities, and signals define how an isolated process interacts with its host and dependencies.

Configuration and secrets

Runtime configuration keeps one image portable while secret mounts or external providers prevent sensitive values from entering layers.

Lifecycle and observability

Health signals, stdout logs, metrics, traces, and graceful termination make a short-lived container operable.

Architecture

Source is compiled in an SDK stage, copied into a minimal runtime image, and executed as a replaceable container connected to external state.

Source + SDK stage
Runtime image
App container
External data

Conceptual architecture · Adapt to your system context

Implementation walkthrough

The Docker Orders API packages a small ASP.NET Core service with a cache-aware multi-stage build, non-root runtime, explicit health endpoints, read-only Compose filesystem, and focused behavior tests.

  1. 01
    Choose the build context

    Build from the narrowest directory that still contains every project reference, shared props file, and lock file required by restore.

  2. 02
    Order layers for caching

    Copy project metadata first, restore dependencies, then copy changing source so ordinary code edits can reuse the restore layer.

  3. 03
    Publish in an SDK stage

    Restore and publish with a pinned SDK family, Release configuration, and no redundant restore during publish.

  4. 04
    Create the runtime stage

    Copy only publish output into the ASP.NET runtime image, set the working directory and port, and use exec-form ENTRYPOINT.

  5. 05
    Reduce privileges

    Run with the .NET image APP_UID, remove unneeded capabilities, prevent privilege escalation, and prefer a read-only root filesystem.

  6. 06
    Inject runtime configuration

    Supply settings through environment variables or mounted configuration and retrieve secrets from an approved runtime secret store.

  7. 07
    Expose operational signals

    Write structured logs to stdout, implement distinct health semantics, and handle termination so in-flight work can finish.

  8. 08
    Verify and distribute

    Test the running image, scan dependencies and layers, generate provenance or an SBOM, tag immutably, and push to a controlled registry.

Code example

A multi-stage Dockerfile restores deterministically, publishes once, and runs the final image without root privileges.

Dockerfile
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY ["Portal.Api.csproj", "."]
RUN dotnet restore "Portal.Api.csproj"
COPY . .
RUN dotnet publish "Portal.Api.csproj" -c Release -o /app --no-restore

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

Testing strategy

Test the artifact that will run, not only the project that produced it.

  • Build with an empty cache periodically to reveal hidden inputs.
  • Start the image with production-like configuration and query health and business endpoints.
  • Assert the runtime user is non-root and the intended port is reachable.
  • Run with a read-only filesystem to expose accidental local writes.
  • Verify graceful stop behavior and bounded termination.
  • Inspect image history and scan the final stage for secrets and vulnerabilities.

Security considerations

A smaller, immutable, least-privileged image narrows risk but still needs supply-chain controls.

  • Use trusted base images and patch by rebuilding regularly.
  • Pin important production inputs by digest and record provenance.
  • Run as non-root with dropped capabilities and no new privileges.
  • Keep credentials out of Dockerfiles, build arguments, layers, and Compose source.
  • Scan OS and application dependencies and define remediation policy.
  • Sign or attest release images where the delivery platform supports verification.

Performance and scalability

Optimize build feedback and runtime behavior independently.

  • Use deterministic layer ordering and a focused .dockerignore.
  • Keep the runtime stage free of SDK and source files.
  • Measure startup, memory, CPU, and request latency under container limits.
  • Set ASP.NET Core thread, GC, and memory behavior from observed workload needs.
  • Avoid writing high-volume data into the container writable layer.

Deployment and operations

Promote one verified image digest and vary only runtime configuration.

  • Publish immutable version and commit tags, then deploy by digest for strong identity.
  • Store images in a private registry with retention and access policy.
  • Inject environment configuration and secrets at runtime.
  • Run pre-deployment smoke and post-deployment health checks.
  • Retain the previous known-good digest for rollback.
  • Rebuild when base-image security updates arrive even if application code is unchanged.

Common problems and fixes

Restore reruns after every code change.

Likely cause: Source was copied before project metadata and restore.

Fix: Copy solution and project files first, restore, then copy source.

The app works locally but the container port is unreachable.

Likely cause: The app listens on another interface or port, or no host port is published.

Fix: Set ASPNETCORE_HTTP_PORTS, expose the container port, and publish the host mapping.

The container exits immediately.

Likely cause: The entry point is wrong or the foreground process failed.

Fix: Inspect container logs, run the image interactively, and verify publish output and ENTRYPOINT.

A non-root container cannot write a file.

Likely cause: The path is owned by root or the filesystem is read-only.

Fix: Write only to an explicit mounted writable path with correct ownership, or externalize the data.

A secret remains visible after deletion.

Likely cause: It was added in an earlier immutable layer.

Fix: Rotate the secret, remove it from build inputs, and rebuild from a clean history.

Compose starts the API before its dependency is usable.

Likely cause: Process start was mistaken for readiness.

Fix: Add a dependency health check and gate startup or make the application retry safely.

Best practices

  • Use multi-stage builds and a minimal trusted runtime base image.
  • Copy project files before source to preserve dependency restore caching.
  • Run as a non-root user and scan both dependencies and the final image.
  • Keep secrets out of layers, build arguments, and committed Compose files.
  • Externalize durable state and make container replacement routine.
  • Publish immutable versions or digests and keep a tested rollback image.

Production checklist

  • Multi-stage build copies only publish output.
  • Restore layers are cache-friendly and deterministic.
  • Runtime process is non-root and minimally privileged.
  • Secrets never enter image layers.
  • State is external or mounted deliberately.
  • Health, logs, and graceful termination are verified.
  • Final image and dependencies pass vulnerability policy.
  • Immutable digest, provenance, and rollback are recorded.

Common interview questions

What is the difference between an image and a container?

An image is an immutable package definition; a container is a running instance with a writable layer and runtime configuration.

Why use a multi-stage build?

It keeps compilers, source, and build caches out of the runtime image, reducing size and attack surface.

Why should container state be externalized?

Containers are replaceable. External databases, object stores, or volumes preserve durable state across restarts, rescheduling, and scaling.

What belongs in .dockerignore?

Exclude build outputs, source-control metadata, editor state, test results, credentials, and any file the image build does not require so contexts stay small and safe.

Why deploy an image digest instead of only a tag?

A digest is content-addressed and immutable, so it proves which exact image was deployed even if a human-readable tag later moves.

How do Docker volumes differ from bind mounts?

Docker manages named-volume storage and lifecycle, while a bind mount exposes a specific host path and therefore couples the container more closely to that host.

What should a container write to stdout?

Write structured application and access logs without secrets; the runtime platform should collect, retain, route, and query them.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

Docker Orders API

A containerized .NET 10 API demonstrating a cache-efficient multi-stage build, non-root execution, health endpoints, runtime configuration, and hardened Compose settings.

ASP.NET Core 10DockerDocker ComposexUnit
dedicated-samplemulti-stagenon-rootcontainer-health
Run
dotnet run --project src/DockerOrdersApi
Test
dotnet test DockerOrdersApi.slnx