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

Lab 3.2: containerise the Accounts API with a chiseled, non-root image

Build the module project's ASP.NET Core API into a multi-stage, chiseled, non-root container image, run it locally with docker compose under production-like restrictions, and check its size, user and start-up time.

beginnerโฑ 1 h ๐ŸŸข FreeDVA-C03

Assumes: .NET 10 LTS ยท mcr.microsoft.com/dotnet/aspnet:10.0-noble-chiseled ยท Docker Desktop with Compose v2 ยท labs/m03-accounts-api. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lab you can:

  • Read and explain each line of a multi-stage Dockerfile for ASP.NET Core.
  • Build an image on the Ubuntu chiseled ASP.NET runtime base: no shell, no package manager, non-root user 1654.
  • Run the container with docker compose the way ECS runs it: production settings, read-only root file system, no Linux capabilities, CPU and memory limits.
  • Prove the result: image size, user, start-up time, health endpoints and ProblemDetails responses.

Prerequisites

Why this matters in banking

A container image is what you ship to production. Everything in it is attack surface and patching work: a shell an attacker can use, a package manager that installs tools, a root user that can write anywhere. Harbourline's container standard requires minimal base images, non-root users, read-only file systems and image scanning (Lab 3.3). Running the image locally under the same restrictions catches problems on your laptop instead of in a failed deployment.

The idea in plain language

A multi-stage build uses a big image with the .NET SDK to compile the app, then copies only the compiled output into a small runtime image. The SDK, source code and build tools never reach production.

A chiseled image is Ubuntu cut down to only the files .NET needs to run: no bash, no apt, no curl. It defaults to a non-root user (app, UID 1654).

Analogy: a bank vault delivery. The workshop (build stage) has every tool; only the finished, sealed box (runtime image) goes to the branch, and it arrives without a crowbar inside.

Architecture

Step-by-step

Read the Dockerfile

Open labs/m03-accounts-api/Dockerfile:

Dockerfile
# syntax=docker/dockerfile:1
FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:10.0 AS build
ARG TARGETARCH
WORKDIR /source

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

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 .
USER $APP_UID
ENV ASPNETCORE_HTTP_PORTS=8080 \
    DOTNET_gcServer=0
EXPOSE 8080
ENTRYPOINT ["dotnet", "Harbourline.Accounts.Api.dll"]

Set the pseudonymisation key in your shell

The API refuses to start outside Development without a key (fail fast). The key never goes into a file:

# Git Bash
export HL_PSEUDO_KEY=$(openssl rand -hex 32)
# PowerShell
$env:HL_PSEUDO_KEY = [guid]::NewGuid().ToString("N")

Build and start with compose

From labs/m03-accounts-api:

docker compose up --build -d
docker compose logs --no-color | head -5

The compose.yaml in the lab sets ASPNETCORE_ENVIRONMENT=Production, the in-memory repository, read_only: true, a tmpfs for /tmp, cap_drop: [ALL], no-new-privileges, 512 MB and 0.25 CPU (the Fargate task size).

Call it

curl -i http://localhost:8080/health/ready
curl -i http://localhost:8080/v1/accounts/ACC-0000000001
curl -i http://localhost:8080/v1/accounts/bad
curl -i -H "X-Correlation-ID: lab32-test-0001" http://localhost:8080/v1/customers/CUS-00012345/accounts

Inspect the image

docker image ls hl-m03-accounts-api:local
docker inspect --format '{{.Config.User}}' hl-m03-accounts-api:local
docker compose exec api id          # fails: there is no shell or 'id' binary
docker history hl-m03-accounts-api:local --format '{{.Size}}\t{{.CreatedBy}}' | head

Stop and clean up

docker compose down
docker image rm hl-m03-accounts-api:local

Expected output

Verified when this lab was written (timestamps and IDs will differ):

HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store, no-cache
X-Correlation-ID: 01a1ebb4-bb30-796b-b29b-d7d1cdc2a30c

{"status":"Healthy","checks":{"repository":"Healthy"},"durationMs":0.4}
{"accountId":"ACC-0000000001","customerId":"CUS-00012345","iban":"GB96HLBK30991200000001","currency":"GBP","product":"current","status":"open","balance":-75.37,"openedAt":"2023-11-01T09:00:00+00:00"}
{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"Invalid account id","status":400,"detail":"Account ids look like ACC-0000000001.","instance":"GET /v1/accounts/bad","traceId":"00-a89065c8e76b74da1c600dfbe0fc59b8-efc672f903bd8d04-00","correlationId":"01a1ebb4-bbe1-74c7-95e1-40a1139cc049"}
IMAGE                       DISK USAGE   CONTENT SIZE
hl-m03-accounts-api:local        192MB         59.2MB
1654
OCI runtime exec failed: exec failed: unable to start container process: exec: "id": executable file not found in $PATH

