Skip to main content

Managing Container Images with Amazon ECR

Store, scan and manage container images in Amazon ECR with immutable tags, lifecycle policies, cross-account access and pull-through cache.

Overview and What You Will Learn

Amazon Elastic Container Registry (ECR) is AWS's managed registry for container images. Images are stored privately in your account, access is controlled by IAM, and ECS, EKS and CodeBuild pull from it over the AWS network. A well-run ECR setup uses immutable tags, vulnerability scanning, lifecycle policies that expire old images, and a pull-through cache for public base images.

In this lab you will:

  • Create a private repository with immutable tags and scan on push
  • Authenticate, build, tag and push an image, and see immutability reject a duplicate tag
  • Read scan findings and understand basic versus enhanced scanning
  • Define a lifecycle policy and a cross-account pull policy as code
  • Set up a pull-through cache for public images
  • Diagnose the most common ECS and EKS image pull failures

Why This Matters in Production

Every team running containers needs a place to keep images. A public registry is an external dependency: pulls can be rate limited, an outage there blocks your deployments, and your images may be visible to others. ECR keeps images in your account and Region with IAM authentication, so a deployment never depends on a third party being available. A platform team at a company like Hotstar or Razorpay, deploying many services many times a day, also needs old images cleaned up automatically and tags that cannot be overwritten, so a rollback target always exists.

Core Principles

A registry belongs to one account in one Region, and holds many repositories, one per application. Each repository stores images identified by tags and by immutable digests, and shares identical layers so repeated pushes upload only what changed.

flowchart LR CI[CI pipeline
build and test] -->|docker push| R[(ECR repository)] R --> SC[Scan on push] R --> LC[Lifecycle policy
expires old images] R -->|pull| ECS([ECS tasks]) R -->|pull| EKS([EKS pods]) UP[Docker Hub or Quay] -->|pull-through cache| R classDef ci fill:#EDE9FE,color:#1E293B classDef reg fill:#326CE5,color:#FFFFFF classDef run fill:#10B981,color:#FFFFFF classDef ext fill:#F1F5F9,color:#1E293B class CI ci class R,SC,LC reg class ECS,EKS run class UP ext
Feature Purpose
Private repository Default, IAM-controlled storage
Public repository (ECR Public) Share open-source images at public.ecr.aws
Tag immutability Reject pushes that reuse an existing tag
Lifecycle policy Automatically expire images by age or count
Replication Copy images to other Regions or accounts

Detailed Step-by-Step Practical Lab

Milestone 1: Create the Repository

Create it with immutable tags and scanning from the start. Enabling lifecycle rules at creation avoids cleaning thousands of images later.

