Amazon ECR: storing .NET images safely
Use Amazon Elastic Container Registry the way a bank should: private repositories, immutable tags, scan on push and enhanced scanning, lifecycle and archive policies, KMS encryption, cross-account access, private networking, and a C# release gate that blocks images with critical vulnerabilities.
Assumes: .NET 10 LTS · AWS SDK for .NET v4 (AWSSDK.ECR 4.1.2) · AWS CLI v2 · Docker · Amazon.CDK.Lib 2.277.0 · Terraform AWS provider v6 · Region us-east-1. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this lesson you can:
- Explain ECR's building blocks — registry, repository, image, tag, digest — and how Docker authenticates to ECR with short-lived tokens.
- Create a private repository with immutable tags, scan on push and an appropriate encryption setting, using the console, the CLI, CDK and Terraform.
- Choose between basic scanning and enhanced scanning (Amazon Inspector), and read findings from the CLI and from C#.
- Write and preview lifecycle policies that expire untagged images, keep the last N releases and archive old ones.
- Grant cross-account pull access from a production account, and pull images from private subnets through VPC endpoints.
- Build a C# release gate that waits for the scan and fails a pipeline when an image has critical or too many high findings.
Prerequisites
- Containerising .NET — you have a chiseled, non-root image of the Accounts API
- IAM fundamentals — identity and resource policies
- Tools: Docker Desktop, AWS CLI v2 with
learn-sandbox, .NET 10 SDK or Docker
Why this matters in banking
During a supplier audit, Harbourline was asked a simple question: "Show us exactly which build of the Payments API was running in production on 3 March, and its known vulnerabilities on that day." The team could not answer. Their registry had one mutable tag, latest, that every build overwrote. The image that ran in March no longer existed.
A month later a different team's pipeline pushed v2.4.1 twice, first a broken build and then a fix. Half of the ECS tasks had pulled the broken one. Nobody could tell from the tag which was which.
A container registry is part of your software supply chain. For a bank it must answer: what exactly is running (digest), where it came from (pipeline, commit), whether it was checked (scan results), who can push and pull it (IAM), and how long you keep it (retention). Payment-card standards and most banks' internal policies expect vulnerability management for the software you deploy. ECR gives you the controls. Configuring them is your job.
The idea in plain language
Amazon ECR (Elastic Container Registry) is AWS's managed Docker registry, the same idea as Docker Hub or Azure Container Registry. You push images to it and ECS, EKS, Lambda or EC2 pull them.
- Each AWS account has a private registry in each Region:
123456789012.dkr.ecr.us-east-1.amazonaws.com. - Inside it you create repositories, one per application:
hl-m03-accounts-api. - A repository holds images. Each image has a digest, a SHA-256 hash of its manifest that never changes, and zero or more tags (
v1.4.0,git-3f9c2ab), which are human-friendly labels. - With immutable tags, a tag can be assigned once and never moved to a different image.
- ECR can scan images for known vulnerabilities, expire old images automatically, encrypt them with KMS, replicate them to other Regions or accounts, and sign them.
Analogy: ECR is the bank's secure document archive. Each document (image) has a fingerprint (digest) that proves it has not changed. Labels on the folder (tags) help people find it. "Immutable tags" means a label, once stuck on, can never be peeled off and stuck on a different document. The archive inspects every incoming document for known problems (scanning), shreds drafts after a retention period (lifecycle policies), and only lets named departments in (IAM and repository policies).
What problem ECR solves
- Durable, private image storage close to your compute, with no registry servers to run.
- IAM-based access. Push and pull are IAM actions, so task roles, pipeline roles and SCPs control them. There are no separate registry passwords.
- Fast, free pulls in-Region. Data transfer from ECR to ECS, Fargate, EC2 and Lambda in the same Region is free.
- Security features: scan on push, enhanced scanning with Amazon Inspector, KMS encryption, immutable tags, managed signing with AWS Signer, and CloudTrail logging of every push, pull and delete.
Limitations and sharp edges:
- Scanning finds known CVEs in OS packages (basic) or OS and language packages (enhanced). It does not find your bugs. Pair it with code scanning (Pipeline security scanning).
- Basic scanning runs at most once per image every 24 hours (scan on push counts) and does not rescan automatically when new CVEs appear. Enhanced scanning rescans continuously but costs money.
- Encryption type is fixed at repository creation. To change from AES-256 to KMS, create a new repository.
- Pull through cache does not support Microsoft Container Registry (
mcr.microsoft.com), where the .NET base images live. Mirror them yourself (see Security considerations). - Lifecycle policies act within 24 hours, not instantly, and they can delete an image that a running task still uses. A replacement task would then fail to start.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Azure Container Registry (ACR) | Amazon ECR private registry | No SKUs (Basic/Standard/Premium). One registry per account per Region; pay per GB stored |
| ACR repositories and tags | ECR repositories and tags | Tag immutability is a repository setting, with optional wildcard exclusions |
az acr login | aws ecr get-login-password | docker login --username AWS --password-stdin | Token valid for 12 hours, derived from your IAM credentials |
| Microsoft Defender for Containers scanning | ECR basic scanning, or enhanced scanning with Amazon Inspector | Basic is free and on push; Inspector rescans continuously and covers language packages such as NuGet |
ACR retention policy / acr purge | ECR lifecycle policies (expire or archive) | JSON rules by tag status, tag pattern, count, age or last pull; preview before applying |
| ACR geo-replication (Premium) | ECR replication rules (cross-Region, cross-account) | Configured per registry with repository filters |
| ACR content trust / Notation | ECR managed signing with AWS Signer, or Notation with the Signer plugin | Managed signing signs automatically on push |
| ACR private endpoints | Interface VPC endpoints ecr.api and ecr.dkr, plus the S3 gateway endpoint | Image layers are served from S3, so you need the S3 endpoint too |
| ACR cache rules | ECR pull through cache | Upstreams include ECR Public, Docker Hub, Quay, GitHub, GitLab, ACR and others, but not MCR |
Architecture
Security-boundary view:
- Who can push: only the CI role from the build pipeline. Developers cannot push to the production repository from laptops.
- Who can pull: the ECS task execution role in the production account, allowed by the repository policy (resource side) and its IAM policy (identity side). Both sides are required for cross-account access.
- Network path: tasks in private subnets reach ECR through interface endpoints (
com.amazonaws.us-east-1.ecr.apiandcom.amazonaws.us-east-1.ecr.dkr) and fetch layers through the S3 gateway endpoint. No internet path is needed. - Evidence: CloudTrail records
PutImage,BatchGetImageandBatchDeleteImage. Scan results are queryable per digest. Lifecycle actions appear in CloudTrail.
Step-by-step implementation
Create the repository with secure settings
Immutable tags, scan on push, and AES-256 encryption for the lab (KMS for production), plus tags for cleanup. Use the CLI or IaC below.
Authenticate Docker to ECR
aws ecr get-login-password returns a token valid for 12 hours, which you pipe into docker login. Your SSO role's permissions decide what you may push or pull.
Tag and push the image you built in the previous lesson
Use two tags: the Git commit SHA (unique, traceable) and the semantic version (human-friendly). Push both. Note the digest that docker push prints.
Read the scan result and run the release gate
Wait for the scan to finish, list the findings by severity, then run the C# ScanGate to apply Harbourline's rule: no CRITICAL findings, at most a configured number of HIGH findings.
Add a lifecycle policy and preview it
Expire untagged images after 7 days and keep the 10 most recent images. Run a lifecycle preview before applying it so you can see what would be deleted.
Prove immutability
Rebuild with a small change and try to push it with the same version tag. ECR rejects it with ImageTagAlreadyExistsException. That rejection is the control working.
AWS Console instructions
- Console → Elastic Container Registry → Private registry → Repositories → Create repository.
- Repository name:
hl-m03-accounts-api. - Image tag mutability: Immutable. Leave Immutable tag exclusions empty.
- Encryption: AES-256 for this lab. Choose AWS KMS with a customer managed key for production. This cannot be changed later.
- Add tags
Project=cea-lab,Lab=m03-ecr,Environment=learn,Owner=<you>.
- Repository name:
- Private registry → Features & settings → Scanning. Choose Basic scanning and add a scan on push filter
hl-*(or Enhanced scanning with Amazon Inspector if your organisation has it on). Scanning is best configured at the registry level, not per repository. - Repositories → hl-m03-accounts-api → View push commands. The console shows the four commands (login, build, tag, push) for your account and Region.
- After pushing: Images → (your tag). Open Vulnerabilities to see findings by severity, with the package and fixed version for each.
- Repository → Lifecycle policy → Create rule. Add the two rules from the CLI section. Use Save and preview (test rules) before applying.
AWS CLI
REGION=us-east-1
ACCOUNT=$(aws sts get-caller-identity --query Account --output text --profile learn-sandbox)
REGISTRY=$ACCOUNT.dkr.ecr.$REGION.amazonaws.com
REPO=hl-m03-accounts-api
# 1. Create a private repository: immutable tags, scan on push, AES-256, tags for cleanup.
aws ecr create-repository --repository-name $REPO --region $REGION --profile learn-sandbox \
--image-tag-mutability IMMUTABLE \
--image-scanning-configuration scanOnPush=true \
--encryption-configuration encryptionType=AES256 \
--tags Key=Project,Value=cea-lab Key=Lab,Value=m03-ecr Key=Environment,Value=learn Key=Owner,Value=alex
# 2. Log Docker in (token valid 12 hours).
aws ecr get-login-password --region $REGION --profile learn-sandbox \
| docker login --username AWS --password-stdin $REGISTRY
# 3. Tag the local image twice (commit SHA + version) and push both tags.
GIT_SHA=$(git rev-parse --short=12 HEAD)
docker tag hl-m03-accounts-api:local $REGISTRY/$REPO:git-$GIT_SHA
docker tag hl-m03-accounts-api:local $REGISTRY/$REPO:v1.0.0
docker push $REGISTRY/$REPO:git-$GIT_SHA
docker push $REGISTRY/$REPO:v1.0.0
# 4. The digest is the immutable identity. Record it in the release notes.
aws ecr describe-images --repository-name $REPO --image-ids imageTag=v1.0.0 \
--query "imageDetails[0].{digest:imageDigest,tags:imageTags,sizeMB:to_string(imageSizeInBytes)}" \
--region $REGION --profile learn-sandbox
# 5. Wait for the scan and print the severity counts.
aws ecr wait image-scan-complete --repository-name $REPO --image-id imageTag=v1.0.0 --region $REGION --profile learn-sandbox
aws ecr describe-image-scan-findings --repository-name $REPO --image-id imageTag=v1.0.0 \
--query "imageScanFindings.findingSeverityCounts" --region $REGION --profile learn-sandbox
# 6. Lifecycle policy: preview first, then apply.
cat > lifecycle.json <<'EOF'
{
"rules": [
{
"rulePriority": 1,
"description": "Expire untagged images after 7 days",
"selection": { "tagStatus": "untagged", "countType": "sinceImagePushed", "countUnit": "days", "countNumber": 7 },
"action": { "type": "expire" }
},
{
"rulePriority": 2,
"description": "Keep the 10 most recent images",
"selection": { "tagStatus": "any", "countType": "imageCountMoreThan", "countNumber": 10 },
"action": { "type": "expire" }
}
]
}
EOF
aws ecr start-lifecycle-policy-preview --repository-name $REPO --lifecycle-policy-text file://lifecycle.json --region $REGION --profile learn-sandbox
aws ecr get-lifecycle-policy-preview --repository-name $REPO --region $REGION --profile learn-sandbox
aws ecr put-lifecycle-policy --repository-name $REPO --lifecycle-policy-text file://lifecycle.json --region $REGION --profile learn-sandbox
# 7. Prove immutability: pushing a different image with an existing tag fails.
docker build -t $REGISTRY/$REPO:v1.0.0 --build-arg BUILD_NOTE=changed .
docker push $REGISTRY/$REPO:v1.0.0 # expect: tag invalid ... ImageTagAlreadyExistsExceptionNotes:
- A rule with
"tagStatus": "any"must have the highestrulePrioritynumber (lowest priority) in the policy. aws ecr wait image-scan-completepolls until the scan finishes or the waiter times out.- If you need one movable tag such as
latestfor a development repository, useIMMUTABLE_WITH_EXCLUSIONwith--image-tag-mutability-exclusion-filters filterType=WILDCARD,filter=latest. Never do that for production repositories.
Archive instead of delete (retention)
Banks often need to keep released images for audit long after they stop running. ECR lifecycle policies can transition images to an archive storage class instead of deleting them. Archived images have a minimum storage duration of 90 days.
{
"rules": [
{
"rulePriority": 1,
"description": "Archive release images not pulled for 90 days",
"selection": {
"tagStatus": "tagged",
"tagPatternList": ["v*"],
"countType": "sinceImagePulled",
"countUnit": "days",
"countNumber": 90
},
"action": { "type": "transition", "targetStorageClass": "archive" }
},
{
"rulePriority": 2,
"description": "Delete archived images after 7 years",
"selection": {
"tagStatus": "any",
"storageClass": "archive",
"countType": "sinceImageTransitioned",
"countUnit": "days",
"countNumber": 2555
},
"action": { "type": "expire" }
}
]
}The seven-year figure is only an example. Your retention period comes from Harbourline's records-retention policy, set by legal and compliance, not from engineering. Check the archive storage price on the ECR pricing page before applying this ⚠ VERIFY.
Infrastructure as Code
This is the lab's compiled RegistryStack (labs/m03-accounts-api/infra/cdk/Harbourline.Accounts.Infra/SharedStack.cs):
/// <summary>Private ECR repository with immutable tags, scan on push and lifecycle rules.</summary>
public sealed class RegistryStack : Stack
{
public const string RepositoryName = "hl-m03-accounts-api";
public RegistryStack(Construct scope, string id, IStackProps props) : base(scope, id, props)
{
var repo = new Repository(this, "Repository", new RepositoryProps
{
RepositoryName = RepositoryName,
ImageTagMutability = TagMutability.IMMUTABLE, // a tag such as v1 can never be overwritten
ImageScanOnPush = true, // basic scanning; enable Inspector enhanced scanning at registry level for production
EmptyOnDelete = true, // ⚠ learning shortcut so destroy succeeds with images inside
RemovalPolicy = RemovalPolicy.DESTROY,
LifecycleRules =
[
new LifecycleRule { RulePriority = 1, Description = "Expire untagged images after 7 days", TagStatus = TagStatus.UNTAGGED, MaxImageAge = Duration.Days(7) },
new LifecycleRule { RulePriority = 2, Description = "Keep the 10 most recent images", TagStatus = TagStatus.ANY, MaxImageCount = 10 },
],
});
_ = new CfnOutput(this, "RepositoryUri", new CfnOutputProps { Value = repo.RepositoryUri });
}
}For production, add Encryption = RepositoryEncryption.KMS with EncryptionKey = yourKey, keep RemovalPolicy.RETAIN, and remove EmptyOnDelete. Cross-account pull for a production account looks like this:
repo.AddToResourcePolicy(new PolicyStatement(new PolicyStatementProps
{
Sid = "AllowProdAccountPull",
Principals = [new AccountPrincipal("444455556666")],
Actions = ["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer", "ecr:BatchCheckLayerAvailability"],
}));Complete code
The ScanGate is a small console app for the pipeline. It waits for the scan, prints the severity counts and exits non-zero when the image breaks the release rule. It compiles with TreatWarningsAsErrors, and its policy logic is unit-tested with no AWS account.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<RootNamespace>Harbourline.ScanGate</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AWSSDK.ECR" Version="4.1.2" />
<PackageReference Include="AWSSDK.SSO" Version="4.1.0.2" />
<PackageReference Include="AWSSDK.SSOOIDC" Version="4.1.0.2" />
</ItemGroup>
</Project>namespace Harbourline.ScanGate;
public sealed record GateVerdict(bool Passed, string Reason);
/// <summary>Release rule agreed with the security team: no CRITICAL, at most <see cref="MaxHigh"/> HIGH findings.</summary>
public sealed record GatePolicy(int MaxCritical, int MaxHigh)
{
public GateVerdict Evaluate(IReadOnlyDictionary<string, int> severityCounts)
{
var critical = severityCounts.GetValueOrDefault("CRITICAL");
var high = severityCounts.GetValueOrDefault("HIGH");
if (critical > MaxCritical) return new(false, $"{critical} CRITICAL finding(s), limit {MaxCritical}");
if (high > MaxHigh) return new(false, $"{high} HIGH finding(s), limit {MaxHigh}");
return new(true, "within policy");
}
}using Amazon.ECR;
using Amazon.ECR.Model;
using Harbourline.ScanGate;
// Usage: dotnet run -- <repository> <tag> [maxHigh]
// Exit codes: 0 = pass, 1 = blocked by policy, 2 = scan not available, 3 = usage error.
if (args.Length < 2)
{
Console.Error.WriteLine("Usage: Harbourline.ScanGate <repository> <tag> [maxHigh]");
return 3;
}
var repository = args[0];
var tag = args[1];
var policy = new GatePolicy(MaxCritical: 0, MaxHigh: args.Length > 2 ? int.Parse(args[2]) : 0);
// Region and credentials come from the default chain (AWS_PROFILE locally, the pipeline's role in CI).
using var ecr = new AmazonECRClient();
using var deadline = new CancellationTokenSource(TimeSpan.FromMinutes(10));
var request = new DescribeImageScanFindingsRequest
{
RepositoryName = repository,
ImageId = new ImageIdentifier { ImageTag = tag },
};
// 1. Wait for the scan to finish. Scan-on-push starts automatically but takes a little while.
DescribeImageScanFindingsResponse response;
var delay = TimeSpan.FromSeconds(5);
while (true)
{
try
{
response = await ecr.DescribeImageScanFindingsAsync(request, deadline.Token);
}
catch (ScanNotFoundException)
{
Console.Error.WriteLine($"No scan exists for {repository}:{tag}. Is scan on push (or enhanced scanning) enabled?");
return 2;
}
var status = response.ImageScanStatus?.Status;
if (status == ScanStatus.COMPLETE || status == ScanStatus.ACTIVE) break; // ACTIVE = enhanced scanning, continuously monitored
if (status == ScanStatus.FAILED || status == ScanStatus.UNSUPPORTED_IMAGE)
{
Console.Error.WriteLine($"Scan status {status}: {response.ImageScanStatus?.Description}");
return 2;
}
Console.WriteLine($"Scan status {status ?? "unknown"}; waiting {delay.TotalSeconds:N0} s...");
await Task.Delay(delay, deadline.Token);
delay = TimeSpan.FromSeconds(Math.Min(delay.TotalSeconds * 2, 30));
}
// 2. Decide. FindingSeverityCounts is null when the image has no findings at all (SDK v4).
var counts = response.ImageScanFindings?.FindingSeverityCounts ?? [];
var verdict = policy.Evaluate(counts);
foreach (var (severity, count) in counts.OrderBy(kv => kv.Key))
{
Console.WriteLine($" {severity,-14} {count,5}");
}
Console.WriteLine(verdict.Passed ? $"PASS {repository}:{tag}" : $"BLOCKED {repository}:{tag}: {verdict.Reason}");
return verdict.Passed ? 0 : 1;using Harbourline.ScanGate;
namespace Harbourline.ScanGate.Tests;
public class GatePolicyTests
{
[Theory]
[InlineData(0, 0, true)]
[InlineData(1, 0, false)]
[InlineData(0, 3, false)]
public void Applies_the_release_rule(int critical, int high, bool expected)
{
var counts = new Dictionary<string, int> { ["CRITICAL"] = critical, ["HIGH"] = high, ["MEDIUM"] = 12 };
Assert.Equal(expected, new GatePolicy(MaxCritical: 0, MaxHigh: 2).Evaluate(counts).Passed);
}
[Fact]
public void No_findings_passes() => Assert.True(new GatePolicy(0, 0).Evaluate(new Dictionary<string, int>()).Passed);
}Use it in a pipeline step after docker push:
dotnet run --project tools/Harbourline.ScanGate -- hl-m03-accounts-api v1.0.0 2 || { echo "Release blocked"; exit 1; }The pipeline role needs ecr:DescribeImageScanFindings (and inspector2:ListFindings if you extend the gate to Inspector's detailed findings).
Code explained line by line
GatePolicy.cs
GatePolicy(MaxCritical, MaxHigh)turns the security team's rule into code that can be reviewed and tested. The thresholds belong in pipeline configuration, not in individual developers' heads.GetValueOrDefault("CRITICAL")treats a missing severity as zero. ECR only returns severities that have findings.- Returning a
GateVerdictwith a reason gives the pipeline log a clear message such as "BLOCKED: 1 CRITICAL finding(s), limit 0".
Program.cs
new AmazonECRClient()uses the default chain. Locally that is your SSO profile throughAWS_PROFILE; in CI it is the OIDC-federated pipeline role. The Region comes fromAWS_REGION.CancellationTokenSource(TimeSpan.FromMinutes(10))is the overall deadline. A pipeline step must never hang forever.DescribeImageScanFindingsRequestwithImageTag. You can also passImageDigest, which is even safer because it is what ECS will run.catch (ScanNotFoundException)means no scan exists for this image: scan on push is off, or the image was pushed before scanning was enabled. That is a configuration failure, so exit code 2, distinct from "blocked by policy".status == ScanStatus.COMPLETE || status == ScanStatus.ACTIVE. Basic scans end inCOMPLETE. With enhanced scanning, Amazon Inspector reportsACTIVEwhile it monitors the image continuously.FAILED/UNSUPPORTED_IMAGEstop the gate with the description. An unsupported image means the scanner cannot read the OS. Chiseled Ubuntu images are scannable, but check with your first push.- The back-off loop (5, 10, 20, 30, 30 … seconds) avoids hammering the API while the scan runs.
FindingSeverityCounts ?? []. In SDK v4 the dictionary isnullwhen there are no findings at all. Without the null-coalescing, a perfectly clean image would crash the gate.- Exit codes let the pipeline distinguish a policy block (1) from a tooling problem (2) and a usage error (3).
Security considerations
⚠ Learning shortcut — not for production
The lab repository uses AES-256 encryption, EmptyOnDelete/force_delete and RemovalPolicy.DESTROY so that teardown is one command, and you push from your laptop with your SSO role. In production: KMS with a customer managed key (set at creation), RETAIN on deletion, pushes only from the CI role, and a repository policy that denies ecr:BatchDeleteImage to everyone except a controlled break-glass role.
- Deploy by digest, not by tag. ECS's default
versionConsistencyresolves a tag to a digest when the deployment starts, so every task in that deployment runs the same image. Recording the digest in the release ticket gives auditors exact traceability. - Immutable tags for anything that reaches production. If a team needs a moving tag for development, use a separate repository or
IMMUTABLE_WITH_EXCLUSIONlimited to that tag. - Enhanced scanning for production. Basic scanning sees OS packages at push time. Amazon Inspector also covers language packages (including NuGet dependencies in published .NET apps ⚠ VERIFY language coverage for your image layout) and rescans when new CVEs are published. That matters for images that run for months.
- Mirror base images. Pull through cache does not support MCR, so run a scheduled pipeline that pulls
mcr.microsoft.com/dotnet/aspnet:10.0-noble-chiseled, scans it, and pushes it to an internalbase/dotnet-aspnetrepository. Build from that. You control when new base images enter the bank, and builds do not depend on an external registry being up. - Sign images. ECR managed signing (launched November 2025) signs images automatically on push with an AWS Signer profile. Verification at deploy time (for example with an admission policy on EKS) proves the image came from your pipeline.
- Least privilege. Separate push (CI only) from pull (execution roles).
ecr:GetAuthorizationTokenapplies to*, but every other action can be scoped to repository ARNs. - Private networking. Use the
ecr.apiandecr.dkrinterface endpoints plus the S3 gateway endpoint. Add an endpoint policy that only allows your organisation's repositories, so a compromised task cannot push data out to an attacker's registry.
Banking use case
Harbourline runs ECR in a shared-services account with this release flow for the Accounts API:
- GitHub Actions builds the image and pushes it with tags
git-<sha>andv<semver>using an OIDC-federated role that may push only tohl-*repositories. - ECR managed signing signs the image. Amazon Inspector scans it.
- The
ScanGatestep blocks the release on any CRITICAL finding or more than two HIGH findings with no fix available. Exceptions need a time-limited risk acceptance recorded in the risk system, referenced in the pipeline's override input. - The deployment pipeline in the production account deploys the digest, not the tag.
- A lifecycle policy expires untagged images after 7 days and archives release images not pulled for 90 days. Archived images are kept for the retention period set by the records policy.
- Every week, Inspector findings for running images are exported to Security Hub. An image whose findings change from clean to CRITICAL triggers a rebuild on the latest mirrored base image.
When the auditor asks "what ran on 3 March?", the team queries CloudTrail for the ECS UpdateService and task events on that date, reads the digest, and pulls the archived image and its scan history. Whether this satisfies a particular PCI DSS or regulatory requirement is for Harbourline's compliance team and assessors to confirm.
Common mistakes
- Using
latestin production → nobody can tell what is running, and rollbacks are guesswork → immutable version and SHA tags, deploy by digest. - Scan on push enabled after images were pushed → old images have no scan (
ScanNotFoundException) → enable scanning at registry level first, or start a manual scan (aws ecr start-image-scan). - Trusting a clean basic scan forever → new CVEs appear daily → enhanced scanning, or a scheduled rebuild and rescan.
- Lifecycle rule with
tagStatus: anyat priority 1 → it marks everything before your more specific rules → keepanyrules at the highest priority number. - Lifecycle policy deletes an image still in use → the next task launch fails with
CannotPullContainerError→ keep enough images (count rules), and archive instead of expiring release tags. - Forgetting the S3 gateway endpoint with ECR interface endpoints → image pulls hang at layer download → add
com.amazonaws.<region>.s3as a gateway endpoint on the private route tables. - Cross-account pull with only one side configured →
AccessDenied→ the repository policy (resource side) and the execution role's IAM policy (identity side) must both allow it. - Pushing from developer laptops to production repositories → unreviewed images in production → repository policy that allows push only from the CI role.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
no basic auth credentials or denied: Your authorization token has expired on push | Not logged in, or the 12-hour token expired | Re-run aws ecr get-login-password ... | docker login ... |
name unknown: The repository with name ... does not exist | Repository not created (ECR does not create on push unless you configure create-on-push templates), or wrong Region or account in the URI | Create the repository; check the registry URI |
tag invalid: The image tag 'v1.0.0' already exists ... cannot be overwritten because the repository is immutable | Immutable tags working as designed | Bump the version; never reuse release tags |
ScanNotFoundException in the gate | Scan on push off, or the image was pushed before scanning was enabled | Enable registry scanning; run aws ecr start-image-scan |
Scan status UNSUPPORTED_IMAGE | Base OS not supported by the scanner | Use a supported base (Ubuntu chiseled is); check the supported OS list |
ECS task CannotPullContainerError ... i/o timeout | No network path to ECR or S3 from private subnets | NAT gateway, or ecr.api + ecr.dkr interface endpoints and the S3 gateway endpoint; security group allows 443 to the endpoints |
ECS task CannotPullContainerError ... AccessDeniedException | Execution role lacks ECR permissions, or the cross-account repository policy is missing | Attach AmazonECSTaskExecutionRolePolicy; add the repository policy |
exec format error when the task starts | Image architecture (amd64) differs from the task's (ARM64), or the reverse | Build for the task's platform (--platform linux/arm64) or a multi-arch image |
| Lifecycle policy "did nothing" | Rules are evaluated within 24 hours; or a higher-priority rule already selected the images | Wait, then check get-lifecycle-policy-preview and the rule priorities |
Cost and cleanup
ECR costs are small for a lab:
| Item | Cost (us-east-1) |
|---|---|
| Private storage | USD 0.10 per GB-month. A chiseled .NET API image is roughly 100 MB compressed, so about one cent a month |
| Data transfer to ECS, Fargate, EC2, Lambda in the same Region | Free |
| Free tier | New customers: 500 MB per month of private storage for one year (accounts created from 15 July 2025 receive Free Tier credits instead, usable on ECR) |
| Basic scanning | No charge |
| Enhanced scanning (Amazon Inspector) | Charged per image scanned and rescanned; see Inspector pricing ⚠ VERIFY current rates |
| Managed signing | Charged per signature (about USD 0.02 per signature at launch ⚠ VERIFY) |
| Interface VPC endpoints (if used) | Per endpoint per AZ-hour plus per GB: these cost more than the registry itself for a lab |
So the label is free if you push one image and delete it the same day.
# Delete the repository and all images in it.
aws ecr delete-repository --repository-name hl-m03-accounts-api --force --region us-east-1 --profile learn-sandbox
# Or: cdk destroy HlM03-Registry / terraform destroy
# Log Docker out of the registry.
docker logout $ACCOUNT.dkr.ecr.us-east-1.amazonaws.com
# Confirm nothing tagged for this lesson remains.
aws resourcegroupstaggingapi get-resources --tag-filters Key=Lab,Values=m03-ecr \
--region us-east-1 --profile learn-sandbox --query "ResourceTagMappingList[].ResourceARN"
aws ecr describe-repositories --region us-east-1 --profile learn-sandbox --query "repositories[].repositoryName"If you changed the registry scanning configuration to enhanced, switch it back to basic (or turn off Inspector ECR scanning) so it does not keep billing.
Exercises
- 🟢 Guided: Create the repository, push the Accounts API image with two tags, wait for the scan, read the severity counts with the CLI, and run the
ScanGatewithmaxHigh= 0 and then 5. Try to push a changed image with the same version tag and capture the error. - 🟡 Challenge: Extend the
ScanGateto accept a digest instead of a tag, and to print the five most severe findings (name, package, fixed version) using theFindingslist for basic scans. Use the paginatorecr.Paginators.DescribeImageScanFindings(...)and stop after five. - 🔴 Live problem: A new critical OpenSSL CVE is announced on a Friday afternoon. The CISO asks: "Which of our production services are affected, and when will they be fixed?" You have 30 repositories, basic scanning only, and images built over the past six months. Plan your response for the next four hours and the next four weeks.
Assignment
Add a docs/container-supply-chain.md page to your portfolio repository describing your image policy: base-image mirroring, tagging scheme, immutability, scanning (basic or enhanced) and the gate thresholds, signing, lifecycle and archive rules, who can push and pull, and the evidence you can produce for an auditor. Include the ScanGate and its tests, and a GitHub Actions workflow snippet that runs it after the push step.
Solutions
dotnet run --project src/Harbourline.ScanGate -- hl-m03-accounts-api v1.0.0 0
# HIGH 1
# LOW 4
# MEDIUM 3
# BLOCKED hl-m03-accounts-api:v1.0.0: 1 HIGH finding(s), limit 0
echo $? # 1
dotnet run --project src/Harbourline.ScanGate -- hl-m03-accounts-api v1.0.0 5
# PASS hl-m03-accounts-api:v1.0.0Your counts will differ, and may be zero for a freshly patched chiseled image. The push with an existing tag fails with a message containing ImageTagAlreadyExistsException (Docker prints it as "tag invalid ... already exists ... cannot be overwritten because the repository is immutable").
Why: the exit code is what the pipeline acts on. The immutability failure proves that nobody, including you, can silently replace v1.0.0.
var imageId = tagOrDigest.StartsWith("sha256:", StringComparison.Ordinal)
? new ImageIdentifier { ImageDigest = tagOrDigest }
: new ImageIdentifier { ImageTag = tagOrDigest };
string[] order = ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFORMATIONAL", "UNDEFINED"];
var findings = new List<ImageScanFinding>();
var paginator = ecr.Paginators.DescribeImageScanFindings(new DescribeImageScanFindingsRequest
{
RepositoryName = repository,
ImageId = imageId,
});
await foreach (var page in paginator.Responses.WithCancellation(deadline.Token))
{
findings.AddRange(page.ImageScanFindings?.Findings ?? []);
}
foreach (var f in findings.OrderBy(f => Array.IndexOf(order, f.Severity?.Value)).Take(5))
{
var attrs = (f.Attributes ?? []).ToDictionary(a => a.Key, a => a.Value);
Console.WriteLine($"{f.Severity?.Value,-9} {f.Name,-18} {attrs.GetValueOrDefault("package_name")} {attrs.GetValueOrDefault("package_version")}");
}Why: a digest is the only identifier ECS will actually run, so the gate should check exactly that. Reading all pages then sorting is simple and safe for the few hundred findings an image typically has. Basic scan findings carry package details in Attributes (keys such as package_name and package_version ⚠ VERIFY attribute names in your output). Enhanced scans return EnhancedFindings instead, with a richer structure.
Next four hours:
- Find what is running. List running ECS task definitions and their image digests across production accounts (
aws ecs list-tasks/describe-tasks, or AWS Config's resource inventory). - Find what is affected. For each running digest, start a manual basic scan (
aws ecr start-image-scan). Each image can be scanned once per 24 hours. Search findings for the CVE ID. In parallel, check the vendor advisory: Ubuntu chiseled images contain far fewer packages, and the CVE may only affect certain library versions. - Communicate. Send the CISO an affected/not-affected list per service, with confidence levels and next update time.
- Mitigate where possible: WAF rules or configuration changes, if the advisory suggests any.
Next four weeks:
- When Microsoft publishes patched .NET images (they rebuild on base OS fixes), the base-image mirror pipeline pulls, scans and publishes them. All services rebuild and redeploy through the normal pipeline, with the gate proving the CVE is gone.
- Turn on enhanced scanning for production repositories, so the next question ("which running images are affected?") is answered continuously by Inspector instead of manual rescans.
- Add a weekly automatic rebuild of every service on the latest mirrored base image, so patches flow even without a crisis.
- Write the post-incident review: time to identify, time to remediate, gaps found.
Why: the hard part is not patching. It is knowing what runs where. Digests, immutable tags and continuous scanning turn a frantic weekend into a query.
Knowledge check
Answer: A tag is a human-readable label that, unless the repository is immutable, can be moved to another image. A digest is the SHA-256 hash of the image manifest. It identifies exactly one image content and can never change.
Answer: 12 hours. The token is derived from the IAM credentials that called GetAuthorizationToken, so pushes and pulls are authorised by that identity's IAM policies (and any repository policy).
Answer: Enhanced scanning (Amazon Inspector) monitors images continuously and updates findings when new vulnerabilities are published. Basic scanning scans on push or on demand, at most once per image per 24 hours.
Answer: Interface endpoints for com.amazonaws.<region>.ecr.api and com.amazonaws.<region>.ecr.dkr, plus the S3 gateway endpoint, because image layers are served from S3. If the task logs to CloudWatch, it also needs the logs interface endpoint.
Answer: Rules are applied in priority order and an image is acted on by at most one rule. An any rule at a higher priority would claim images before the more specific rules (such as "untagged older than 7 days") could select them. ECR requires any rules to come last.
Interview questions
- "How do you make sure the image in production is the one you tested?" — Immutable tags, build once and promote the same image through environments, deploy by digest, sign images on push, and verify signatures or digests at deploy time.
- "How do you handle container vulnerabilities?" — Small base images (chiseled), mirrored and regularly refreshed. Scan on push with a pipeline gate. Continuous enhanced scanning for running images. Automatic weekly rebuilds. A documented exception process with expiry dates.
- "How do ECS tasks in private subnets pull images?" — Through a NAT gateway, or privately through the
ecr.apiandecr.dkrinterface endpoints plus the S3 gateway endpoint. The task execution role needs the ECR pull permissions and, for cross-account, the repository policy must allow it. - "How do you control ECR storage cost?" — Lifecycle policies: expire untagged images quickly, keep the last N, archive old releases that must be retained, and delete archives after the retention period.
Certification practice
A team discovered that two different builds were pushed to Amazon ECR with the same tag v2.4.1, and ECS tasks are running both versions. The team must prevent this from happening again with the LEAST operational effort. What should they do?
A. Add a pipeline step that checks whether the tag exists before pushing. B. Enable tag immutability on the ECR repository. C. Enable scan on push. D. Create a lifecycle policy that keeps only one image per tag.
Answer: B. With tag immutability, ECR rejects any push that reuses an existing tag. A is a custom check that can race or be bypassed. C is about vulnerabilities. D cannot express "one image per tag" and would not prevent the overwrite.
A financial company stores hundreds of container images in Amazon ECR. Images remain in production for months. The security team needs to know when a newly published CVE affects an image that is already deployed, without rebuilding or re-pushing it. Which solution meets this requirement?
A. Enable basic scanning with scan on push. B. Enable enhanced scanning with Amazon Inspector at the registry level with continuous scanning. C. Run a weekly AWS Lambda function that pulls each image and runs an open-source scanner. D. Enable AWS Config rules for ECR repositories.
Answer: B. Enhanced scanning continuously re-evaluates images as new vulnerabilities are published. Basic scanning only scans on push or on demand (A). C works but adds custom operational effort. Config rules check configuration, not image contents (D).
An ECS service on Fargate runs in private subnets that have no route to the internet. The VPC has interface endpoints for ecr.api and ecr.dkr. Tasks fail with CannotPullContainerError and a timeout while downloading layers. What is the MOST likely fix?
A. Add an Amazon S3 gateway endpoint to the private subnets' route tables.
B. Attach AmazonEC2ContainerRegistryFullAccess to the task role.
C. Enable scan on push.
D. Change the repository to mutable tags.
Answer: A. ECR stores image layers in S3, so tasks need a path to S3: the gateway endpoint. The task role is for the application, not for pulling images (the execution role does that), and full access is not least privilege (B). C and D are unrelated to networking.
Completion checklist
- I created a repository with immutable tags and scan on push
- I pushed an image with SHA and version tags and recorded its digest
- I read the scan results with the CLI and ran the ScanGate
- I previewed and applied a lifecycle policy
- I deleted the repository and logged Docker out
Key takeaways
- Digests identify images; tags are labels. Make release tags immutable and deploy by digest.
- Scan on push is free and catches known OS CVEs at build time. Enhanced scanning keeps watching after deployment. Gate releases on the results.
- Lifecycle policies control cost and retention: expire untagged images, keep the last N, archive releases you must keep.
- IAM on both sides for cross-account pulls; VPC endpoints plus the S3 gateway endpoint for private pulls.
- Mirror the .NET base images yourself (pull through cache does not support MCR), and consider managed signing for provenance.
Further reading
- Preventing image tags from being overwritten in Amazon ECR
- Scan images for OS vulnerabilities in Amazon ECR
- Automate the cleanup of images by using lifecycle policies in Amazon ECR
- Examples of lifecycle policies in Amazon ECR
- Sync an upstream registry with an Amazon ECR private registry
- Amazon ECR now supports managed container image signing
- Amazon ECR pricing
- Previous: Containerising .NET · Next: Deploying .NET to ECS on Fargate
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.
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.
Deploying .NET to ECS on Fargate
Deploy a containerised ASP.NET Core API to Amazon ECS on Fargate in private subnets behind an Application Load Balancer, with separate task and execution roles, safe rolling deployments and a C# rollout watcher.