Skip to content

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.

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:

ok get-template ecr_pull_through_cache

What's this?

If you previously pulled the following image:

public.ecr.aws/nginx/nginx:latest

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:

public.ecr.aws/

Is replaced with:

${var.account_id}.dkr.ecr.${var.region}.amazonaws.com/${var.environment}-ecr-public/

Step 2: Apply the configuration

Initialize Terraform and apply the configuration:

terraform init
terraform apply

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


  1. See Using pull through cache rules

  2. The ECR user guide about pull through cache rules provides specific instructions for first-time image pulls using a pull-through cache rule.