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.
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
- Containerising .NET and Health checks
- Docker Desktop running (Linux containers)
- The lab code in
labs/m03-accounts-api(read itsREADME.md)
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:
# 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 -5The 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/accountsInspect 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}}' | headStop and clean up
docker compose down
docker image rm hl-m03-accounts-api:localExpected 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 $PATHThe 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 / setting | Why |
|---|---|
FROM --platform=$BUILDPLATFORM ... sdk:10.0 AS build | The 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 $TARGETARCH | Restores and publishes for the requested architecture (amd64 or arm64) |
/p:UseAppHost=false | No native launcher executable; we start with dotnet <dll> |
aspnet:10.0-noble-chiseled | ASP.NET Core runtime on chiseled Ubuntu 24.04: no shell, no package manager, smaller CVE surface |
USER $APP_UID | The non-root app user (1654). Chiseled images already default to it; stating it documents intent and satisfies scanners |
ASPNETCORE_HTTP_PORTS=8080 | Non-root processes cannot bind ports below 1024; 8080 is the .NET image default |
DOTNET_gcServer=0 | Workstation 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 HEALTHCHECK | No shell or curl in the image; the ALB and ECS probe /health/ready from outside |
.dockerignore | Keeps bin/, obj/, tests/, infra/, .aws/, .env and keys out of the build context |
compose read_only, tmpfs /tmp | Matches ECS readonlyRootFilesystem; any unexpected write fails loudly |
compose cap_drop: ALL, no-new-privileges | The 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.envfiles and~/.awsfolders end up in images.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Set HL_PSEUDO_KEY first | The variable is not set in this shell | Export it (step 2) |
Container exits: Configure Pseudonymisation:Key ... | Key empty | Same as above |
Container exits: Auth:Mode=Disabled is only allowed in Development | Override variable missing | Keep Auth__AllowDisabledOutsideDevelopment in compose (lab only) |
bind: address already in use on 8080 | Another process uses the port | Change the mapping to "8081:8080" |
exec format error when running | Image built for a different architecture than your machine | Build without --platform, or for your own architecture |
| Build very slow every time | Build context includes bin/obj, or restore layer invalidated | Check .dockerignore; keep the csproj-first copy order |
| Culture-related exceptions | Code using a specific culture with invariant globalization | Use 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 anddocker compose exec api sh -c idbehaviour. - ๐ก Challenge: Add a
--platform linux/arm64build withdocker buildx buildand confirm the image architecture withdocker image inspect --format '{{.Architecture}}'. Explain why$BUILDPLATFORMkeeps 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
The Debian-based runtime is noticeably larger (it includes a shell, apt and more libraries) and sh -c id works, printing uid=1654(app) only if you also keep USER $APP_UID (the full image's default user is also app in .NET 8+ images, but stating it matters). The point: the chiseled image removes tools an attacker would use after a compromise and has fewer packages to patch.
docker buildx build --platform linux/arm64 -t hl-m03-accounts-api:arm64 --load . then docker image inspect --format '{{.Architecture}}' hl-m03-accounts-api:arm64 prints arm64. Because the build stage uses $BUILDPLATFORM, the SDK runs natively (amd64 on most laptops) and cross-publishes for arm64 with -a $TARGETARCH; only the tiny final stage is arm64. Without it, Docker would emulate the whole .NET build under QEMU, many times slower. Running the arm64 image locally on an x64 machine needs emulation, so test it on ARM or in Fargate.
Exit code 139 is a segmentation fault; on ARM tasks only, the usual cause is an image built for amd64 running on an arm64 task (or a native dependency for the wrong architecture). Check the image manifest's architecture in ECR (docker buildx imagetools inspect <uri>) against the task definition's runtimePlatform.cpuArchitecture. Fix by building with --platform linux/arm64 (or a multi-arch manifest). Also check stopTimeout/logs configuration if the crash happens before logging starts.
Knowledge check
Answer: Docker caches each layer. Restoring from the project file alone means the slow restore layer is reused until dependencies change; code edits only rebuild the later layers.
Answer: The chiseled image has no shell or HTTP client to run one. Health is probed from outside by the ALB (and ECS through the target group), using /health/ready.
Answer: It runs as a non-root user, which cannot bind ports below 1024 by default. The load balancer maps public 80/443 to 8080.
Certification practice
A team must reduce vulnerabilities reported for its .NET container images and prevent attackers from using tools inside a compromised container. Which change helps MOST?
A. Install the latest curl and bash in the runtime image for diagnostics.
B. Use a multi-stage build with a minimal (chiseled) ASP.NET runtime base image running as a non-root user.
C. Build the app inside the runtime image.
D. Use the SDK image as the runtime image so all tools are patched together.
Answer: B. Fewer packages mean fewer CVEs and no shell or tools to abuse; non-root limits damage. A and D add attack surface. C ships compilers and source.
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/ready200, 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.
Health checks that help instead of hurt
Design liveness and readiness endpoints in ASP.NET Core, wire them correctly to ALB target groups, ECS container health checks and Elastic Beanstalk, tune timings and grace periods, shut down gracefully, and avoid the restart loop that turns a database blip into a full outage.
Lab 3.3: push to ECR and deploy to Fargate behind an ALB
Create a private ECR repository with immutable tags and scan on push, push an arm64 image of the Accounts API, deploy it with CDK to ECS on Fargate in private subnets behind an Application Load Balancer, test it, then destroy everything within the hour.