Bash
export AWS_REGION=ap-south-1
export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
export REGISTRY=${ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com
aws ecr create-repository \
--repository-name devops-orders-api \
--image-tag-mutability IMMUTABLE \
--image-scanning-configuration scanOnPush=true \
--encryption-configuration encryptionType=KMS

Data is encrypted at rest. KMS without a key ID uses the AWS managed key, and you can supply your own key for tighter control.

Milestone 2: Authenticate, Build and Push

ECR login tokens last 12 hours. The login endpoint is the registry host only, without a repository name.

Bash
aws ecr get-login-password --region $AWS_REGION | \
docker login --username AWS --password-stdin $REGISTRY
cat > Dockerfile << 'EOF'
FROM nginx:1.27-alpine
RUN echo "orders-api v1.0" > /usr/share/nginx/html/index.html
EOF
docker build -t devops-orders-api:v1.0 .
docker tag devops-orders-api:v1.0 $REGISTRY/devops-orders-api:v1.0
docker push $REGISTRY/devops-orders-api:v1.0

Layers that already exist in the repository are skipped, so repeated pushes are fast.

Milestone 3: See Immutability in Action

Without immutability, pushing v1.0 again silently replaces the earlier image, so a deployment that references that tag gets different code than you tested. With immutability the second push is rejected.

Bash
docker build --no-cache -t devops-orders-api:v1.0 .
docker push $REGISTRY/devops-orders-api:v1.0
# repository and cannot be overwritten because the repository is immutable

Publish every build as a new tag, usually the git commit SHA, plus a semantic version for releases. A repository with immutable tags cannot also hold a moving tag such as latest, so do not deploy latest. Reference an exact tag, or the image digest, in task definitions and manifests.

Bash
# Find the digest of what you pushed
aws ecr describe-images \
--repository-name devops-orders-api \
--image-ids imageTag=v1.0 \
--query "imageDetails[0].imageDigest" --output text
Milestone 4: Scan for Vulnerabilities

ECR offers two kinds of scanning. Basic scanning checks operating system packages against a CVE database when you push or on demand, and it is free. Enhanced scanning uses Amazon Inspector, covers operating system packages and application dependencies such as Python, Node.js and Java libraries, and scans continuously, so an image that was clean last month is flagged when a new CVE is published.

Bash
# Read results of the scan-on-push
aws ecr describe-image-scan-findings \
--repository-name devops-orders-api \
--image-id imageTag=v1.0 \
--query "imageScanFindings.findingSeverityCounts"
# Run a scan on demand (basic scanning)
aws ecr start-image-scan \
--repository-name devops-orders-api \
--image-id imageTag=v1.0
# Turn on enhanced scanning with continuous rescans for matching repositories
aws ecr put-registry-scanning-configuration \
--scan-type ENHANCED \
--rules 'scanFrequency=CONTINUOUS_SCAN,repositoryFilters=[{filter=devops-*,filterType=WILDCARD}]'

Enhanced scanning is configured for the whole registry, not per repository, and Inspector findings also appear in the Inspector console and EventBridge. In CI, fail the build on critical findings before pushing, using a scanner such as Trivy, and treat ECR scanning as the second line that catches new CVEs in images already deployed.

Milestone 5: Add a Lifecycle Policy and Cross-Account Access as Code

Lifecycle policies expire images automatically, and a repository policy shares images with other accounts. Both are best managed in code. This Terraform defines the repository, a lifecycle policy and a pull policy for a second account.

HCL
resource "aws_ecr_repository" "orders_api" {
name = "devops-orders-api"
image_tag_mutability = "IMMUTABLE"
image_scanning_configuration {
scan_on_push = true
}
}
resource "aws_ecr_lifecycle_policy" "orders_api" {
repository = aws_ecr_repository.orders_api.name
policy = jsonencode({
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 25 most recent release images"
selection = {
tagStatus = "tagged"
tagPrefixList = ["v"]
countType = "imageCountMoreThan"
countNumber = 25
}
action = { type = "expire" }
},
{
rulePriority = 3
description = "Keep the 50 most recent commit-tagged images"
selection = {
tagStatus = "any"
countType = "imageCountMoreThan"
countNumber = 50
}
action = { type = "expire" }
}
]
})
}
data "aws_iam_policy_document" "cross_account_pull" {
statement {
sid = "AllowPullFromAppAccount"
effect = "Allow"
principals {
type = "AWS"
identifiers = ["arn:aws:iam::987654321098:root"]
}
actions = [
"ecr:BatchGetImage",
"ecr:GetDownloadUrlForLayer",
"ecr:BatchCheckLayerAvailability",
]
}
}
resource "aws_ecr_repository_policy" "orders_api" {
repository = aws_ecr_repository.orders_api.name
policy = data.aws_iam_policy_document.cross_account_pull.json
}

Lifecycle rules are evaluated by priority, and a rule with tagStatus = "any" must have the highest priority number so it runs last. Preview a policy before you rely on it.

Bash
aws ecr start-lifecycle-policy-preview --repository-name devops-orders-api
aws ecr get-lifecycle-policy-preview --repository-name devops-orders-api

On the pulling side, the other account also needs its own IAM permission. Its role calls ecr:GetAuthorizationToken in its own account and the pull actions against your repository. For multi-account or multi-Region setups, ECR replication copies images automatically so each Region pulls locally.

Milestone 6: Cache Public Images with Pull-Through Cache

A pull-through cache stores copies of images from an upstream public registry in your ECR, so builds and deployments do not depend on that registry's availability or rate limits. Docker Hub requires credentials, which you store in a Secrets Manager secret whose name starts with ecr-pullthroughcache/ and which contains username and accessToken keys. Quay, ECR Public and the Kubernetes registry need no credentials.

Bash
# Docker Hub (credentials secret already created in Secrets Manager)
aws ecr create-pull-through-cache-rule \
--ecr-repository-prefix docker-hub \
--upstream-registry-url registry-1.docker.io \
--credential-arn arn:aws:secretsmanager:ap-south-1:123456789012:secret:ecr-pullthroughcache/docker-hub-AbCdEf
# Quay needs no credentials
aws ecr create-pull-through-cache-rule \
--ecr-repository-prefix quay \
--upstream-registry-url quay.io
# First pull fetches from upstream and caches it. Official images live under library/
docker pull $REGISTRY/docker-hub/library/nginx:1.27-alpine

Later pulls come from your ECR. Cached images can then be scanned and governed like your own, and ECR refreshes them from upstream periodically.

Milestone 7: Fix Image Pull Failures

Most ECS and EKS "cannot pull image" errors come from three causes: permissions, networking and tag mistakes.

Bash
# Is the image and tag really there?
aws ecr describe-images --repository-name devops-orders-api \
--query "imageDetails[].imageTags" --output text
# Which policy does the ECS task execution role carry?
aws iam list-attached-role-policies --role-name ecsTaskExecutionRole
  • Permissions: the ECS task execution role needs ecr:GetAuthorizationToken, ecr:BatchCheckLayerAvailability, ecr:GetDownloadUrlForLayer and ecr:BatchGetImage. The managed policy AmazonECSTaskExecutionRolePolicy includes them. For EKS, the node role or the pod identity needs the equivalent read access.
  • Networking: tasks and nodes in private subnets need a NAT gateway, or VPC endpoints for ecr.api, ecr.dkr and an S3 gateway endpoint, because image layers are served from S3.
  • Reference: the task definition must use the full image URI with an exact tag that exists. A typo, a deleted tag or a lifecycle rule that expired the image all produce the same error.