The logs show the app starting in well under a second ("Now listening on: http://[::]:8080" about 0.7 s after the first line), plus three Data Protection warnings explained below.

What each choice does

Line / settingWhy
FROM --platform=$BUILDPLATFORM ... sdk:10.0 AS buildThe SDK stage runs natively on your machine even when you build for linux/arm64 (Graviton, Lab 3.3); only the output is for the target architecture
COPY *.csproj then restore, then COPY src/Layer caching: package restore is redone only when project files change, not on every code edit
-a $TARGETARCHRestores and publishes for the requested architecture (amd64 or arm64)
/p:UseAppHost=falseNo native launcher executable; we start with dotnet <dll>
aspnet:10.0-noble-chiseledASP.NET Core runtime on chiseled Ubuntu 24.04: no shell, no package manager, smaller CVE surface
USER $APP_UIDThe non-root app user (1654). Chiseled images already default to it; stating it documents intent and satisfies scanners
ASPNETCORE_HTTP_PORTS=8080Non-root processes cannot bind ports below 1024; 8080 is the .NET image default
DOTNET_gcServer=0Workstation GC: lower memory use for a 0.25 vCPU / 512 MB task
InvariantGlobalization=true (in Directory.Build.props)Chiseled images have no ICU; the API formats only invariant data
No HEALTHCHECKNo shell or curl in the image; the ALB and ECS probe /health/ready from outside
.dockerignoreKeeps bin/, obj/, tests/, infra/, .aws/, .env and keys out of the build context
compose read_only, tmpfs /tmpMatches ECS readonlyRootFilesystem; any unexpected write fails loudly
compose cap_drop: ALL, no-new-privilegesThe process cannot gain extra kernel capabilities or escalate via setuid binaries

The Data Protection warnings. With a read-only file system, ASP.NET Core cannot store its Data Protection keys and falls back to an in-memory key ring ("Using an ephemeral key repository"). The Accounts API is a bearer-token API with no cookies, so this is harmless. A cookie-based app must persist keys to a shared store (Scaling .NET apps).

Security considerations

โš  Learning shortcut โ€” not for production

The compose file disables authentication with an explicit override and uses a key generated in your shell. In ECS the key comes from Parameter Store SecureString (Lab 3.5) and authentication uses Cognito (lesson 15). The image tag local is mutable; in ECR you push immutable, versioned tags and scan them (Lab 3.3).

  • Rebuild regularly. Base images receive security patches; a pipeline should rebuild and redeploy at least weekly, not only when code changes.
  • Pin by digest for releases. For audited releases, reference the base image by digest (@sha256:...) and update it deliberately.
  • Never COPY . . without a .dockerignore. It is how .env files and ~/.aws folders end up in images.

Troubleshooting

SymptomLikely causeFix
Set HL_PSEUDO_KEY firstThe variable is not set in this shellExport it (step 2)
Container exits: Configure Pseudonymisation:Key ...Key emptySame as above
Container exits: Auth:Mode=Disabled is only allowed in DevelopmentOverride variable missingKeep Auth__AllowDisabledOutsideDevelopment in compose (lab only)
bind: address already in use on 8080Another process uses the portChange the mapping to "8081:8080"
exec format error when runningImage built for a different architecture than your machineBuild without --platform, or for your own architecture
Build very slow every timeBuild context includes bin/obj, or restore layer invalidatedCheck .dockerignore; keep the csproj-first copy order
Culture-related exceptionsCode using a specific culture with invariant globalizationUse CultureInfo.InvariantCulture, or switch to the non-chiseled -extra image with ICU

Cost and cleanup

Free: everything runs on your machine. Clean up with docker compose down and docker image rm hl-m03-accounts-api:local. Optionally reclaim build cache with docker builder prune (it removes cache for all projects).

Exercises

  • ๐ŸŸข Guided: Change the final stage to mcr.microsoft.com/dotnet/aspnet:10.0 (full Debian), rebuild with a different tag, and compare size and docker compose exec api sh -c id behaviour.
  • ๐ŸŸก Challenge: Add a --platform linux/arm64 build with docker buildx build and confirm the image architecture with docker image inspect --format '{{.Architecture}}'. Explain why $BUILDPLATFORM keeps it fast.
  • ๐Ÿ”ด Live problem: A colleague's image runs locally but ECS stops the task with Exited (139) and no logs, only on Fargate ARM tasks. What do you check first?

Solutions

Knowledge check

Certification practice

Completion checklist

  • I can explain every line of the Dockerfile
  • The container ran under compose with read-only FS and dropped capabilities
  • I saw /health/ready 200, an account JSON and a 400 ProblemDetails with a correlation ID
  • I confirmed the image user is 1654 and there is no shell
  • I removed the containers and image

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