Sub topic 14
Using ECR images from ECS and EKS
This chapter assumes you can push an image to a private ECR repository, and that you know what an IAM role and a repository policy are. It also assumes you have used ECS task definitions or Kubernetes manifests at a basic level. The earlier chapters covered how to get an image into ECR. This one covers how a container service gets it back out, which identity does the pulling, and what breaks when that identity or its network path is wrong.
The pull is done by the platform, not your code
When ECS or EKS starts a container, something other than your application pulls the image. That component needs three things:
- An identity with ECR permissions.
- A network path to the ECR API, the ECR registry endpoint, and Amazon S3, where ECR stores image layers.
- An image reference that resolves to the content you intend to run.
Most pull failures come from one of the first two. Most "it ran the wrong version" incidents come from the third.
The permissions a puller needs
A pull needs four ECR actions:
ecr:GetAuthorizationToken, which must be granted on resource*because it is not tied to a repository.ecr:BatchCheckLayerAvailabilityecr:GetDownloadUrlForLayerecr:BatchGetImage
The last three can be limited to a single repository ARN. A least-privilege identity policy looks like this:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "ecr:GetAuthorizationToken",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"ecr:BatchCheckLayerAvailability",
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage"
],
"Resource": "arn:aws:ecr:us-east-1:123456789012:repository/my-app"
}
]
}AWS also provides managed policies. AmazonEC2ContainerRegistryReadOnly grants read access to every repository in the account, and AmazonEC2ContainerRegistryPullOnly is a pull-only variant. Use a custom policy like the one above when you need per-repository scoping.
If the repository is in a different account, the identity policy is not enough. The repository policy in the owning account must also allow the pulling account, as shown in the earlier chapter on cross-account sharing.
Amazon ECS
The task execution role
On ECS, the agent pulls the image using the task execution role, which you set with executionRoleArn in the task definition. The managed policy AmazonECSTaskExecutionRolePolicy includes the ECR pull actions and the CloudWatch Logs actions the agent needs.
The task role (taskRoleArn) is a different role. It gives credentials to your application code, for example to read an S3 bucket. Granting ECR permissions to the task role does not fix a failed image pull, because the agent never uses that role for pulling.
A Fargate task definition
{
"family": "my-app",
"requiresCompatibilities": ["FARGATE"],
"networkMode": "awsvpc",
"cpu": "256",
"memory": "512",
"executionRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
"containerDefinitions": [
{
"name": "my-app",
"image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/my-app:1.0.0",
"essential": true,
"portMappings": [{ "containerPort": 8080, "protocol": "tcp" }]
}
]
}Register it with aws ecs register-task-definition --cli-input-json file://taskdef.json.
The image value is the full repository URI plus a tag. To pin content exactly, replace :1.0.0 with @sha256:<digest>. A task definition revision is immutable, so a digest in the revision means every task started from it runs the same bytes. If you use a tag, combine it with tag immutability on the repository so that 1.0.0 cannot be repointed later. ECS also resolves a tag to a digest when a service deployment starts, so the tasks in one deployment run the same image even if the tag moves during a rollout. That protects a single deployment but does not protect later deployments, so immutable tags or digests are still the better control.
Launch types and where credentials come from
| Launch type | Who pulls | Identity used |
|---|---|---|
| Fargate | ECS agent managed by AWS | Task execution role |
| EC2 | ECS container agent on your instance | Task execution role for the task, and the container instance role for the agent itself |
For EC2, the instance profile role still needs the ECS agent permissions, normally from AmazonEC2ContainerServiceforEC2Role. A missing execution role is a common cause of failures when a task definition was written for EC2 and later moved to Fargate.
Networking for Fargate tasks
A Fargate task in a private subnet with no route to the internet cannot reach ECR unless you provide a path. There are two options:
- A NAT gateway in the route table. This is simple, but you pay NAT data processing charges on every image pull.
- VPC endpoints, which keep traffic on the AWS network.
For endpoints, create three:
- An interface endpoint for
com.amazonaws.us-east-1.ecr.api - An interface endpoint for
com.amazonaws.us-east-1.ecr.dkr - A gateway endpoint for
com.amazonaws.us-east-1.s3
The S3 endpoint is the one people forget. The registry returns the manifest, but the layers are downloaded from S3, so the pull stalls partway through. If tasks send logs with the awslogs driver, add a logs interface endpoint as well.
aws ec2 create-vpc-endpoint --vpc-id vpc-0abc1234 \
--vpc-endpoint-type Interface \
--service-name com.amazonaws.us-east-1.ecr.api \
--subnet-ids subnet-0aaa1111 subnet-0bbb2222 \
--security-group-ids sg-0ccc3333
aws ec2 create-vpc-endpoint --vpc-id vpc-0abc1234 \
--vpc-endpoint-type Interface \
--service-name com.amazonaws.us-east-1.ecr.dkr \
--subnet-ids subnet-0aaa1111 subnet-0bbb2222 \
--security-group-ids sg-0ccc3333
aws ec2 create-vpc-endpoint --vpc-id vpc-0abc1234 \
--vpc-endpoint-type Gateway \
--service-name com.amazonaws.us-east-1.s3 \
--route-table-ids rtb-0ddd4444The security group on the interface endpoints must allow inbound HTTPS (port 443) from the task's security group.
Amazon EKS
Nodes pull with the node role
On EKS with managed node groups or self-managed nodes, the kubelet pulls images. It gets registry credentials through the ECR credential provider, which calls GetAuthorizationToken using the node's IAM role. Attach AmazonEC2ContainerRegistryReadOnly or AmazonEC2ContainerRegistryPullOnly to the node role. On EKS Auto Mode, the node role uses AmazonEC2ContainerRegistryPullOnly for this.
For pods on Fargate, the pod execution role plays the same part. Its managed policy, AmazonEKSFargatePodExecutionRolePolicy, includes the ECR pull actions.
No imagePullSecrets for same-account ECR
For ECR in the same account, you do not create an imagePullSecrets entry. The authorization token expires after 12 hours, so a Kubernetes secret built from aws ecr get-login-password would silently go stale and new pods would fail to start. Let the node role supply credentials.
IRSA and EKS Pod Identity give permissions to application code in a pod. They do not affect image pulls.
A Deployment that pins a digest
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 2
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-app
image: 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-app@sha256:<digest>
imagePullPolicy: IfNotPresent
ports:
- containerPort: 8080Replace <digest> with a value from aws ecr describe-images. A digest reference is content-addressed, so IfNotPresent is safe: a node that already has the digest cached has exactly the right image. With a mutable tag, a cached node can keep running an old image after the tag moves. Kubernetes defaults imagePullPolicy to Always for the :latest tag and to IfNotPresent for others.
Cross-account and cross-Region pulls
A cluster in account 111122223333 pulling from a repository in 123456789012 needs two grants: the repository policy in 123456789012 allowing the pull actions, and the node or execution role in 111122223333 holding ecr:GetAuthorizationToken and the pull actions. Either one alone is denied.
Pulling across Regions works if permissions and network paths allow it, but each pull adds latency and inter-Region data transfer cost. For clusters in several Regions, replicate the repository (see the replication chapter) and point each cluster at the registry in its own Region.
Diagnosing pull failures
| Symptom | Likely cause |
|---|---|
| ECS `CannotPullContainerError` with a timeout | No route to ECR or S3, or the endpoint security group blocks port 443 |
| ECS error mentioning `ecr:GetAuthorizationToken` | The execution role lacks the permission, or the wrong role was set |
| Pull fails after the manifest, during layer download | Missing S3 gateway endpoint, or an endpoint policy that blocks S3 |
| Kubernetes `ErrImagePull`, then `ImagePullBackOff` | Node role lacks ECR permissions, wrong Region in the URI, or the image or tag does not exist |
| Access denied on a cross-account image | Repository policy or the caller's identity policy is missing |
| Old code after a deployment | A mutable tag was repointed and the node reused a cached image |
On Kubernetes, kubectl describe pod <name> shows the exact registry error in the Events section. On ECS, the stopped task's stoppedReason shows it.
Exercise
A Fargate task in a private subnet fails to start with a timeout while pulling my-app from ECR. You created VPC endpoints for ecr.api and ecr.dkr, and the execution role has AmazonECSTaskExecutionRolePolicy. Which endpoint is most likely missing, and why does its absence still allow the pull to begin?
Show answer
The S3 gateway endpoint (com.amazonaws.<region>.s3) is most likely missing. The ecr.api and ecr.dkr endpoints let the agent get a token and fetch the image manifest, so the pull starts. The layers are downloaded from S3, and without a route to S3 the layer download times out.