Milestone 8: Clean Up
Bash
aws ecr batch-delete-image --repository-name devops-orders-api \
--image-ids imageTag=v1.0
aws ecr delete-repository --repository-name devops-orders-api --force
aws ecr delete-pull-through-cache-rule --ecr-repository-prefix quay

Production Best Practices & Common Pitfalls

  1. Create repositories with a lifecycle policy. Storage is billed per GB, and old images only accumulate.
  2. Use immutable tags. Rollbacks only work when the previous image is guaranteed unchanged.
  3. Deploy exact tags or digests, never latest. The deployed version must be traceable.
  4. Scan twice. Fail CI on critical findings, then use continuous enhanced scanning for newly published CVEs.
  5. Mirror public base images. A pull-through cache removes upstream rate limits and outages.
  6. Share with repository policies and IAM, not credentials. Cross-account access needs both sides to allow it.
  7. Authenticate CI with short-lived roles. Use OIDC or an assumed role, not long-lived access keys.
  8. Define everything as code. Repository, lifecycle and policies belong in Terraform or CloudFormation.
Common Mistake

Setting a repository to immutable and then pushing latest on every build. The second push fails. Use unique tags per build instead.

Tip

Tag each image with the git SHA and add the semantic version on release. The SHA tells you exactly which commit is running, and the version gives humans a stable name.

Remember

The ECR login endpoint is ACCOUNT.dkr.ecr.REGION.amazonaws.com, with no repository name, and the token expires after 12 hours.

Quick Reference & Troubleshooting Commands

Command Description
aws ecr create-repository Create a repository
aws ecr get-login-password Get a Docker login token
aws ecr describe-images List images, tags and digests
aws ecr describe-image-scan-findings Read scan results
aws ecr start-lifecycle-policy-preview Preview which images a policy would expire
aws ecr create-pull-through-cache-rule Cache an upstream registry
Symptom Likely cause and fix
no basic auth credentials Not logged in or token expired, re-run the login
denied: not authorized on push Missing ecr:PutImage and layer upload permissions
tag invalid ... cannot be overwritten Immutable repository, push a new tag
ECS task stuck pulling then fails Execution role permissions or no route to ECR and S3
manifest unknown The tag does not exist, or a lifecycle rule expired it
Pull-through cache returns an auth error Missing or wrong Secrets Manager credentials for the upstream registry

Resources

AWS Direct Connect vs VPN: Run Both as Failover

AWS Direct Connect vs VPN: Run Both as Failover

Run AWS Direct Connect as primary and Site-to-Site VPN as BGP failover. Size the backup, set route preference and test it before an outage does.

10 min read•Aug 2026
Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot, at the crossover where Lambda stops being cheaper — 2026 pricing, invocation thresholds, and interruption math.

5 min read•Aug 2026
Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault: cost math, rotation, dynamic secrets and a decision flow, plus the Vault, IBM and OpenBao licensing context.

10 min read•Aug 2026
AWS VPC Security: Hardening Every Layer

AWS VPC Security: Hardening Every Layer

Harden your AWS VPC in layers: subnets, Security Groups, NACLs, Flow Logs, endpoints, and IAM conditions, with CLI examples for production.

10 min read•Jul 2026
Event-Driven Architecture on AWS Explained

Event-Driven Architecture on AWS Explained

Build event-driven systems on AWS with SQS, SNS, EventBridge and Kinesis: fan-out, DLQs, idempotent consumers and queue-based scaling.

11 min read•Jul 2026
S3 vs RDS vs DynamoDB: Choosing AWS Storage

S3 vs RDS vs DynamoDB: Choosing AWS Storage

Choosing S3, RDS, or DynamoDB wrong costs you in performance, cost, and scalability. Here is a practical decision guide based on your actual access patterns.

5 min read•Jul 2026
AWS Cost Optimisation: 8 Actions That Cut Bills

AWS Cost Optimisation: 8 Actions That Cut Bills

Cut your AWS bill without re-architecting: eight ordered steps from anomaly alerts and tagging to rightsizing, VPC endpoints, Savings Plans and Spot.

11 min read•Jul 2026
EC2 vs Lambda vs Fargate: Choosing AWS Compute

EC2 vs Lambda vs Fargate: Choosing AWS Compute

Choose between EC2, Lambda and Fargate using traffic shape, state and runtime limits, with worked cost break-evens instead of rules of thumb.

11 min read•Jul 2026

Explore More in AWS Messaging, Analytics, and Containers

All 6 Topics

Frequently Asked Questions

Is Managing Container Images with Amazon ECR free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Managing Container Images with Amazon ECR topic cover?

Store, scan and manage container images in Amazon ECR with immutable tags, lifecycle policies, cross-account access and pull-through cache.

Found a mistake, an outdated step or a broken link?