Sub topic 13
Caching upstream registries with pull through cache
This chapter assumes you can push and pull images with ECR, you know what a repository policy and an IAM policy are, and you have the AWS CLI configured. Pull through cache builds on those pieces. It adds a rule that makes ECR fetch and store images from another registry the first time someone asks for them.
What pull through cache does
Pulling from public registries such as Docker Hub has three problems. The registry can throttle anonymous pulls, it can be unreachable from private networks, and the image behind a tag can change or disappear. A pull through cache rule keeps copies of the images you actually use in your own private ECR registry.
A rule links a repository prefix in your registry to an upstream registry URL. When a client pulls an image whose repository name starts with that prefix, ECR does the following:
- It checks whether the repository already exists in your registry.
- If it does not exist, ECR creates the repository, using a repository creation template if one matches.
- ECR downloads the image from the upstream registry and stores it as a normal ECR image.
- ECR returns the image to the client.
Only images that someone has pulled are cached. The rule does not mirror the whole upstream registry.
The client never talks to the upstream registry. ECR makes that connection, so a cluster in private subnets that only reaches ECR through VPC endpoints can still pull through the cache.
Supported upstream registries
| Upstream | Upstream registry URL | Credentials needed |
|---|---|---|
| Amazon ECR Public | `public.ecr.aws` | No |
| Kubernetes container registry | `registry.k8s.io` | No |
| Quay | `quay.io` | No |
| Docker Hub | `registry-1.docker.io` | Yes |
| GitHub Container Registry | `ghcr.io` | Yes |
| GitLab Container Registry | `registry.gitlab.com` | Yes |
| Microsoft Azure Container Registry | `<name>.azurecr.io` | Yes |
| Another ECR private registry | `<account>.dkr.ecr.<region>.amazonaws.com` | No secret, but IAM access to the source registry |
The list of supported upstreams grows over time, so check the current ECR documentation before you plan around a specific registry.
Creating a rule without credentials
Start with an upstream that needs no credentials. This rule maps the prefix ecr-public to Amazon ECR Public:
aws ecr create-pull-through-cache-rule \
--ecr-repository-prefix ecr-public \
--upstream-registry-url public.ecr.aws \
--region us-east-1The prefix is a name you choose. It becomes the first path segment of every cached repository, and each registry in each Region needs its own rules. A prefix must be unique within the registry. Prefixes are short (2 to 30 characters), and a quota limits how many rules one registry can hold.
To pull through the rule, authenticate Docker to your registry as you learned earlier, then use your registry URI plus the prefix plus the upstream repository path:
docker pull 123456789012.dkr.ecr.us-east-1.amazonaws.com/ecr-public/nginx/nginx:latestAfter this command succeeds, describe-repositories shows a new repository named ecr-public/nginx/nginx.
Creating a rule for Docker Hub
Docker Hub, GitHub, GitLab, and Azure require credentials. You store them in AWS Secrets Manager, and the secret name must start with ecr-pullthroughcache/. For Docker Hub the secret holds your username and an access token. Create the access token in Docker Hub and do not use your account password.
aws secretsmanager create-secret \
--name ecr-pullthroughcache/docker-hub \
--secret-string '{"username":"my-docker-user","accessToken":"<access-token>"}' \
--region us-east-1The command prints the secret's ARN. Pass that ARN to the rule. The ARN ends in a random suffix, so copy the real value:
aws ecr create-pull-through-cache-rule \
--ecr-repository-prefix docker-hub \
--upstream-registry-url registry-1.docker.io \
--credential-arn arn:aws:secretsmanager:us-east-1:123456789012:secret:ecr-pullthroughcache/docker-hub-AbCdEf \
--region us-east-1Now pull an official image. Docker Hub stores official images under the library namespace, and you must include it in the path:
docker pull 123456789012.dkr.ecr.us-east-1.amazonaws.com/docker-hub/library/nginx:latestLeaving out library/ is a common mistake, and the pull fails with a "not found" error.
Pulls from Docker Hub through ECR use your authenticated account, so they count against your account's rate limit, not the anonymous limit that is shared by IP address. After the first pull, later pulls are served from ECR and use no Docker Hub quota.
Controlling the repositories ECR creates
By default, ECR creates cached repositories with default settings: mutable tags, AES-256 encryption, and no lifecycle policy. Cached repositories can pile up, so set rules for them before the first pull. A repository creation template does this. It applies settings to every repository whose name starts with a given prefix.
First write a lifecycle policy that expires cached images 90 days after ECR stored them:
{
"rules": [
{
"rulePriority": 1,
"description": "Expire cached images 90 days after they are stored",
"selection": {
"tagStatus": "any",
"countType": "sinceImagePushed",
"countUnit": "days",
"countNumber": 90
},
"action": {
"type": "expire"
}
}
]
}Save it as lifecycle.json, then create a template for the docker-hub prefix:
aws ecr create-repository-creation-template \
--prefix docker-hub \
--applied-for PULL_THROUGH_CACHE \
--description "Settings for repositories cached from Docker Hub" \
--image-tag-mutability MUTABLE \
--lifecycle-policy file://lifecycle.json \
--region us-east-1The --applied-for value tells ECR when to use the template. Besides PULL_THROUGH_CACHE it accepts REPLICATION and CREATE_ON_PUSH. A template only affects repositories created after it exists. Repositories ECR already created keep their old settings.
A template can also set encryption (AES-256 or KMS), resource tags, and a repository policy. These are the same controls you use on repositories you create yourself, applied automatically.
Permissions
A principal that pulls through the cache needs more than normal pull permissions, at least for the first pull of each image. Here is a policy for a CI role or a node role:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "GetToken",
"Effect": "Allow",
"Action": "ecr:GetAuthorizationToken",
"Resource": "*"
},
{
"Sid": "PullAndImport",
"Effect": "Allow",
"Action": [
"ecr:BatchGetImage",
"ecr:GetDownloadUrlForLayer",
"ecr:BatchImportUpstreamImage",
"ecr:CreateRepository"
],
"Resource": "arn:aws:ecr:us-east-1:123456789012:repository/docker-hub/*"
}
]
}ecr:BatchImportUpstreamImage lets the caller trigger the download from upstream. ecr:CreateRepository lets ECR create the repository on behalf of the caller, so it is only needed when the repository does not exist yet. If your template adds tags, the caller also needs ecr:TagResource.
The wildcard in the resource restricts these actions to repositories under one prefix. A role scoped to docker-hub/* cannot create arbitrary repositories elsewhere in your registry.
Some teams give ecr:BatchImportUpstreamImage and ecr:CreateRepository only to a CI job that warms the cache. Runtime roles then hold only pull permissions, and a pull of an image that is not cached fails. This keeps a production node from pulling new, unreviewed images from the internet.
Freshness, deletion, and other behavior
- Refresh interval. On a pull, ECR checks the upstream tag at most once every 24 hours. If the tag now points to a different image, ECR stores the new image and moves the cached tag. A pull inside that window returns whatever is cached.
- Upstream deletion. If the upstream image is deleted, your cached copy remains until you or a lifecycle policy remove it. This is a benefit for availability and a risk if you expect removals, such as a recalled image, to propagate.
- Digests. Cached images keep the same digest as upstream, so a reference like
docker-hub/library/nginx@sha256:<digest>is reproducible. Pinning by digest also avoids surprises from tag refreshes. - Scanning. Cached images are covered by your registry's scanning configuration, like images you push. Use enhanced scanning if you want continuous scanning as new vulnerabilities are published.
- Region and account scope. A rule exists in one Region of one account. A multi-Region setup needs a rule in each Region, or replication from a Region that has one.
Common errors
- Pull fails with "not found" for Docker Hub. The path is probably missing
library/, or the prefix does not match a rule exactly. - Rule creation fails for a credentialed upstream. Check that the secret name starts with
ecr-pullthroughcache/and that the secret holds the keysusernameandaccessTokenfor Docker Hub. - Access denied on the first pull but not later. The caller lacks
ecr:BatchImportUpstreamImageorecr:CreateRepository. Later pulls work because they need only pull permissions. - Expired credentials. Rotating or revoking the Docker Hub token breaks first pulls and refreshes. Already cached tags can still be pulled until a refresh is attempted.
Exercise
A node role in your cluster can pull images from ECR, but a pull of docker-hub/library/redis:7 fails with access denied. Pulls of images that were cached earlier succeed. Which permissions are probably missing, and what is a safer way to arrange permissions for production nodes?
Show answer
The role is missing ecr:BatchImportUpstreamImage (to trigger the import from upstream) and possibly ecr:CreateRepository (needed because the repository does not exist yet). A safer arrangement is to give those two permissions only to a CI role that pulls each approved image once to warm the cache, and give production nodes only pull permissions. Production nodes then can only run images that someone has already cached.
Exercise
You create a pull through cache rule with prefix quay and upstream quay.io, but you want every cached repository to expire its images after 30 days and use a KMS key. You create a repository creation template afterward. Why might some repositories not follow it, and how do you fix them?
Show answer
A template applies only to repositories created after it exists. Repositories ECR created earlier keep their original settings (default encryption and no lifecycle policy). Create the template before the first pull. For existing repositories, apply a lifecycle policy with put-lifecycle-policy. Encryption cannot be changed on an existing repository, so you must delete and recreate it, and ECR will cache it again with the template settings on the next pull.