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

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.

intermediate⏱ 1 h 30 min🟢 FreeDVA-C03SCS-C03

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 equivalentWhat's different
Azure Container Registry (ACR)Amazon ECR private registryNo SKUs (Basic/Standard/Premium). One registry per account per Region; pay per GB stored
ACR repositories and tagsECR repositories and tagsTag immutability is a repository setting, with optional wildcard exclusions
az acr loginaws ecr get-login-password | docker login --username AWS --password-stdinToken valid for 12 hours, derived from your IAM credentials
Microsoft Defender for Containers scanningECR basic scanning, or enhanced scanning with Amazon InspectorBasic is free and on push; Inspector rescans continuously and covers language packages such as NuGet
ACR retention policy / acr purgeECR 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 / NotationECR managed signing with AWS Signer, or Notation with the Signer pluginManaged signing signs automatically on push
ACR private endpointsInterface VPC endpoints ecr.api and ecr.dkr, plus the S3 gateway endpointImage layers are served from S3, so you need the S3 endpoint too
ACR cache rulesECR pull through cacheUpstreams 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.api and com.amazonaws.us-east-1.ecr.dkr) and fetch layers through the S3 gateway endpoint. No internet path is needed.
  • Evidence: CloudTrail records PutImage, BatchGetImage and BatchDeleteImage. 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

  1. 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>.
  2. 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.
  3. Repositories → hl-m03-accounts-api → View push commands. The console shows the four commands (login, build, tag, push) for your account and Region.
  4. After pushing: Images → (your tag). Open Vulnerabilities to see findings by severity, with the package and fixed version for each.
  5. 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 ... ImageTagAlreadyExistsException

Notes:

  • A rule with "tagStatus": "any" must have the highest rulePriority number (lowest priority) in the policy.
  • aws ecr wait image-scan-complete polls until the scan finishes or the waiter times out.
  • If you need one movable tag such as latest for a development repository, use IMMUTABLE_WITH_EXCLUSION with --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.

lifecycle-archive.json
{
  "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):

RegistryStack (from the lab)
/// <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.

Harbourline.ScanGate.csproj
<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>
GatePolicy.cs
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");
    }
}
Program.cs
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;
tests/Harbourline.ScanGate.Tests/GatePolicyTests.cs
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

  1. 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.
  2. GetValueOrDefault("CRITICAL") treats a missing severity as zero. ECR only returns severities that have findings.
  3. Returning a GateVerdict with a reason gives the pipeline log a clear message such as "BLOCKED: 1 CRITICAL finding(s), limit 0".

Program.cs

  1. new AmazonECRClient() uses the default chain. Locally that is your SSO profile through AWS_PROFILE; in CI it is the OIDC-federated pipeline role. The Region comes from AWS_REGION.
  2. CancellationTokenSource(TimeSpan.FromMinutes(10)) is the overall deadline. A pipeline step must never hang forever.
  3. DescribeImageScanFindingsRequest with ImageTag. You can also pass ImageDigest, which is even safer because it is what ECS will run.
  4. 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".
  5. status == ScanStatus.COMPLETE || status == ScanStatus.ACTIVE. Basic scans end in COMPLETE. With enhanced scanning, Amazon Inspector reports ACTIVE while it monitors the image continuously.
  6. FAILED / UNSUPPORTED_IMAGE stop 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.
  7. The back-off loop (5, 10, 20, 30, 30 … seconds) avoids hammering the API while the scan runs.
  8. FindingSeverityCounts ?? []. In SDK v4 the dictionary is null when there are no findings at all. Without the null-coalescing, a perfectly clean image would crash the gate.
  9. 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 versionConsistency resolves 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_EXCLUSION limited 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 internal base/dotnet-aspnet repository. 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:GetAuthorizationToken applies to *, but every other action can be scoped to repository ARNs.
  • Private networking. Use the ecr.api and ecr.dkr interface 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:

  1. GitHub Actions builds the image and pushes it with tags git-<sha> and v<semver> using an OIDC-federated role that may push only to hl-* repositories.
  2. ECR managed signing signs the image. Amazon Inspector scans it.
  3. The ScanGate step 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.
  4. The deployment pipeline in the production account deploys the digest, not the tag.
  5. 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.
  6. 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 latest in 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: any at priority 1 → it marks everything before your more specific rules → keep any rules 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>.s3 as 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

SymptomLikely causeFix
no basic auth credentials or denied: Your authorization token has expired on pushNot logged in, or the 12-hour token expiredRe-run aws ecr get-login-password ... | docker login ...
name unknown: The repository with name ... does not existRepository not created (ECR does not create on push unless you configure create-on-push templates), or wrong Region or account in the URICreate the repository; check the registry URI
tag invalid: The image tag 'v1.0.0' already exists ... cannot be overwritten because the repository is immutableImmutable tags working as designedBump the version; never reuse release tags
ScanNotFoundException in the gateScan on push off, or the image was pushed before scanning was enabledEnable registry scanning; run aws ecr start-image-scan
Scan status UNSUPPORTED_IMAGEBase OS not supported by the scannerUse a supported base (Ubuntu chiseled is); check the supported OS list
ECS task CannotPullContainerError ... i/o timeoutNo network path to ECR or S3 from private subnetsNAT gateway, or ecr.api + ecr.dkr interface endpoints and the S3 gateway endpoint; security group allows 443 to the endpoints
ECS task CannotPullContainerError ... AccessDeniedExceptionExecution role lacks ECR permissions, or the cross-account repository policy is missingAttach AmazonECSTaskExecutionRolePolicy; add the repository policy
exec format error when the task startsImage architecture (amd64) differs from the task's (ARM64), or the reverseBuild 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 imagesWait, then check get-lifecycle-policy-preview and the rule priorities

Cost and cleanup

ECR costs are small for a lab:

ItemCost (us-east-1)
Private storageUSD 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 RegionFree
Free tierNew 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 scanningNo charge
Enhanced scanning (Amazon Inspector)Charged per image scanned and rescanned; see Inspector pricing ⚠ VERIFY current rates
Managed signingCharged 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 ScanGate with maxHigh = 0 and then 5. Try to push a changed image with the same version tag and capture the error.
  • 🟡 Challenge: Extend the ScanGate to accept a digest instead of a tag, and to print the five most severe findings (name, package, fixed version) using the Findings list for basic scans. Use the paginator ecr.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

Knowledge check

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.api and ecr.dkr interface 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

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

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