Skip to Content
Cloud Engineering Academy
3. .NET Application Development on AWS

Containerising .NET for AWS

Build small, secure, fast-starting container images for ASP.NET Core: multi-stage Dockerfiles, Ubuntu chiseled images, non-root users, read-only file systems, globalisation and time-zone trade-offs, arm64 builds, SDK container publishing and how to measure size and startup.

intermediate⏱ 2 h 🟢 FreeDVA-C03

Assumes: .NET 10 LTS (10.0.15 images) · mcr.microsoft.com/dotnet/aspnet:10.0-noble-chiseled · Docker Desktop with BuildKit · Region us-east-1. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lesson you can:

  • Write a multi-stage Dockerfile for an ASP.NET Core API that caches NuGet restore, publishes once and ships only the runtime.
  • Choose between the .NET base image families: Ubuntu (default), chiseled, chiseled-extra, Alpine and runtime-deps for Native AOT. Explain what each removes and what that breaks.
  • Run containers as a non-root user with a read-only root file system and no Linux capabilities, and know what .NET needs to keep working.
  • Build arm64 (Graviton) images on an x64 laptop without slow emulation.
  • Use dotnet publish -t:PublishContainer to build images without a Dockerfile, and know when a Dockerfile is still the better choice.
  • Measure image size, startup time and memory, and use the numbers in hosting decisions.

Prerequisites

Why this matters in banking

Harbourline's first container images were built from the full .NET SDK image "because it worked". Each image was over 1 GB, contained compilers, curl, a shell and a package manager, and ran as root. The first container vulnerability report listed 140 findings, most in packages the app never used. Every finding needed a triage decision, so the security team spent weeks on noise.

Then a penetration tester found a server-side request forgery bug in a reporting endpoint. Because the container had a shell and curl and ran as root, the tester could explore the file system and reach internal hosts. The bug was in the code, but the image decided how much damage it could do.

Small, minimal, non-root images reduce three things a bank cares about: attack surface (fewer tools for an attacker), vulnerability noise (fewer packages to patch and explain) and cost and speed (smaller images pull and start faster, which matters for scaling and recovery).

The idea in plain language

A container image is a packaged file system plus a little metadata: which user to run as, which command to start, which port it listens on. It is built in layers. Each instruction in a Dockerfile adds a layer, and layers are cached and shared.

A multi-stage build uses one big image to build your app (the .NET SDK, with compilers) and a different small image to run it (just the ASP.NET Core runtime). Only the final stage ships.

Chiseled images are Ubuntu images that Canonical and Microsoft "chiselled" down to the files .NET needs. There is no shell, no package manager and no root default user. They are the container equivalent of a locked-down server build.

Analogy: building an image is like preparing a branch for opening. The builders (SDK stage) arrive with cranes, saws and scaffolding. When the branch opens (final stage), only the counters, safes and staff remain. Nobody leaves a crane in the lobby. A chiseled image goes further: the branch has no spare keys cut on site (no package manager) and no back-office terminal anyone could wander up to (no shell).

What problem it solves

ProblemContainer answer
"Works on my machine"The same image runs on your laptop, in CI, on Fargate and on EKS
Slow, unrepeatable server buildsAn immutable image built once and promoted through environments
Large attack surfaceMinimal runtime images: chiseled, non-root, no shell
Patch drift across serversRebuild on a patched base image and redeploy everything the same way
Scaling speedSmall images pull faster, and .NET starts in about a second

