Explain it simply
Explain it simply
ECR (Elastic Container Registry) is a private Docker registry inside your AWS account. You push and pull images like with Docker Hub, but access is controlled with IAM and ECS, EKS and Lambda pull from it directly.
Image security means being able to answer three questions: what is inside the image (any vulnerable packages?), have we removed what we don't need, and is what runs in production exactly the image we built? Think of ECR as a warehouse, scanning as the guard who inspects every delivery, and tag immutability as a label nobody can peel off a box and stick on a different one.
Problem → Why → Solution
The problem — one ':latest' tag and nobody knows what is running
A team pushes every CI build as :latest. One day the ECS service scales out and two new tasks pull :latest — but code that was merged a minute ago, and not yet tested, has already overwritten :latest. One service now runs two versions of the code and about half the requests fail. When they try to roll back, nobody knows which image 'the previous :latest' was.
Meanwhile thousands of untagged images have piled up in the repository and the storage bill keeps rising. When a critical CVE is announced, nobody can say which images are affected.
REGISTRY=111122223333.dkr.ecr.us-east-1.amazonaws.com
docker build -t $REGISTRY/orders-api:latest .
docker push $REGISTRY/orders-api:latest # overwrites yesterday's :latest
aws ecs update-service --cluster demo-cluster --service orders-api \
--force-new-deployment # "deploy whatever latest is now"
aws ecr describe-images --repository-name orders-api \
--filter tagStatus=UNTAGGED --query 'length(imageDetails)'
# 1874Why this happens
A tag is just a movable pointer; an image's real identity is its sha256 digest. Repositories are mutable by default, so a tag can be overwritten and the old image is left behind untagged. Without a lifecycle policy, nothing ever deletes those.
Core concept — registry, tags, digests, lifecycle and scanning
- Image digest
- The sha256 hash of an image manifest (for example sha256:4f1c...). Change one byte of content and the digest changes, so pulling by digest always returns exactly one image.
Each account has one private registry per region (111122223333.dkr.ecr.us-east-1.amazonaws.com), and you create repositories inside it. The Docker client knows nothing about IAM, so 'aws ecr get-login-password' uses your IAM credentials to mint a token valid for 12 hours and pipes it into docker login. ECS and EKS do this automatically with the execution role or node role.
With tag immutability set to IMMUTABLE, pushing an existing tag again is rejected. A tag such as a git SHA then always points to one image. Deploying by digest is even more precise.
IMAGE SUPPLY CHAIN WITH ECR
---------------------------
CI build ECR repo: orders-api (IMMUTABLE, KMS)
+---------+ push +------------------------------------------+
| git sha |-------->| 3f9a2c1 -> sha256:4f1c.. scan: 0 CRIT |
| 3f9a2c1 | | 8b7e0d4 -> sha256:a90e.. scan: 1 HIGH |
+---------+ | <untagged> x 40 --lifecycle--> expired |
+----------------+-------------------------+
| pull by digest
Inspector (enhanced) ----+ re-scans on new CVEs
v
ECS task / EKS pod / LambdaA lifecycle policy evaluates rules in ascending rulePriority order and expires old images automatically, with rules such as 'delete untagged images older than 7 days' or 'keep only the 30 newest images tagged release-'. Expiry runs asynchronously in the background, so images don't vanish instantly.
Scanning comes in two flavours. Basic scanning checks OS package vulnerabilities once, at push time (or on demand). Enhanced scanning integrates with Amazon Inspector and covers language packages — Python, Java, Node.js and more — as well as OS packages. It re-scans existing images whenever a new CVE is published, which is what lets you answer 'which images does this CVE affect?'.
| Basic scanning | Enhanced (Inspector) | |
|---|---|---|
| Packages covered | OS packages | OS and language packages |
| When it scans | On push or on demand | On push, then continuously as CVEs appear |
| Cost | No extra charge | Inspector charges per image scanned |
Immutability has a trade-off too. Some tools expect to move a tag such as 'prod' or 'stable' onto a new image as their deploy step. That workflow can't work in an immutable repository, so the pipeline has to deploy by digest or by a new version tag instead. It feels like extra work at first, and it pays for itself the first day you need to roll back.
- Build + tag with git SHA
- Push to IMMUTABLE repo
- Scan (Inspector re-scans)
- Deploy by digest
- Lifecycle expires the rest
Tags are for humans; digests are what machines should trust.
A lifecycle policy
{
"rules": [
{
"rulePriority": 1,
"description": "Delete untagged images 7 days after push",
"selection": {
"tagStatus": "untagged",
"countType": "sinceImagePushed",
"countUnit": "days",
"countNumber": 7
},
"action": { "type": "expire" }
},
{
"rulePriority": 2,
"description": "Keep the 30 newest release images",
"selection": {
"tagStatus": "tagged",
"tagPrefixList": ["release-"],
"countType": "imageCountMoreThan",
"countNumber": 30
},
"action": { "type": "expire" }
},
{
"rulePriority": 3,
"description": "Keep at most 200 images of any kind",
"selection": {
"tagStatus": "any",
"countType": "imageCountMoreThan",
"countNumber": 200
},
"action": { "type": "expire" }
}
]
}Rule 1 deletes untagged images 7 days after push. Rule 2 uses 'tagged', which requires a tagPrefixList (or tagPatternList), and keeps only the 30 newest release- images. The rule with tagStatus 'any' must have the highest rulePriority number (it runs last) or the policy is rejected. Before applying, run start-lifecycle-policy-preview to see exactly what would be expired.
A hardened repository and a push-scan-deploy flow
This script is shaped like a CI pipeline step. It creates the repository with immutable tags, scan on push and KMS encryption, and attaches the lifecycle policy. Then it tags the build with the git SHA, pushes it, waits for the scan, reads the severity counts and finally prints the digest to deploy. Creating the repository is a one-time step — keep it in IaC in practice.
#!/usr/bin/env bash
set -euo pipefail
REGION=us-east-1
REPO=orders-api
REGISTRY=111122223333.dkr.ecr.$REGION.amazonaws.com
TAG=$(git rev-parse --short HEAD)
aws ecr create-repository --repository-name $REPO \
--image-tag-mutability IMMUTABLE \
--image-scanning-configuration scanOnPush=true \
--encryption-configuration encryptionType=KMS
aws ecr put-lifecycle-policy --repository-name $REPO \
--lifecycle-policy-text file://lifecycle.json
aws ecr get-login-password --region $REGION \
| docker login --username AWS --password-stdin $REGISTRY
docker build --platform linux/arm64 -t $REGISTRY/$REPO:$TAG .
docker push $REGISTRY/$REPO:$TAG
aws ecr wait image-scan-complete --repository-name $REPO --image-id imageTag=$TAG
aws ecr describe-image-scan-findings --repository-name $REPO \
--image-id imageTag=$TAG \
--query 'imageScanFindings.findingSeverityCounts'
DIGEST=$(aws ecr describe-images --repository-name $REPO \
--image-ids imageTag=$TAG --query 'imageDetails[0].imageDigest' --output text)
echo "deploy: $REGISTRY/$REPO@$DIGEST"Code breakdown
- create-repository
--image-tag-mutability IMMUTABLE --encryption-configuration encryptionType=KMSMakes tags impossible to overwrite and encrypts layers with the AWS managed KMS key (the default is AES-256). With a customer managed key, every role that pulls also needs kms:Decrypt in the key policy.
- get-login-password
| docker login --username AWS --password-stdin $REGISTRYThe username is always 'AWS', and passing the password on stdin keeps it out of shell history. The token lasts 12 hours.
- tag = git SHA
TAG=$(git rev-parse --short HEAD)Ties each image to one commit. Because the repository is immutable, pushing the same SHA twice fails with a 'tag already exists' error.
- wait + scan findings
aws ecr wait image-scan-complete ...Waits for the scan, then reads finding counts by severity. CI pipelines commonly fail the build if any CRITICAL finding appears.
- digest
--query 'imageDetails[0].imageDigest'Put repo@sha256:... into the task definition or Kubernetes manifest, so what runs is guaranteed to be exactly the image that was scanned.
Sample output (scan results and digest will differ):
{
"HIGH": 1,
"MEDIUM": 4,
"LOW": 9
}
deploy: 111122223333.dkr.ecr.us-east-1.amazonaws.com/orders-api@sha256:4f1c9e...Turning on enhanced scanning for the whole registry
Scanning configuration is set at the registry level, per region. Choose ENHANCED and registry rules replace each repository's scanOnPush setting. Repositories matched with CONTINUOUS_SCAN are re-scanned by Inspector as new CVEs are published, and findings flow to the Inspector console, Security Hub and EventBridge. Continuous scanning of a registry full of old images raises the Inspector bill, so pair it with lifecycle policies.
aws inspector2 enable --resource-types ECR
cat > scan-rules.json <<'EOF'
[
{
"scanFrequency": "CONTINUOUS_SCAN",
"repositoryFilters": [{ "filter": "prod-*", "filterType": "WILDCARD" }]
},
{
"scanFrequency": "SCAN_ON_PUSH",
"repositoryFilters": [{ "filter": "*", "filterType": "WILDCARD" }]
}
]
EOF
aws ecr put-registry-scanning-configuration --scan-type ENHANCED \
--rules file://scan-rules.jsonPull-through cache — public images through your own registry
Pulling base images straight from Docker Hub risks rate limits, breaks builds when the upstream is down, and needs NAT for private subnets. With a pull-through cache rule you pull upstream images through your own ECR URL: on the first pull ECR fetches the image and stores it as a new repository in your registry. Later pulls come from ECR, which re-checks the upstream periodically.
Upstreams such as ECR Public, registry.k8s.io and Quay need no authentication. Docker Hub and GitHub Container Registry need a credential stored in Secrets Manager with the 'ecr-pullthroughcache/' name prefix, passed by ARN. Cached images are then covered by your own scanning and lifecycle rules, so third-party images get inspected too.
REGISTRY=111122223333.dkr.ecr.us-east-1.amazonaws.com
SECRETS=arn:aws:secretsmanager:us-east-1:111122223333:secret
aws ecr create-pull-through-cache-rule --ecr-repository-prefix ecr-public \
--upstream-registry-url public.ecr.aws
aws ecr create-pull-through-cache-rule --ecr-repository-prefix docker-hub \
--upstream-registry-url registry-1.docker.io \
--credential-arn "$SECRETS:ecr-pullthroughcache/docker-hub-AbCdEf"
# <prefix>/<upstream repository path>:<tag>
docker pull $REGISTRY/ecr-public/nginx/nginx:stable
docker pull $REGISTRY/docker-hub/library/python:3.12-slimPermissions for the first pull
If the cache repository doesn't exist yet, the identity doing the first pull needs ecr:CreateRepository and ecr:BatchImportUpstreamImage. Give those to the CI role and keep runtime roles at plain pull permissions.
Cross-account pulls
In a multi-account setup, images are usually built in a shared-services or tooling account and pulled by the dev, staging and prod accounts. Both sides must allow it: the repository policy (a resource policy) in the image account must grant the prod account pull access, and the prod role's identity policy must also allow pulling that repository plus ecr:GetAuthorizationToken. To allow a whole organization, use Principal '*' with an aws:PrincipalOrgID condition.
# in the image account (111122223333): let the prod account pull
cat > repo-policy.json <<'EOF'
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ProdPull",
"Effect": "Allow",
"Principal": { "AWS": "arn:aws:iam::444455556666:root" },
"Action": [
"ecr:BatchGetImage",
"ecr:GetDownloadUrlForLayer",
"ecr:BatchCheckLayerAvailability"
]
}
]
}
EOF
aws ecr set-repository-policy --repository-name orders-api \
--policy-text file://repo-policy.json{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "EcrToken",
"Effect": "Allow",
"Action": "ecr:GetAuthorizationToken",
"Resource": "*"
},
{
"Sid": "PullOrdersApi",
"Effect": "Allow",
"Action": [
"ecr:BatchGetImage",
"ecr:GetDownloadUrlForLayer",
"ecr:BatchCheckLayerAvailability"
],
"Resource": "arn:aws:ecr:us-east-1:111122223333:repository/orders-api"
}
]
}Minimal base images and image signing
The fastest way to cut vulnerabilities is to ship fewer packages. In a multi-stage build, compilers and build tools live only in the first stage, and the runtime stage is based on an image with no shell or package manager, such as distroless or scratch. A full OS image can carry hundreds of CVEs; a distroless static image usually has a handful. The trade-off is that without a shell, ECS Exec and CMD-SHELL health checks stop working — rely on ALB health checks instead.
Image signing proves 'our pipeline really built this image'. AWS Signer can sign ECR images with Notation (the Notary Project), and tools such as Sigstore cosign can also store signatures in ECR as OCI artifacts. Verifying signatures at deploy time (for example with an EKS admission controller) is a separate piece of setup.
# build stage: full toolchain, never shipped
FROM golang:1.24 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" \
-o /out/orders-api ./cmd/orders-api
# runtime stage: no shell, no package manager, runs as non-root
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/orders-api /orders-api
USER nonroot:nonroot
EXPOSE 8080
ENTRYPOINT ["/orders-api"]In production
How teams run this in production
Most organizations keep ECR repositories in one shared-services account, and only the CI pipeline may push. Workload accounts can only pull, through an organization-wide repository policy. Developers cannot push to production repositories from their laptops — one of the most important supply-chain controls there is.
Pipelines include a scan gate: a CRITICAL finding blocks the deploy, and findings with no fix yet get a time-limited suppression rule in Inspector. Enhanced scanning's EventBridge events are routed to Slack or a ticketing system, so the owning team hears directly when a new CVE affects an image running in production. For multi-region deployments, a replication configuration copies images between regions automatically, avoiding cross-region pull cost and latency.
- Repositories are named team/service (payments/orders-api), and IAM policies use prefix wildcards to scope access per team.
- Repository creation templates keep immutability, encryption and lifecycle settings consistent even for repositories created automatically by pull-through cache or replication.
- A scheduled pipeline rebuilds images monthly, or when a new base-image CVE lands, so images get refreshed even when app code hasn't changed.
Common mistakes
Common mistakes
Mistake 1 — only the repository policy, and cross-account pulls still fail
The repository policy is in place in the image account, yet pulls from the prod account fail with 'no basic auth credentials' or AccessDenied. Cross-account access needs both a resource policy and an identity policy — without the pull actions and ecr:GetAuthorizationToken on the prod role, it fails. If the repository uses a customer managed KMS key, the key policy must also grant the prod role kms:Decrypt.
Mistake 2 — a lifecycle policy deletes an image that is still running
A simple 'tagStatus any, keep the last 20' rule on a busy repository can delete, within weeks, the image a slow-moving service still runs. Running tasks are unaffected, but the next scale-out or task replacement fails with CannotPullContainerError. Keep generous counts for release images and always run a lifecycle preview before applying.
Mistake 3 — scanning without acting
Scan on push is worthless if nobody reads the findings. And basic scanning checks only once, at push, so an image that was 'clean' four months ago may carry a critical CVE today. Use a CI gate, continuous scanning and alert routing so findings reach an owner.
Best practices
Best practices
- Make every repository IMMUTABLE, tag with the git SHA and deploy by digest.
- Give every repository a lifecycle policy with at least an untagged-cleanup rule.
- Enable enhanced continuous scanning on production repositories.
- Pull third-party base images only through a pull-through cache.
- Build runtime images on distroless or another minimal base, running as non-root.
💰 Cost & Cleanup
ECR charges per GB-month stored and for data transferred out to other regions or the internet; pulls by ECS or EKS in the same region carry no transfer charge. The free tier includes a small amount of private storage for the first 12 months. Basic scanning is free; enhanced scanning is billed by Amazon Inspector per image scanned. After the lab, delete the repository, the pull-through cache rules and any repositories the cache created, and switch enhanced scanning off. Check the pricing pages for exact rates.
Clean up when you are done
aws ecr delete-repository --repository-name orders-api --force
aws ecr delete-pull-through-cache-rule --ecr-repository-prefix ecr-public
aws ecr delete-pull-through-cache-rule --ecr-repository-prefix docker-hub
aws ecr delete-repository --repository-name ecr-public/nginx/nginx --force
aws ecr delete-repository --repository-name docker-hub/library/python --force
aws ecr put-registry-scanning-configuration --scan-type BASIC
aws inspector2 disable --resource-types ECRMini challenge
Mini challenge — a lifecycle policy for PR builds
A repository receives one image per pull request (tag pr-<number>-<sha>) and its storage is ballooning. Write a lifecycle policy and check it with a preview.
- Expire untagged images 1 day after push
- Expire images tagged pr- 14 days after push
- Cap the repository at 300 images of any tag
- Valid JSON, with the 'any' rule at the last priority
Expected: get-lifecycle-policy-preview lists untagged images and pr- images older than 14 days as EXPIRE, and no release images.
Show hint
For the pr- rule, use countType 'sinceImagePushed' with a tagPrefixList. Try it with 'aws ecr start-lifecycle-policy-preview' before applying.
Show solution
{
"rules": [
{
"rulePriority": 1,
"description": "Untagged: 1 day",
"selection": {
"tagStatus": "untagged",
"countType": "sinceImagePushed",
"countUnit": "days",
"countNumber": 1
},
"action": { "type": "expire" }
},
{
"rulePriority": 2,
"description": "PR images: 14 days",
"selection": {
"tagStatus": "tagged",
"tagPrefixList": ["pr-"],
"countType": "sinceImagePushed",
"countUnit": "days",
"countNumber": 14
},
"action": { "type": "expire" }
},
{
"rulePriority": 10,
"description": "Hard cap: 300 images",
"selection": {
"tagStatus": "any",
"countType": "imageCountMoreThan",
"countNumber": 300
},
"action": { "type": "expire" }
}
]
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- get-login-password mints a 12-hour token and pipes it into docker login.
- IMMUTABLE tags + git SHA + deploy by digest = you always know what is running.
- Lifecycle rules run in priority order, and the 'any' rule must come last.
- Enhanced scanning (Inspector) covers language packages and keeps re-scanning against new CVEs.
- Cross-account pulls need both the repository policy and an identity policy.
Amazon ECR User Guide — AWS Documentation
Lifecycle policies in Amazon ECR — AWS Documentation
Scan images for vulnerabilities in Amazon ECR — AWS Documentation