Create and use ECR pull through cache rules
This guide explains how to set up a rule for ECR pull through caching.1 This lets you access public container images via private ECR repositories, acting as a caching proxy that keeps these images current.
Reference implementation
See ECR pull through cache rule in pirates-iac
.
The ECS service for this website (app-km
) relies on the ECR pull through cache rule.
Before you begin
Consider setting up VPC endpoints. Utilizing VPC endpoints together with pull through cache proves to be especially beneficial, considering that ECR is often the sole reason an ECS service would require internet access.
Step 1: Create an ECR pull through cache rule
Navigate to the stack where you configure your ECS cluster.
Get the ecr_pull_through_cache
template from Golden Path:
What's this?
If you previously pulled the following image:
You can now pull the image via the ECR pull through cache address:
${var.account_id}.dkr.ecr.${var.region}.amazonaws.com/${var.environment}-ecr-public/nginx/nginx:latest
In other words, the original upstream registry URL:
Is replaced with:
Step 2: Apply the configuration
Initialize Terraform and apply the configuration:
Step 3: Perform initial pull
To activate the ECR pull through cache, you need to pull the image once while having access to the internet.
The easiest way to do this is to run the following script locally:
AWS_REGION=$(aws configure get region)
AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query "Account" --output text)
ENVIRONMENT="pirates-dev"
aws ecr get-login-password --region "${AWS_REGION}" | docker login --username AWS --password-stdin ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com
ECR_REGISTRY_URL="${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com"
ECR_REPOSITORY_PREFIX="${ENVIRONMENT}-ecr-public"
ECR_REPOSITORY_NAMESPACE="nginx"
IMAGE_NAME="nginx"
IMAGE_TAG="latest"
docker pull "${ECR_REGISTRY_URL}/${ECR_REPOSITORY_PREFIX}/${ECR_REPOSITORY_NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG}"
Subsequent pulls will not require access to the internet.2
-
The ECR user guide about pull through cache rules provides specific instructions for first-time image pulls using a pull-through cache rule. ↩