Limitations and sharp edges:

  • No shell means no docker exec ... sh for debugging. You debug with logs, metrics, dotnet-monitor sidecars, or by running the same app on a non-chiseled image locally.
  • Chiseled images have no ICU (culture data) and no tzdata (time zones). They set DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=true, so culture-specific formatting and named time zones such as Europe/London do not work. Use the -extra variant if you need them.
  • Read-only root file systems break code that writes beside the app or into the user profile (for example ASP.NET Core Data Protection's default key storage).
  • Native AOT gives the smallest and fastest images but restricts reflection-heavy libraries. Not every NuGet package works with it.

The .NET 10 image families, measured

We pulled each image on Docker Desktop (with the containerd image store) and read docker image ls on 2026-11-18. These are on-disk sizes; compressed pull sizes are smaller. Compare them relative to each other.

Image (mcr.microsoft.com/dotnet/...)Size on diskShell / package managerICU + tzdataDefault userUse it for
sdk:10.01.31 GBYesYesrootBuild stage only
aspnet:10.0 (Ubuntu 24.04 "noble")342 MBYesYesroot (non-root app user available)Local debugging, apps that need OS tools
aspnet:10.0-noble-chiseled-extra239 MBNoYesapp (UID 1654)APIs that format by culture or convert time zones
aspnet:10.0-noble-chiseled182 MBNoNo (invariant mode)app (UID 1654)Harbourline default for APIs
aspnet:10.0-alpine178 MBYes (apk)No by defaultroot (non-root app available)When you need a shell but small size; musl libc differences
runtime-deps:10.0-noble-chiseled20.4 MBNoNoappNative AOT or self-contained apps

Our Accounts API image built on the chiseled base was 192 MB on disk, so the app adds about 10 MB. Two other facts we confirmed by inspecting the chiseled image: it sets APP_UID=1654, ASPNETCORE_HTTP_PORTS=8080 and DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=true, and its configured user is 1654.

Since .NET 10, the default tags (such as 10.0) are Ubuntu 24.04 (noble). Microsoft no longer ships Debian images for .NET 10. Ubuntu 26.04 images are also published with resolute tags ⚠ VERIFY before switching, and your scanner's support for the newer OS.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Visual Studio "Add Docker support" DockerfileThe same multi-stage DockerfileUse chiseled runtime images and set the platform explicitly for arm64 Fargate
dotnet publish -t:PublishContainer to ACRThe same command, pushing to ECRLog in with aws ecr get-login-password; ECR repositories must exist first
Azure Container Apps / App Service for Containers runtimeECS on Fargate, ECS Express Mode, EKSFargate supports readonlyRootFilesystem and non-root users in the task definition
Windows containers (nanoserver, servercore)Supported on ECS (EC2 and Fargate)Larger, slower and pricier; use Linux containers for .NET 8/10
Azure Linux (Mariner) distroless .NET imagesUbuntu chiseled images (also available: Azure Linux distroless)Both are distroless-style; chiseled is the common choice on AWS
ACR Tasks for cloud buildsGitHub Actions or AWS CodeBuild, pushing to ECRBuild once, push once, promote by digest

Architecture

Security-boundary view inside the running container:

  • Process: dotnet as UID 1654, not root. All Linux capabilities dropped. no-new-privileges set.
  • File system: read-only root. Only /tmp (an in-memory tmpfs locally, or an ephemeral volume on Fargate) is writable.
  • Network: listens on 8080 only (no privileged ports below 1024 needed, which is why non-root works).
  • Secrets: none in the image or its layers. They are injected at run time from Secrets Manager or Parameter Store (later in this module).

Step-by-step implementation

Read the lab's Dockerfile

Open labs/m03-accounts-api/Dockerfile and .dockerignore. The complete code section explains them line by line.

Build for your machine and run it hardened

cd labs/m03-accounts-api
docker build -t hl-m03-accounts-api:local .
docker run --rm -d --name accounts \
  --read-only --tmpfs /tmp --cap-drop ALL --security-opt no-new-privileges \
  -e ASPNETCORE_ENVIRONMENT=Development -p 8080:8080 hl-m03-accounts-api:local
curl http://localhost:8080/health/ready
curl http://localhost:8080/v1/accounts/ACC-0000000001

We measured this on a Windows laptop with Docker Desktop: the container answered /health/live about 1.3 seconds after docker run (including Docker's own start-up), and used about 34 MiB of memory when idle. The logs show two Data Protection warnings about an ephemeral key repository. That is expected for a read-only container, and discussed below.

Prove there is no shell and no root

docker exec accounts sh
# OCI runtime exec failed: exec failed: ... exec: "sh": executable file not found in $PATH
docker image inspect hl-m03-accounts-api:local --format '{{.Config.User}}'
# 1654
docker stop accounts

Build for arm64 (Graviton) from an x64 laptop

docker buildx build --platform linux/arm64 -t hl-m03-accounts-api:arm64 --load .

The Dockerfile's build stage runs on your architecture (--platform=$BUILDPLATFORM) and asks the SDK to publish for the target architecture (-a $TARGETARCH). Only the final stage is arm64, so no slow CPU emulation is needed for the .NET build. You cannot run the arm64 image on an x64 machine without emulation, but Fargate arm64 tasks run it natively.

Try SDK container publishing (no Dockerfile)

dotnet publish src/Harbourline.Accounts.Api -c Release -t:PublishContainer \
  -p ContainerFamily=noble-chiseled \
  -p ContainerRepository=hl-m03-accounts-api \
  -p ContainerImageTag=sdk-built \
  --os linux --arch x64
docker image ls hl-m03-accounts-api

The SDK picks mcr.microsoft.com/dotnet/aspnet:10.0-noble-chiseled (ASP.NET Core project + net10.0 + the family), runs as the non-root app user, and loads the image into your local Docker. Add -p ContainerRegistry=<account>.dkr.ecr.us-east-1.amazonaws.com to push straight to ECR after docker login.

Run it with Docker Compose

Use the compose file in the complete code section to run the API with the same hardening flags every time, so nobody forgets --read-only on the command line.

AWS Console instructions

There is nothing to create in AWS for this lesson. Two console views show how these image settings map to ECS:

  • Console → ECS → Task definitions → Create new task definition → Container details. Under Docker configuration, see Read-only root file system, User and Linux parameters (capabilities). Under Task size, see Operating system/Architecture (Linux/ARM64 for Graviton).
  • Console → ECR → Repositories → (repository) → Images. After the next lesson's push, the Image type and Vulnerabilities columns show what you built and what the scanner found.

AWS CLI

# Which architecture is your local image? It must match the Fargate task's cpuArchitecture.
docker image inspect hl-m03-accounts-api:arm64 --format '{{.Os}}/{{.Architecture}}'

# Register a hardened task definition (excerpt; the Fargate lesson registers the full one).
cat > taskdef-hardening.json <<'EOF'
{
  "family": "hl-m03-accounts-api",
  "requiresCompatibilities": ["FARGATE"],
  "networkMode": "awsvpc",
  "cpu": "256",
  "memory": "512",
  "runtimePlatform": { "cpuArchitecture": "ARM64", "operatingSystemFamily": "LINUX" },
  "volumes": [ { "name": "tmp" } ],
  "containerDefinitions": [
    {
      "name": "api",
      "image": "<account>.dkr.ecr.us-east-1.amazonaws.com/hl-m03-accounts-api:v1.0.0",
      "essential": true,
      "user": "1654",
      "readonlyRootFilesystem": true,
      "linuxParameters": { "capabilities": { "drop": ["ALL"] }, "initProcessEnabled": true },
      "mountPoints": [ { "sourceVolume": "tmp", "containerPath": "/tmp", "readOnly": false } ],
      "portMappings": [ { "containerPort": 8080, "protocol": "tcp" } ],
      "stopTimeout": 30
    }
  ]
}
EOF
# Validate the JSON locally before using it in the Fargate lesson.
python -m json.tool taskdef-hardening.json > /dev/null && echo "valid JSON"

On Fargate, a task-level volume with no host path (as tmp above) is backed by the task's ephemeral storage. Fargate does not support tmpfs mounts in linuxParameters ⚠ VERIFY, which is why the writable /tmp comes from a volume instead.

Infrastructure as Code

The same hardening in CDK and Terraform task definitions. The Fargate lesson wires them into a service.

HardenedTaskDefinition.cs (excerpt inside a Stack)
var taskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps
{
    Cpu = 256,
    MemoryLimitMiB = 512,
    RuntimePlatform = new RuntimePlatform
    {
        CpuArchitecture = CpuArchitecture.ARM64,
        OperatingSystemFamily = OperatingSystemFamily.LINUX,
    },
});
taskDefinition.AddVolume(new Amazon.CDK.AWS.ECS.Volume { Name = "tmp" }); // ephemeral, task-scoped

var container = taskDefinition.AddContainer("api", new ContainerDefinitionOptions
{
    Image = ContainerImage.FromEcrRepository(repository, "v1.0.0"),
    User = "1654",
    ReadonlyRootFilesystem = true,
    PortMappings = [new PortMapping { ContainerPort = 8080 }],
    StopTimeout = Duration.Seconds(30),
    Logging = LogDrivers.AwsLogs(new AwsLogDriverProps { StreamPrefix = "api" }),
});
container.AddMountPoints(new MountPoint { SourceVolume = "tmp", ContainerPath = "/tmp", ReadOnly = false });

Complete code

labs/m03-accounts-api/Dockerfile
# syntax=docker/dockerfile:1
# Multi-stage build for Harbourline.Accounts.Api
#   build stage : full .NET SDK (large, has compilers)  — never shipped
#   final stage : Ubuntu "chiseled" ASP.NET runtime   — no shell, no package manager, non-root
#
# Cross-compiles: the SDK stage runs on your machine's architecture ($BUILDPLATFORM) and publishes for
# the target architecture ($TARGETARCH), so `docker buildx build --platform linux/arm64` on an x64 laptop
# does not need slow QEMU emulation for the .NET build.

FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:10.0 AS build
ARG TARGETARCH
WORKDIR /source

# 1) Restore first, using only the project files, so this layer is cached until dependencies change.
COPY global.json Directory.Build.props ./
COPY src/Harbourline.Accounts.Api/Harbourline.Accounts.Api.csproj src/Harbourline.Accounts.Api/
RUN dotnet restore src/Harbourline.Accounts.Api/Harbourline.Accounts.Api.csproj -a $TARGETARCH

# 2) Then copy the source and publish (framework-dependent; the runtime is in the final image).
COPY src/ src/
RUN dotnet publish src/Harbourline.Accounts.Api/Harbourline.Accounts.Api.csproj \
    -c Release -a $TARGETARCH --no-restore -o /app /p:UseAppHost=false

# ---------------------------------------------------------------------------------------------------
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble-chiseled AS final
WORKDIR /app
COPY --from=build /app .

# The chiseled images already default to the non-root "app" user (UID 1654); stating it makes the
# intent visible to reviewers and scanners.
USER $APP_UID
ENV ASPNETCORE_HTTP_PORTS=8080 \
    DOTNET_gcServer=0
EXPOSE 8080

# No HEALTHCHECK: chiseled images have no shell or curl. The ALB (and ECS) probe /health/ready instead.
ENTRYPOINT ["dotnet", "Harbourline.Accounts.Api.dll"]
labs/m03-accounts-api/.dockerignore
# Keep the build context small and never send secrets or build output to the Docker daemon.
**/bin/
**/obj/
**/TestResults/
tests/
infra/
seed/
publish/
*.zip
.git/
.vs/
.idea/
.aws/
.env
*.pem
compose.yaml
# Local run with the same hardening as production. Start: docker compose up --build
services:
  accounts-api:
    build:
      context: ./labs/m03-accounts-api
    image: hl-m03-accounts-api:local
    ports:
      - "8080:8080"
    environment:
      ASPNETCORE_ENVIRONMENT: Development   # in-memory repository, auth disabled (Development only)
    read_only: true                         # root file system is read-only
    tmpfs:
      - /tmp                                # the only writable path
    cap_drop:
      - ALL                                 # no Linux capabilities; port 8080 does not need any
    security_opt:
      - no-new-privileges:true
    mem_limit: 512m                         # match the Fargate task size, so you see the same limits
    cpus: 0.5

Code explained line by line

Dockerfile, build stage

  1. # syntax=docker/dockerfile:1 opts into the current Dockerfile syntax through BuildKit.
  2. FROM --platform=$BUILDPLATFORM ... sdk:10.0 AS build runs the SDK on the machine doing the build, for example an x64 laptop or CI runner, even when the target is arm64. $BUILDPLATFORM and $TARGETARCH are supplied automatically by BuildKit.
  3. ARG TARGETARCH brings the target architecture (amd64 or arm64) into this stage. .NET accepts both spellings in -a.
  4. COPY global.json Directory.Build.props ./ and the .csproj only, then dotnet restore. This layer is rebuilt only when dependencies change, so most builds skip the NuGet download. This is the single biggest build-time win.
  5. -a $TARGETARCH on restore and publish makes NuGet pick the right runtime assets for the target.
  6. COPY src/ src/ brings in the code after restore. Changing a .cs file invalidates only this layer and the next.
  7. dotnet publish -c Release ... --no-restore -o /app /p:UseAppHost=false produces a framework-dependent app (the runtime comes from the base image). UseAppHost=false skips the native launcher, because the entry point uses dotnet app.dll.

Dockerfile, final stage

  1. FROM ... aspnet:10.0-noble-chiseled AS final starts clean from the small runtime image. Nothing from the SDK image comes along except what you copy.
  2. COPY --from=build /app . copies only the published output.
  3. USER $APP_UID runs as UID 1654. The chiseled image already defaults to it, and stating it makes the intent obvious to reviewers and to scanners that flag "no USER instruction".
  4. ASPNETCORE_HTTP_PORTS=8080 is already the image default, restated for clarity. A non-root user cannot bind ports below 1024, which is why .NET 8 and later default to 8080.
  5. DOTNET_gcServer=0 selects workstation garbage collection. Server GC creates a heap per CPU core and reserves more memory. Workstation GC suits small Fargate tasks (0.25–1 vCPU) with tight memory limits. For large tasks with many cores and high throughput, measure both.
  6. No HEALTHCHECK. A Docker HEALTHCHECK would need curl or a shell, which do not exist. The ALB and ECS health checks call /health/ready from outside instead.
  7. ENTRYPOINT ["dotnet", "Harbourline.Accounts.Api.dll"] uses the exec form, so dotnet is PID 1 (or a child of the init process) and receives SIGTERM directly for graceful shutdown.

.dockerignore

  1. **/bin/, **/obj/ keep local build output out of the context, which avoids "works locally, different in the image" bugs.
  2. .aws/, .env, *.pem stop credentials and keys from ever reaching the build context, and therefore an image layer. A secret copied into any layer stays in the image history even if a later layer deletes it.

compose.yaml

  1. read_only: true + tmpfs: /tmp mirror readonlyRootFilesystem plus a writable /tmp in the task definition.
  2. cap_drop: ALL and no-new-privileges remove the remaining kernel privileges a root-less process could gain.
  3. mem_limit / cpus reproduce the Fargate task size, so memory problems appear on your laptop first.

What breaks in a minimal, read-only container, and the fix

SymptomCauseFix
Logs warn "Using an ephemeral key repository" (we saw this in our run)ASP.NET Core Data Protection cannot persist keys in a read-only containerFine for a stateless JWT API. If you use cookies or anti-forgery tokens across tasks, persist keys centrally (for example Parameter Store or S3 with KMS)
TimeZoneNotFoundException: Europe/LondonNo tzdata in chiseled imagesUse -chiseled-extra, or keep everything in UTC and convert at the edge
CultureNotFoundException or amounts formatted without £Invariant globalisation modeUse -chiseled-extra and set InvariantGlobalization to false, or format currency explicitly from ISO codes
UnauthorizedAccessException writing a fileRead-only root, or not rootWrite to /tmp (temporary) or to S3 (durable). Never write beside the app
docker exec fails: no shNo shell, by designUse logs and metrics; reproduce on aspnet:10.0 locally; dotnet-monitor as a sidecar for dumps

For Harbourline's Accounts API, everything is UTC and amounts are serialised as numbers with an ISO currency code, so the plain chiseled image and InvariantGlobalization=true (set in Directory.Build.props) are correct. A statements service that renders "1 November 2026, 09:00 (London time)" in a PDF would need -chiseled-extra.

Smaller and faster: ReadyToRun and Native AOT

  • ReadyToRun (-p:PublishReadyToRun=true) precompiles your assemblies, so less JIT happens at startup. The image grows a little and startup improves. It is a safe default for latency-sensitive services; measure it.
  • Native AOT (<PublishAot>true</PublishAot>) compiles the whole app to a single native binary that runs on runtime-deps:10.0-noble-chiseled (20 MB). Startup drops to tens of milliseconds and memory falls sharply. The costs: no runtime code generation, so you need source-generated JSON, and some libraries are not AOT-compatible. It shines on Lambda, where cold starts matter most, and is optional for long-running Fargate tasks.

Security considerations

⚠ Learning shortcut — not for production

The compose file runs with ASPNETCORE_ENVIRONMENT=Development, which in the reference API means the in-memory repository and authentication disabled. The API refuses to start that way in any other environment unless an explicit learning-shortcut flag is set. Never ship an image or task definition with Development settings. Production images are identical; only the run-time configuration differs.

  • Pin and mirror base images. aspnet:10.0-noble-chiseled moves when Microsoft patches it, which is good, but your build should take base images from your mirror in ECR, refreshed by a pipeline that scans them first. For full reproducibility, pin by digest (@sha256:...) and let a bot (Renovate or Dependabot) raise updates.
  • Never put secrets in images. No ARG/ENV secrets, no copied .aws folders, no appsettings.Production.json with passwords. Build arguments are visible in image history.
  • Non-root, read-only, no capabilities in every task definition, not just in the Dockerfile. ECS's user, readonlyRootFilesystem and dropped capabilities make the rule enforceable at deploy time, and policy-as-code tools can check them.
  • Rebuild regularly. A chiseled image with no known vulnerabilities today will have some next month. Rebuild weekly on the latest mirrored base, even without code changes.
  • Generate an SBOM (software bill of materials) during the build, for example with docker buildx build --sbom=true or a CycloneDX tool, and store it with the image. When the next big CVE arrives, an SBOM tells you in minutes whether you are affected.
  • Image provenance. Sign images in the registry (next lesson) and only deploy images your pipeline built.

Banking use case

Harbourline's container standard (an internal engineering policy, fictional) says:

  1. Runtime base: aspnet:10.0-noble-chiseled from the internal ECR mirror, or -chiseled-extra with a recorded reason (time zones or cultures).
  2. Multi-stage builds only; the SDK image never ships.
  3. USER non-root, readonlyRootFilesystem: true, all capabilities dropped. Checked by a policy rule in the deployment pipeline.
  4. arm64 by default for Fargate (Graviton is cheaper per vCPU-hour), with x64 only where a dependency requires it.
  5. A weekly rebuild of every service. An SBOM attached to each image.
  6. Image size and cold-start time recorded per release. A jump of more than 20% needs an explanation in the pull request.

The result for the Accounts API: an image of about 190 MB on disk (well under 100 MB compressed), startup in about a second, and a first vulnerability report short enough for a human to read. Whether the standard meets a specific regulatory or PCI DSS requirement is for the security and compliance teams to confirm.

Common mistakes

  • Shipping the SDK image (a single-stage FROM sdk) → 1 GB+ images full of compilers → multi-stage builds.
  • COPY . . before dotnet restore → every code change re-downloads all packages → copy project files, restore, then copy source.
  • Building amd64 images for arm64 tasks (or the reverse) → exec format error at task start → set --platform and match runtimePlatform.cpuArchitecture.
  • Adding RUN apt-get install curl to a chiseled image for a health check → fails (no package manager) or defeats the point → let the ALB/ECS check /health/ready from outside.
  • Using TimeZoneInfo.FindSystemTimeZoneById("Europe/London") on plain chiseled → exception in production only → -chiseled-extra, or UTC everywhere.
  • Secrets in ENV or build args → visible in image history → inject at run time.
  • Using latest as the base tag → unpredictable rebuilds → use the 10.0 family tag from your mirror, or a digest.
  • Server GC in a 0.5 GB task → higher memory and possible out-of-memory kills → workstation GC (DOTNET_gcServer=0) for small tasks, or measure.

Troubleshooting

SymptomLikely causeFix
exec format errorImage architecture differs from the host or taskdocker image inspect --format '{{.Architecture}}'; rebuild with --platform
Build is slow on every changeRestore layer not cached (COPY . . first) or .dockerignore missing (huge context)Restore-first layering; add .dockerignore
Unable to bind to http://+:80 / permission deniedNon-root process trying a privileged portUse 8080 (ASPNETCORE_HTTP_PORTS)
Container exits immediately, no logsWrong ENTRYPOINT DLL name, or missing runtime for a self-contained buildCheck the DLL name in /app; run the same image with --entrypoint dotnet and --info
Couldn't find a valid ICU packageApp not in invariant mode on an image without ICUSet InvariantGlobalization=true, or use -chiseled-extra
OOMKilled on FargateMemory limit too low, or Server GC on a small taskRaise task memory; DOTNET_gcServer=0; check docker stats locally with the same limit
docker buildx arm64 build very slowThe build stage itself is emulated (no --platform=$BUILDPLATFORM)Keep the build stage on $BUILDPLATFORM and cross-publish with -a $TARGETARCH

Cost and cleanup

This lesson is free. Everything runs locally. Docker images use disk space, which you can reclaim:

docker compose down
docker image rm hl-m03-accounts-api:local hl-m03-accounts-api:arm64 hl-m03-accounts-api:sdk-built
docker builder prune --filter until=24h   # build cache older than a day

Running the same image on Fargate later costs per second for the task size you choose (about USD 0.01 per hour for 0.25 vCPU / 0.5 GB on arm64 in us-east-1). Smaller images also mean faster scale-out and lower ECR storage, which is USD 0.10 per GB-month.

Exercises

  • 🟢 Guided: Build the lab image, run it with the hardening flags, confirm there is no shell and the user is 1654, then record the image size, the time to first healthy response and idle memory in a table.
  • 🟡 Challenge: Build a second image using aspnet:10.0-noble-chiseled-extra, set InvariantGlobalization to false, and add a temporary endpoint that returns the current time in Europe/London and a balance formatted with en-GB culture. Prove it fails on the plain chiseled image and works on -extra. Compare the sizes.
  • 🔴 Live problem: The platform team reports that the Accounts API's Fargate tasks use 480 MB of their 512 MB limit and are occasionally killed during the 08:00 peak, while CPU is only at 30%. The developers say "it uses 34 MB locally". Investigate and propose fixes.

Assignment

Create a docs/container-standard.md in your portfolio repository: base image choice and mirroring, multi-stage template, non-root and read-only rules, GC settings, architecture policy, rebuild cadence, SBOM, and a measured table (size, startup, memory) for your API on chiseled, chiseled-extra and the default Ubuntu image. Include your compose.yaml.

Solutions

Knowledge check

Interview questions

  • "How do you build a production container image for .NET?" — Multi-stage Dockerfile with restore-first layering, a chiseled ASP.NET runtime base from an internal mirror, non-root user, port 8080, no secrets, .dockerignore, SBOM generation, scan in the registry, rebuild weekly.
  • "What are chiseled images and what do they cost you?" — Ubuntu images stripped to what .NET needs: no shell, no package manager, non-root by default, so fewer CVEs and a smaller attack surface. Costs: harder interactive debugging, and no ICU or tzdata unless you use -extra.
  • "How do you debug a container with no shell?" — Structured logs and metrics first. dotnet-monitor as a sidecar for dumps and traces. Reproduce with the same app on a full image locally. ECS Exec needs a shell in the container, so it is not an option with chiseled images.
  • "Dockerfile or dotnet publish -t:PublishContainer?" — The SDK path is simpler, needs no Docker daemon to build, and picks secure defaults. A Dockerfile gives full control (custom base mirrors, multi-project builds, extra build steps, SBOM tooling) and is what most bank pipelines standardise on.

Certification practice

Completion checklist

  • I built the lab image and ran it read-only, non-root and with no capabilities
  • I measured size, startup time and memory, and can explain the numbers
  • I built an arm64 image on my machine
  • I know when to use chiseled, chiseled-extra and runtime-deps (AOT)
  • I tried SDK container publishing and can compare it with a Dockerfile
  • I removed local images and pruned the build cache

Key takeaways

  • Multi-stage builds with restore-first layering give small images and fast builds.
  • Chiseled runtime images are Harbourline's default: no shell, no package manager, non-root UID 1654, port 8080. Use -extra when you need time zones or cultures.
  • Enforce non-root, read-only root file system and dropped capabilities in the task definition, and give .NET a writable /tmp.
  • Build arm64 with --platform=$BUILDPLATFORM and -a $TARGETARCH, and match the Fargate task architecture.
  • Measure size, startup and memory, and rebuild regularly on mirrored, scanned base images.

Further reading

Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page