Amazon ECR is the one service in the DOP-C02 blueprint that almost every candidate “already knows” and almost nobody has studied. You have typed aws ecr get-login-password a hundred times, you know a task execution role pulls the image, and you know lifecycle policies delete old tags. Then the exam asks why a Docker Hub image pulled through ECR is a day stale, why a cross-account replication silently never happens, or why a lifecycle rule with tagStatus: any expired the production image your other rule was supposed to protect, and the answer is a mechanism, not a feature name.
This guide covers those mechanisms. Our SDLC Automation guide places ECR in the pipeline, the CodePipeline V2 internals post covers how the build that pushes the image is triggered, the CodeArtifact post covers the package-registry equivalent of what you are about to read, and our ECS, ECR & Fargate guide for the Developer Associate covers the push/pull/auth basics at associate altitude. This post assumes those and goes inside the registry: pull through cache, replication, the lifecycle policy evaluator, tag mutability, scanning, repository creation templates, the two policy layers, VPC endpoints and the archive storage class.
Where ECR Sits in the DOP-C02 Blueprint
ECR does not get its own task statement. It appears as the artifact store inside Domain 1 (SDLC Automation), as something to configure at scale inside Domain 2 (Configuration Management and IaC), as a replication target inside Domain 4 (Monitoring and Logging) and Domain 5 (Incident and Event Response) when scan findings must trigger action, and as a security control inside Domain 6 (Security and Compliance). The practical effect is that ECR facts arrive wrapped in a larger scenario: a multi-Region ECS deployment, an EKS cluster in a private subnet, an organisation that wants every repository to be immutable and encrypted with KMS, a security team that wants vulnerability findings in Security Hub.
The questions reward the candidate who knows which layer a setting lives at (registry, repository or image), which account owns the policy (source or destination), and which timer applies (24 hours for cache refresh and lifecycle evaluation, under 30 minutes for most replications, 20 minutes for a restore).
The Three Layers: Registry, Repository, Image
Everything in ECR is scoped to one of three layers, and most wrong answers on the exam put a setting at the wrong one.
| Layer | What it is | Settings that live here |
|---|---|---|
| Private registry | One per account per Region, <account>.dkr.ecr.<region>.amazonaws.com | Registry permissions policy, replication configuration, pull through cache rules, scanning configuration (basic vs enhanced + filters), repository creation templates |
| Repository | A named collection of images | Repository policy (resource-based), tag mutability (+ exclusion filters), encryption (AES256 or KMS, fixed at creation), lifecycle policy, resource tags, repository-level basic scan-on-push |
| Image | A manifest (or manifest list) plus layers, addressed by tag or digest | Storage class (standard or archive), scan findings, replication status, referrer artifacts |
Two consequences matter immediately. First, replication, pull through cache and scanning type are registry-level, so you configure them once per Region and they apply to every repository that matches a filter. Second, encryption cannot be changed after a repository exists, which is why the exam keeps steering you toward repository creation templates when an organisation “wants all new repositories encrypted with a customer managed key”.
Pull Through Cache Rules
A pull through cache rule tells your private registry: “when someone pulls <my-registry>/<prefix>/<upstream-path>:<tag>, fetch it from the upstream registry, store it in a repository you create for me, and serve it from there.” It turns ECR into a caching proxy for public and partner registries, which solves three real problems: Docker Hub rate limits, upstream outages during a deployment, and workloads in private subnets that have no route to the public internet.
Supported upstreams and authentication
| Upstream registry | Authentication required? | How credentials are supplied |
|---|---|---|
| Amazon ECR Public | No | — |
Kubernetes container image registry (registry.k8s.io) | No | — |
| Quay | No | — |
| Docker Hub | Yes | Secrets Manager secret |
| GitHub Container Registry | Yes | Secrets Manager secret |
| GitLab Container Registry (SaaS only) | Yes | Secrets Manager secret |
| Microsoft Azure Container Registry | Yes | Secrets Manager secret |
| Chainguard Registry | Yes | Secrets Manager secret |
| Another Amazon ECR private registry | Cross-account only | IAM role |
The Secrets Manager secret has a hard naming rule: its name must start with ecr-pullthroughcache/, and it must live in the same account and Region as the rule. A question that shows a secret named dockerhub-creds and asks why the rule creation fails is testing exactly this. For a cross-account ECR-to-ECR cache, the rule references an IAM role instead of a secret.
# Rule for Docker Hub (authenticated upstream)
aws ecr create-pull-through-cache-rule \
--ecr-repository-prefix docker-hub \
--upstream-registry docker-hub \
--upstream-registry-url registry-1.docker.io \
--credential-arn arn:aws:secretsmanager:us-east-1:111122223333:secret:ecr-pullthroughcache/docker-hub-AbCdEf
# Rule for ECR Public (no credentials)
aws ecr create-pull-through-cache-rule \
--ecr-repository-prefix ecr-public \
--upstream-registry ecr-public \
--upstream-registry-url public.ecr.aws
# First pull creates the repository docker-hub/library/nginx and caches the image
docker pull 111122223333.dkr.ecr.us-east-1.amazonaws.com/docker-hub/library/nginx:1.27
Note the library/ segment for Docker Hub official images. The cached repository name is <prefix>/<upstream repository path>, and ECR never renames it.
The refresh window: 24 hours (and 6 for referrers)
This is the fact the exam loves. When you pull a cached tag, ECR checks whether it has validated that tag against the upstream within the last 24 hours. If the window has expired, it contacts the upstream, and if a newer image exists under that tag it updates the cache. If the window has not expired, it serves the cached image without contacting the upstream at all. Referrer artifacts (signatures, SBOMs attached to an image) use a shorter 6-hour window.
Two corollaries:
- If the upstream is unreachable or the credentials in the secret have expired, the last cached image is still served. Pull through cache degrades gracefully.
- A mutable tag (
latest,1.27) can therefore be up to 24 hours behind the upstream. If the scenario says “developers report that the cached image does not reflect the fix published upstream an hour ago”, the answer is the refresh window, not a misconfigured rule. Pulling by digest sidesteps the problem entirely.
Considerations that become distractors
- Tag immutability on a cached repository prevents updates. ECR cannot overwrite the tag, so the cache freezes at the first version. The docs recommend
MUTABLEfor pull through cache repositories. - Pushing directly to a cached repository is unsupported and causes pulls to keep returning the old cached version until you delete the image or wait up to 24 hours.
- AWS Lambda cannot pull container images through a pull through cache rule.
- The first pull may need a route to the internet even if you use interface VPC endpoints for ECR. Subsequent pulls are served from the cache over PrivateLink. The documented fix is a NAT gateway in a public subnet for the first pull.
- Multi-architecture images pull the manifest list and every referenced architecture; pull a specific architecture by digest to avoid that.
- A service-linked role is created automatically to let ECR create the repository, read the secret and push the cached image.
- There are 50 pull through cache rules per registry (not adjustable).
The IAM side
Three permissions are involved and they are granted in different places:
| Permission | What it allows | Where it can be granted |
|---|---|---|
ecr:CreatePullThroughCacheRule | Create the rule | Identity-based IAM policy only |
ecr:BatchImportUpstreamImage | Fetch the upstream image and import it | Identity policy, registry policy, or repository policy |
ecr:CreateRepository | Create the cached repository on first pull | Identity policy or registry policy |
If a developer can pull from existing cached repositories but the first pull of a new upstream image fails, the missing permission is ecr:CreateRepository (or ecr:BatchImportUpstreamImage if nothing imports at all). The registry permissions policy is the mechanism for scoping who may trigger upstream imports for which prefix; an identity policy with ecr:* already covers everything, so the registry policy only adds, never subtracts.
Private Image Replication
Replication is a registry-level configuration that copies images to other Regions and other accounts as they are pushed. It is how you give a multi-Region ECS or EKS deployment a local registry in every Region, and it is one of the most testable DOP-C02 facts because of three counter-intuitive rules.
Rule 1: Only the destination needs a policy
For cross-account replication, the destination account must have a registry permissions policy granting the source account ecr:ReplicateImage and (so ECR can create missing repositories) ecr:CreateRepository. The source account needs nothing beyond the replication configuration itself. The documentation lists the misconceptions explicitly: the source repository does not need a policy allowing the destination to replicate, and both accounts do not need registry policies.
{
"Version": "2012-10-17",
"Statement": [{
"Sid": "AllowCrossAccountReplication",
"Effect": "Allow",
"Principal": { "AWS": "arn:aws:iam::111122223333:root" },
"Action": ["ecr:ReplicateImage", "ecr:CreateRepository"],
"Resource": "*"
}]
}
Apply it in the destination with aws ecr put-registry-policy --policy-text file://policy.json. If you omit ecr:CreateRepository, you must pre-create repositories with identical names in the destination. Cross-Region replication within one account needs no policy at all, but both Regions must be opted in, and replication never crosses partitions (us-west-2 to cn-north-1 is impossible).
Rule 2: Only future pushes replicate, and only one hop
- Pre-existing images are not replicated when you turn replication on. Only content pushed (or restored from archive) afterwards is copied. For existing images, ECR now offers replication backfill; before that existed, the answer was “re-push”.
- A replication action happens once per push. If A replicates to B and B replicates to C, an image pushed to A reaches B and stops. There is no chaining.
- Most images replicate in under 30 minutes. Check with
aws ecr describe-image-replication-status --repository-name app --image-id imageTag=1.4.2. - Repository names are identical in every destination; ECR cannot rename during replication.
Rule 3: Replication copies images, not settings
Repository policies, lifecycle policies and repository settings (tag mutability, encryption) are not replicated. A destination repository created by replication gets the defaults (mutable tags, AES256, no policies) unless a repository creation template with appliedFor: REPLICATION matches it. Replication also performs no delete or archive actions: expiring an image at the source does nothing at the destination, and archiving at the source does not archive at the destination (though replicating into an archived destination image restores it).
One more trap: if the destination repository has tag immutability and the replicated image’s tag already exists there, the image is replicated but arrives without the duplicate tag, which may leave it untagged.
Configuration shape and quotas
{
"rules": [{
"destinations": [
{ "region": "eu-west-1", "registryId": "111122223333" },
{ "region": "us-east-1", "registryId": "444455556666" }
],
"repositoryFilters": [
{ "filter": "prod/", "filterType": "PREFIX_MATCH" }
]
}]
}
aws ecr put-replication-configuration --replication-configuration file://replication.json installs it. The limits are 25 rules, 25 unique destinations across all rules, and 100 filters per rule, none adjustable. Filters are prefix matches only. If KMS encryption is involved cross-Region, the destination key policy needs additional permissions, and if blob mounting is enabled in both registries ECR mounts layers that already exist at the destination instead of copying them.
Lifecycle Policies: How the Evaluator Actually Decides
A lifecycle policy is a JSON document of up to 50 rules and 30,720 characters attached to one repository. Once applied, images meeting the criteria are expired or archived within 24 hours, and every action is recorded in CloudTrail. The exam tests the evaluator’s logic far more than the JSON syntax, so learn the rules of engagement.
The selection vocabulary
{
"rules": [{
"rulePriority": 1,
"description": "Expire untagged images older than 14 days",
"selection": {
"tagStatus": "untagged",
"countType": "sinceImagePushed",
"countUnit": "days",
"countNumber": 14
},
"action": { "type": "expire" }
}]
}
| Field | Values | Rules |
|---|---|---|
tagStatus | tagged, untagged, any | tagPatternList/tagPrefixList allowed only with tagged |
tagPatternList | wildcard patterns, e.g. ["prod*"], ["*release*"] | Max 4 wildcards per string; mutually exclusive with tagPrefixList in the same rule |
tagPrefixList | literal prefixes, e.g. ["prod", "v1."] | An image matches only if all listed prefixes match one of its tags |
countType | imageCountMoreThan, sinceImagePushed, sinceImagePulled, sinceImageTransitioned | countUnit: days is required for the three since* types |
storageClass | standard, archive | Optional selector; sinceImageTransitioned requires archive |
action.type | expire, transition | transition needs targetStorageClass: archive |
The “all patterns must match” rule is the subtle one. ["alpha*", "beta*"] in a single rule selects only images tagged with both an alpha* and a beta* tag. To select images with either, write two rules.
The evaluation rules
- All rules are evaluated at the same time; then they are applied in priority order. A lower
rulePrioritynumber means higher priority. - An image is expired or archived by exactly one or zero rules.
- An image that matches a higher-priority rule’s tagging requirements cannot be expired by a lower-priority rule, even if the higher-priority rule decided to keep it. This is the rule that produces the counter-intuitive results.
- Expiration is always oldest first, ordered by
pushed_at_time(orlast_activated_atfor a restored image). imageCountMoreThansorts images youngest to oldest and expires everything beyond the count.sinceImagePushedexpires anything older than N days.sinceImagePulleduseslast_recorded_pulltime, falling back to push time for never-pulled images.sinceImageTransitionedapplies to archived images only.- An image referenced by a manifest list cannot expire until the manifest list is deleted.
- Referrer artifacts attached to an image expire within 24 hours of the subject image’s expiry.
Here is the documented example that the exam paraphrases. Repository: Image A tagged beta-1 + prod-1 (10 days old), Image B tagged beta-2 + prod-2 (9 days), Image C tagged beta-3 (8 days). Rule 1 (priority 1): tagged prod*, imageCountMoreThan: 1. Rule 2 (priority 2): tagged beta*, imageCountMoreThan: 1.
- Rule 1 sees A and B, keeps the newest (B) and marks A.
- Rule 2 sees A, B and C and would mark A and B. But B matched Rule 1, which protected it, so Rule 2 may not expire B. It marks A, already marked.
- Result: only A expires.
Swap the priorities and the outcome flips: the beta* rule now runs first, marks A and B, and the prod* rule finds nothing it is allowed to touch. A and B expire, including the newest prod image. Rule order is not cosmetic.
The same mechanism explains the classic “keep the last 10 release images, delete everything else” policy. The tagStatus: any catch-all rule must carry the highest priority number (lowest priority) so the specific rules claim their images first. Put it at priority 1 and it eats everything.
Preview before you apply
Always run the preview on a production repository:
aws ecr start-lifecycle-policy-preview --repository-name app --lifecycle-policy-text file://policy.json
aws ecr get-lifecycle-policy-preview --repository-name app # lists images that WOULD be affected
aws ecr put-lifecycle-policy --repository-name app --lifecycle-policy-text file://policy.json
A question that mentions “a lifecycle policy deleted images that were still in use” and asks what should have been done first is pointing at the preview.
Lifecycle policies at scale
A lifecycle policy belongs to one repository and is not replicated. To apply the same policy to every repository in an organisation you have three tools: a repository creation template (for repositories ECR creates), infrastructure as code (CloudFormation AWS::ECR::Repository with LifecyclePolicy, or a StackSet across accounts), or an automation that calls put-lifecycle-policy on repository creation events. The Configuration Management & IaC guide covers the StackSet pattern.
The Archive Storage Class
ECR has two storage classes: standard (default, for active images) and archive (low-cost, for images that are rarely pulled but must be retained for compliance). Images move to archive either through a lifecycle transition action (based on push age, last pull, or image count) or manually. The rules that matter:
- Minimum 90 days in archive. A lifecycle policy cannot expire an image archived for less than 90 days, and
sinceImageTransitionedmust be used withexpireand thearchivestorage class. Deleting earlier throughbatch-delete-imagestill bills the 90-day minimum. - Archived images cannot be pulled or scanned. Restore them first; ECR restores within 20 minutes, and a restored image behaves like a newly pushed image, so it is subject to scanning, replication and lifecycle policies again.
- A combined policy is the canonical pattern: priority 1 transitions images older than 30 days to archive; priority 2 expires images archived for more than 365 days.
Exam cue: “retain every production image for seven years at the lowest cost, images are almost never pulled after 90 days” is the archive storage class, not S3, not deletion.
Tag Mutability and Exclusion Filters
By default a repository is MUTABLE: pushing app:1.4.2 again silently moves the tag to the new digest. Setting IMMUTABLE makes any push with an existing tag fail with ImageTagAlreadyExistsException. Immutability applies to all tags in the repository, which historically created a dilemma: teams wanted immutable release tags but a floating latest. ECR now solves that with exclusion filters:
| Setting | Behaviour |
|---|---|
MUTABLE | All tags can be overwritten |
IMMUTABLE | No tag can be overwritten |
MUTABLE_WITH_EXCLUSION | Tags are mutable except those matching the filters, which are immutable |
IMMUTABLE_WITH_EXCLUSION | Tags are immutable except those matching the filters, which stay mutable |
# Immutable repository where only "latest" may move
aws ecr put-image-tag-mutability \
--repository-name app \
--image-tag-mutability IMMUTABLE_WITH_EXCLUSION \
--image-tag-mutability-exclusion-filters filterType=WILDCARD,filter=latest
The filter type is WILDCARD, so filter=dev-* works. Immutability is the compliance answer to “ensure a deployed tag can never be changed to point at different code”, and pairs with deploying by digest in task definitions for the strongest guarantee. Remember the two interactions covered above: immutability blocks pull through cache refreshes and strips duplicate tags during replication.
Image Scanning: Basic vs Enhanced
Scanning type is chosen at the registry level, and switching between the two discards the established scans of the type you leave (they come back if you switch back).
| Basic scanning | Enhanced scanning | |
|---|---|---|
| Engine | AWS native technology against the CVE database (the older generation used the open-source Clair engine) | Amazon Inspector |
| Finds | OS package vulnerabilities only | OS and programming language package vulnerabilities |
| Frequencies | Manual and scan on push | Scan on push and continuous scan (manual scans are not supported) |
| Rescans when new CVEs appear | No | Yes, continuously, for a configurable duration (default: until the image is deleted or the feature is disabled) |
| Rate limit | 1 scan per image per 24 hours; 100,000 basic scans per Region per 24 hours | Governed by Inspector |
| Cost | Included in ECR | No ECR charge; Inspector bills per image scanned |
| Findings | describe-image-scan-findings, EventBridge ECR Image Scan event | ECR console, describe-image-scan-findings, Inspector console, EventBridge Inspector2 Finding events, Security Hub |
| Extra context | — | Shows which ECS and EKS clusters are using the image and when it was last used |
Facts that turn into questions:
- Enhanced scanning uses repository filters with wildcards. Repositories that match no filter have scan frequency
Offand are not scanned. If a repository matches both a scan-on-push filter and a continuous-scan filter, continuous wins. - When you first enable enhanced scanning, Inspector only recognises images pushed in the last 14 days. Older images show
SCAN_ELIGIBILITY_EXPIRED; re-push them to scan them. The same status appears when the configured rescan duration lapses. - The current version of basic scanning does not populate
imageScanFindingsSummaryinDescribeImages; useDescribeImageScanFindings. - Archived images cannot be scanned.
- Best practice is to configure scanning at the registry, not per repository.
aws ecr put-registry-scanning-configuration \
--scan-type ENHANCED \
--rules '[{"repositoryFilters":[{"filter":"prod/*","filterType":"WILDCARD"}],"scanFrequency":"CONTINUOUS_SCAN"},
{"repositoryFilters":[{"filter":"*","filterType":"WILDCARD"}],"scanFrequency":"SCAN_ON_PUSH"}]'
The DOP-C02 pattern that combines Domains 5 and 6 is: enhanced scanning → EventBridge rule matching Inspector2 Finding with severity: CRITICAL → SNS to the security team and a Lambda that tags the image or blocks the deployment stage. Our Security & Compliance Automation guide covers the remediation half and the EventBridge advanced routing post covers the routing half. In CodePipeline, the natural gate is a stage condition or a test action after the build that calls describe-image-scan-findings and fails on critical counts.
Repository Creation Templates
ECR creates repositories on your behalf in three situations: the first pull through a cache rule, replication into a Region or account where the repository does not exist, and (if enabled) create on push. Without a template, pull through cache and replication create repositories with defaults: mutable tags, AES256, no repository policy, no lifecycle policy, no tags. A push to a non-existent repository fails unless a create-on-push template matches.
A repository creation template fixes that by defining the settings ECR applies at creation time only:
| Parameter | Notes |
|---|---|
prefix | Namespace prefix; an implied / is appended (prod matches prod/...). The longest matching prefix wins. ROOT matches every repository with no other matching template |
appliedFor | PULL_THROUGH_CACHE, CREATE_ON_PUSH, REPLICATION (any combination) |
customRoleArn | IAM role ECR assumes; required when the template sets resource tags or KMS encryption, otherwise creation fails |
imageTagMutability | Defaults to MUTABLE; recommended for pull through cache templates so the cache can refresh |
encryptionConfiguration | AES256 or KMS (with optional customer managed key); dual-layer KMS is GovCloud only |
repositoryPolicy, lifecyclePolicy, resourceTags | Applied to every new repository under the prefix |
aws ecr create-repository-creation-template \
--prefix prod \
--applied-for CREATE_ON_PUSH REPLICATION \
--image-tag-mutability IMMUTABLE \
--encryption-configuration encryptionType=KMS,kmsKey=arn:aws:kms:us-east-1:111122223333:key/1234abcd-... \
--custom-role-arn arn:aws:iam::111122223333:role/ECRTemplateRole \
--lifecycle-policy file://lifecycle.json
Scenario: “an organisation requires every new repository created by replication in the DR Region to be immutable and encrypted with a customer managed KMS key, with no manual steps”. The answer is a repository creation template in the destination registry with appliedFor: REPLICATION, a KMS encryption configuration and a custom role, because encryption cannot be changed after creation and replication does not copy settings. Templates never affect existing repositories.
Registry Policies vs Repository Policies
ECR has two resource-based policy layers and the exam checks that you can tell them apart.
| Registry permissions policy | Repository policy | |
|---|---|---|
| Scope | The whole private registry in one Region | One repository |
| Typical grants | ecr:ReplicateImage, ecr:CreateRepository, ecr:BatchImportUpstreamImage | ecr:BatchGetImage, ecr:GetDownloadUrlForLayer, ecr:BatchCheckLayerAvailability, push actions |
| Who you grant to | Another account (replication source) or your own principals (pull through cache scoping) | Accounts, roles or services that need to pull or push |
| CLI | put-registry-policy, get-registry-policy, delete-registry-policy | set-repository-policy, get-repository-policy |
Cross-account pull is a repository policy problem: the repository owner allows the other account’s principals ecr:BatchGetImage and ecr:GetDownloadUrlForLayer, and the pulling principal still needs ecr:GetAuthorizationToken in its own identity policy, because that action is registry-wide (resource *) and cannot be granted by a repository policy. Cross-account replication is a registry policy problem on the destination. A question that mixes the two (“add a repository policy on the source so the destination account can replicate”) is describing something that does nothing.
For ECS, the task execution role needs the pull permissions; for EKS, the node instance role or a pod identity does; for Lambda container images, the function’s resource policy on the repository must allow the Lambda service. For Kubernetes clusters outside AWS, the cluster uses a kubelet credential provider or an image pull Secret, which our CKAD image-pull internals post explains from the Kubernetes side.
Private Pulls: The Three Endpoints
An image pull from a private subnet with no internet route needs three endpoints, and questions that give you only two are testing which one is missing.
| Endpoint | Type | Used for |
|---|---|---|
com.amazonaws.<region>.ecr.api | Interface | ECR API calls: GetAuthorizationToken, BatchGetImage, DescribeImages, CreateRepository |
com.amazonaws.<region>.ecr.dkr | Interface, private DNS must be enabled | Docker Registry API: docker push, docker pull |
com.amazonaws.<region>.s3 | Gateway | Downloading the layers, which ECR stores in prod-<region>-starport-layer-bucket |
Add com.amazonaws.<region>.logs if Fargate tasks use the awslogs driver without internet access, and the Secrets Manager or SSM endpoints if the task definition injects secrets. Fargate platform version 1.4.0 and later needs both ECR endpoints; 1.3.0 and earlier needed only ecr.dkr. The endpoint security group must allow inbound 443 from the subnets, and an endpoint policy can restrict which roles may pull or deny ecr:DeleteRepository for a specific repository. And, once more: the first pull through a pull through cache rule still needs an internet route.
Everyday Mechanics the Exam Still Checks
aws ecr get-login-password | docker login --username AWS --password-stdin <registry>issues a token valid for 12 hours;GetAuthorizationTokenis rate-limited at 500 requests per second per Region and is the API that fails first when a large fleet starts at once. Use the credential helper or pull via instance/task roles rather than caching tokens in build scripts.- A push is a sequence of
BatchCheckLayerAvailability(skip existing layers),InitiateLayerUpload+UploadLayerPart+CompleteLayerUploadper new layer, then onePutImagefor the manifest.PutImageis limited to 10 per second, so a CI farm pushing hundreds of tags simultaneously hits throttling there first. - Layers can be up to 52,000 MiB; a repository holds up to 100,000 images (adjustable); an image can carry 1,000 tags.
- ECR stores OCI artifacts as well as images: Helm charts (
helm push chart.tgz oci://...), SBOMs and signatures as referrer artifacts. AWS Signer can sign container images in ECR, and the Kubernetes side of verifying those signatures is in our CKS image signing post. - ECR emits EventBridge events for image pushes and deletes (
ECR Image Action), basic scan completion (ECR Image Scan), replication (ECR Replication Action), pull through cache imports (ECR Pull Through Cache Action) and scan-frequency changes (ECR Scan Resource Change). An “automatically deploy when a new tag is pushed” scenario is an EventBridge rule onECR Image Actionwithaction-type: PUSHstarting CodePipeline; the CodePipeline V2 post covers the ECR source action alternative. - ECR Public is a separate public registry (
public.ecr.aws) with its own namespace of aliases; it is an upstream for pull through cache, not a replication target. - Encryption at rest is always on: AES256 (SSE-S3 managed) by default, or KMS with the AWS managed key or a customer managed key, chosen at creation only.
Scenario Drill: Cue → Answer
| Cue in the question | Mechanism | Answer |
|---|---|---|
| Docker Hub rate limits are breaking builds | Pull through cache | Create a rule with a Secrets Manager secret named ecr-pullthroughcache/...; pull via the private registry URI |
| Cached image is up to a day behind upstream | 24-hour refresh window | Expected behaviour; pull by digest for exact versions |
| Pull through cache stopped updating after a security change | Tag immutability enabled on the cached repo | Keep cached repositories MUTABLE (or use exclusion filters) |
| First pull via cache fails in a VPC with ECR endpoints only | First pull needs internet | Add a NAT gateway route for the first pull |
| Lambda container image through pull through cache | Unsupported | Push the image into a normal private repository |
| Cross-account replication never happens, no errors | Destination registry policy missing | Add ecr:ReplicateImage + ecr:CreateRepository for the source account in the destination |
| Images pushed before replication was enabled are missing | Only future pushes replicate | Use replication backfill (or re-push) |
| A → B → C chain, C never receives images | One hop per push | Add C as a destination of A’s rule |
| Destination repositories lack immutability/KMS | Settings are not replicated | Repository creation template with appliedFor: REPLICATION in the destination |
| Replicated image arrives untagged | Immutable destination tag already existed | Expected; avoid duplicate tags or keep destination mutable |
| Lifecycle policy deleted the newest prod image | Lower-priority catch-all or wrong rule order | Reorder: specific rules first, tagStatus: any last; run the preview |
Rule with ["alpha*","beta*"] matches fewer images than expected | All patterns must match | Split into two rules |
tagPrefixList rejected with tagStatus: untagged | Prefix/pattern lists require tagged | Remove the list or change tagStatus |
| Need to retain images cheaply for years | Archive storage class | transition to archive; 90-day minimum; restore within 20 minutes before pulling |
| Deployed tag must never change | Tag immutability | IMMUTABLE (or IMMUTABLE_WITH_EXCLUSION to keep latest floating) |
| Need language-package CVEs, continuous rescans, Security Hub | Enhanced scanning | put-registry-scanning-configuration --scan-type ENHANCED with filters |
Old images show SCAN_ELIGIBILITY_EXPIRED right after enabling | 14-day lookback | Re-push the images |
| Repository matches both scan-on-push and continuous filters | Continuous wins | Expected |
| All new repositories must be KMS-encrypted with tags | Encryption fixed at creation | Repository creation template with KMS + customRoleArn; ROOT prefix for everything |
docker push to a new repository name fails | No create-on-push template | Create the repository or a CREATE_ON_PUSH template |
Private subnet pull fails although ecr.api and ecr.dkr exist | S3 gateway endpoint missing | Add com.amazonaws.<region>.s3 gateway endpoint |
| Fleet start-up throttled before pulls begin | GetAuthorizationToken 500/s | Request a quota increase; stagger; use roles not cached tokens |
| Deploy automatically on image push | EventBridge ECR Image Action | Rule → CodePipeline / Lambda |
Common Mistakes
- Treating pull through cache as a real-time proxy. It is a cache with a 24-hour validation window; stale mutable tags are by design.
- Writing a source-side policy for cross-account replication. Only the destination’s registry policy matters.
- Expecting replication to copy lifecycle policies, repository policies or encryption settings. It copies images; templates copy settings.
- Putting the
tagStatus: anyrule first. It claims every image and the specific rules do nothing. - Thinking the lifecycle evaluator runs immediately. Expect up to 24 hours; the same window applies to scheduled scans and cache refreshes.
- Confusing basic scan-on-push (repository setting) with enhanced scanning (registry setting with filters).
- Forgetting the S3 gateway endpoint. Two ECR interface endpoints get you the manifest, not the layers.
- Assuming encryption can be changed later. It cannot; plan with templates or IaC.
How to Practice
Build a small lab in a sandbox account: create a pull through cache rule for ECR Public, pull public.ecr.aws/amazonlinux/amazonlinux through it and inspect the created repository; enable cross-Region replication with a PREFIX_MATCH filter, push an image and watch describe-image-replication-status; write a three-rule lifecycle policy and run the preview against a repository with mixed tags; then flip a repository to IMMUTABLE_WITH_EXCLUSION and try to overwrite a tag. An afternoon of this makes every row in the drill table obvious.
Then test the recall under exam conditions. The AWS Certified DevOps Engineer - Professional (DOP-C02) Mock Exam Bundle has eight 75-question timed exams with explanations that spell out which ECR layer, which account and which timer a scenario hinges on, which is exactly the kind of distinction this exam uses to separate “has used ECR” from “understands ECR”. Pair it with the DOP-C02 study plan and our free practice questions to see where container-registry questions sit in your weak spots.
Frequently Asked Questions
How often does an ECR pull through cache check the upstream registry?
At most once every 24 hours per tag. When you pull a cached tag, ECR checks whether it validated that tag upstream within the last 24 hours; if so it serves the cache without contacting the upstream, otherwise it checks for a newer version and updates the cache. Referrer artifacts use a 6-hour window. If the upstream is unreachable, the last cached image is served.
Which account needs a policy for cross-account ECR replication?
Only the destination account. It must have a registry permissions policy granting the source account ecr:ReplicateImage and ecr:CreateRepository. The source account configures the replication rules and needs nothing else; source repositories do not need repository policies for replication.
Does ECR replication copy lifecycle policies and tag immutability settings?
No. Replication copies images only. Repository policies, lifecycle policies and repository settings such as tag mutability and encryption are not replicated. Use a repository creation template with appliedFor: REPLICATION in the destination registry to apply settings to repositories that replication creates.
Why did a lower-priority lifecycle rule not expire an image it matched?
Because the image also matched a higher-priority rule’s tagging requirements. The evaluator applies rules in priority order, and an image seen by a higher-priority rule cannot be expired by a lower-priority one, even if the higher-priority rule kept it. Reorder the rules or narrow the selections, and always run the lifecycle policy preview first.
What is the difference between ECR basic and enhanced scanning?
Basic scanning uses AWS native technology to find OS package vulnerabilities, supports manual and scan-on-push frequencies, and is limited to one scan per image per 24 hours. Enhanced scanning integrates Amazon Inspector, finds OS and programming language package vulnerabilities, supports scan-on-push and continuous rescanning, publishes findings to Inspector, EventBridge and Security Hub, and is billed by Inspector.
Can I make only some tags immutable in an ECR repository?
Yes, with exclusion filters. IMMUTABLE_WITH_EXCLUSION makes every tag immutable except those matching wildcard filters (for example latest), and MUTABLE_WITH_EXCLUSION does the reverse. Plain IMMUTABLE applies to all tags and returns ImageTagAlreadyExistsException on a duplicate push.
Which VPC endpoints does a private image pull from ECR need?
Three: the ecr.api interface endpoint for the ECR API, the ecr.dkr interface endpoint (with private DNS enabled) for the Docker Registry API, and an S3 gateway endpoint because image layers are stored in S3. Fargate tasks that log to CloudWatch also need the logs endpoint.
How long do archived ECR images have to stay archived?
A minimum of 90 days. Lifecycle policies cannot expire an image archived for less than 90 days, and deleting earlier through the API still bills the minimum. Archived images cannot be pulled or scanned; a restore completes within about 20 minutes and the restored image behaves like a newly pushed one.
Conclusion
ECR questions on the DOP-C02 are layered questions: a setting lives at the registry, the repository or the image; a policy belongs to the source or the destination; a timer is 24 hours, 30 minutes, 20 minutes or 90 days. Pull through cache rules sync upstream registries with a 24-hour validation window and need a specially named secret, mutable tags and an internet route for the first pull. Replication is registry-level, destination-authorised, one hop, future-only and copies images but never settings. The lifecycle evaluator applies rules by priority with the “seen by a higher rule” protection that makes rule order decisive, and it can archive as well as expire. Tag immutability now has exclusion filters, scanning is a registry-level choice between AWS native basic scanning and Inspector-powered enhanced scanning, repository creation templates fix the settings replication and caching would otherwise leave at defaults, and every private pull needs two interface endpoints plus the S3 gateway. Learn the mechanism behind each fact and the scenarios resolve themselves.