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.
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.
export AWS_REGION=ap-south-1export 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=KMSData 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.
aws ecr get-login-password --region $AWS_REGION | \ docker login --username AWS --password-stdin $REGISTRY cat > Dockerfile << 'EOF'FROM nginx:1.27-alpineRUN echo "orders-api v1.0" > /usr/share/nginx/html/index.htmlEOF docker build -t devops-orders-api:v1.0 .docker tag devops-orders-api:v1.0 $REGISTRY/devops-orders-api:v1.0docker push $REGISTRY/devops-orders-api:v1.0Layers 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.
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 immutablePublish 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.
# Find the digest of what you pushedaws ecr describe-images \ --repository-name devops-orders-api \ --image-ids imageTag=v1.0 \ --query "imageDetails[0].imageDigest" --output textMilestone 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.
# Read results of the scan-on-pushaws 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 repositoriesaws 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.
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.
aws ecr start-lifecycle-policy-preview --repository-name devops-orders-apiaws ecr get-lifecycle-policy-preview --repository-name devops-orders-apiOn 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.
# 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 credentialsaws 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-alpineLater 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.
# 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:GetDownloadUrlForLayerandecr:BatchGetImage. The managed policyAmazonECSTaskExecutionRolePolicyincludes 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.dkrand 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
aws ecr batch-delete-image --repository-name devops-orders-api \ --image-ids imageTag=v1.0aws ecr delete-repository --repository-name devops-orders-api --forceaws ecr delete-pull-through-cache-rule --ecr-repository-prefix quayProduction Best Practices & Common Pitfalls
- Create repositories with a lifecycle policy. Storage is billed per GB, and old images only accumulate.
- Use immutable tags. Rollbacks only work when the previous image is guaranteed unchanged.
- Deploy exact tags or digests, never
latest. The deployed version must be traceable. - Scan twice. Fail CI on critical findings, then use continuous enhanced scanning for newly published CVEs.
- Mirror public base images. A pull-through cache removes upstream rate limits and outages.
- Share with repository policies and IAM, not credentials. Cross-account access needs both sides to allow it.
- Authenticate CI with short-lived roles. Use OIDC or an assumed role, not long-lived access keys.
- Define everything as code. Repository, lifecycle and policies belong in Terraform or CloudFormation.
Common MistakeSetting a repository to immutable and then pushing
lateston every build. The second push fails. Use unique tags per build instead.
TipTag 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.
RememberThe 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 |