Sub topic 2
Storing images in Amazon ECR
This chapter assumes you can build a Docker image and run it locally, you know what an IAM role and a VPC subnet are, and you can use the AWS CLI. It covers the registry that your Fargate task definition pulls from: how to create a repository, push an image, control tags, clean up old images, and fix the pull errors that most often stop a first deployment.
What ECR is
Amazon Elastic Container Registry (ECR) is a managed registry for container images. A registry is the account-level endpoint, shaped like 123456789012.dkr.ecr.us-east-1.amazonaws.com. Inside it you create repositories, and each repository holds the versions of one image. An image is identified in two ways:
- A tag is a mutable label such as
1.0.0orlatest. It points at one image at a time and can be moved. - A digest is the SHA-256 hash of the image manifest, written
sha256:.... It never changes for a given image.
The full reference in a task definition is registry/repository:tag or registry/repository@digest.
ECR is private by default. Access is controlled by IAM, so no one can pull an image unless an identity has been granted permission.
The push and pull path
The Fargate task execution role pulls the image when it starts a task. Your task code does not pull it, so the task role is not involved.
Creating a repository
Create one repository per image. Turn on immutability and scan on push when you create it:
aws ecr create-repository \
--repository-name web-app \
--image-tag-mutability IMMUTABLE \
--image-scanning-configuration scanOnPush=true \
--encryption-configuration encryptionType=AES256 \
--region us-east-1IMMUTABLEtags make ECR reject a push that reuses an existing tag. This stops someone overwriting1.0.0with different code, which would make two deployments of the same tag run different software.- Scan on push runs a basic vulnerability scan on each new image. Read the findings with
aws ecr describe-image-scan-findings. Enhanced scanning through Amazon Inspector is a separate, account-level setting. - Encryption is on at rest by default with AES-256. Use
KMSif your policy requires a customer-managed key.
Authenticating, building, and pushing
Docker does not know about IAM, so you exchange your IAM credentials for a token that lasts 12 hours:
aws ecr get-login-password --region us-east-1 \
| docker login --username AWS --password-stdin \
123456789012.dkr.ecr.us-east-1.amazonaws.com
docker build --platform linux/amd64 -t web-app:1.0.0 .
docker tag web-app:1.0.0 \
123456789012.dkr.ecr.us-east-1.amazonaws.com/web-app:1.0.0
docker push \
123456789012.dkr.ecr.us-east-1.amazonaws.com/web-app:1.0.0The --platform linux/amd64 flag matters. If you build on an Apple Silicon laptop without it, you get an arm64 image. The task definition from the Topic Spine sets cpuArchitecture to X86_64, so that image fails at start with exec format error. Either build for the architecture you declare, or declare ARM64 and build for linux/arm64. A multi-architecture image, built with docker buildx build --platform linux/amd64,linux/arm64, works with either setting.
The identity that pushes needs ecr:GetAuthorizationToken and the push actions: ecr:BatchCheckLayerAvailability, ecr:InitiateLayerUpload, ecr:UploadLayerPart, ecr:CompleteLayerUpload, and ecr:PutImage.
Tags versus digests
List what is in the repository:
aws ecr describe-images \
--repository-name web-app \
--query 'imageDetails[].{tags:imageTags,digest:imageDigest,pushed:imagePushedAt}' \
--output tableTo pin a deployment to the exact bytes you tested, look up the digest and use it in the task definition's image field:
aws ecr describe-images \
--repository-name web-app \
--image-ids imageTag=1.0.0 \
--query 'imageDetails[0].imageDigest' \
--output textThe image field then reads 123456789012.dkr.ecr.us-east-1.amazonaws.com/web-app@sha256:<digest>.
| Reference style | Mutable? | Readable? | Use when |
|---|---|---|---|
| `:latest` | Yes | Yes | Local experiments only |
| `:1.0.0` or a Git SHA tag | No, if the repository is immutable | Yes | Normal deployments |
| `@sha256:...` | Never | No | Strict reproducibility and audits |
Avoid latest for services. ECS resolves the tag when each task starts, so tasks started at different times, such as after a scale-out, can run different images while the task definition revision stays the same.
Lifecycle policies
Every push adds storage cost, and repositories grow without limit unless you set a rule. A lifecycle policy expires images automatically. Save this as lifecycle.json:
{
"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 only the newest 20 images",
"selection": {
"tagStatus": "any",
"countType": "imageCountMoreThan",
"countNumber": 20
},
"action": { "type": "expire" }
}
]
}Apply it:
aws ecr put-lifecycle-policy \
--repository-name web-app \
--lifecycle-policy-text file://lifecycle.jsonRules run in priority order, and a rule with tagStatus: any must have the highest priority number. Before you rely on a policy, use the preview in the console, or aws ecr start-lifecycle-policy-preview. A policy that keeps only 20 images can delete the image an older task definition revision points to, and a rollback to that revision then fails to pull.
Letting Fargate pull the image
The managed policy AmazonECSTaskExecutionRolePolicy already grants the execution role these actions:
ecr:GetAuthorizationTokenecr:BatchCheckLayerAvailabilityecr:GetDownloadUrlForLayerecr:BatchGetImage
For a repository in the same account, that is enough. For cross-account pulls, you also add a repository policy in the account that owns the repository, naming the other account's execution role as a principal with those same pull actions.
Network path from a private subnet
The service in this tutorial runs in private subnets with assignPublicIp=DISABLED. The task's network interface then needs a route to ECR. Fargate pulls over this path, so a missing route shows up as a pull failure and not as an application error. You have two options:
- A NAT gateway in a public subnet, which gives outbound internet access.
- VPC endpoints, which keep the traffic on the AWS network. You need an interface endpoint for
com.amazonaws.us-east-1.ecr.api, one forcom.amazonaws.us-east-1.ecr.dkr, and an S3 gateway endpoint, because image layers are stored in S3. If your tasks use theawslogsdriver, add alogsinterface endpoint too. The endpoint security groups must allow inbound HTTPS (443) from the task security group.
Common pull errors
| Symptom in the stopped task reason | Likely cause | Fix |
|---|---|---|
| `CannotPullContainerError: ... i/o timeout` | No route to ECR or S3 from the subnet | Add a NAT gateway or the VPC endpoints above |
| `... pull access denied` or `not authorized` | Execution role lacks pull permissions, or wrong account | Attach the managed policy and check the repository policy |
| `... not found` | Wrong repository name, tag, or region, or the image was expired | Check `describe-images` and the lifecycle policy |
| `exec format error` in the container logs | Image architecture differs from `cpuArchitecture` | Rebuild with the matching `--platform` |
| `tag invalid: The image tag ... already exists` on push | Immutable repository | Use a new tag |
Exercise
A Fargate service in private subnets with no NAT gateway keeps stopping tasks with CannotPullContainerError ... i/o timeout. The execution role has AmazonECSTaskExecutionRolePolicy attached. Name the VPC endpoints you would add so the tasks can pull from ECR and still write logs with awslogs.
Show answer
Add interface endpoints for ecr.api, ecr.dkr, and logs, plus an S3 gateway endpoint, because image layers are served from S3. The endpoint security groups must allow inbound HTTPS from the task security group. The IAM policy is not the problem, because the error is a timeout and not an authorization failure.
Exercise
Your team pushes web-app:1.0.0 twice with different code, and a scale-out starts tasks that behave differently from the existing ones. Which two repository settings or reference styles prevent this?
Show answer
Set the repository's tag mutability to IMMUTABLE so a second push of 1.0.0 is rejected, and optionally reference the image by digest (@sha256:...) in the task definition so the exact bytes are fixed.