Skip to main content

Cloud and deployment · Intermediate · 20 min

Store container images in Amazon ECR with scanning and lifecycle policies

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · AWS CLI 2.42.4 · crane 0.22.1

You will have a private Amazon ECR repository with immutable tags and scan on push, an nginx image copied into it with crane, its vulnerability findings read from the CLI, a lifecycle policy that keeps the ten newest tagged images, and pull access granted to a second AWS account.

On this page

Amazon Elastic Container Registry (ECR) is where most AWS workloads pull their images from: ECS, EKS, Lambda container functions and App Runner all read from it with IAM, so there is no extra registry password to manage. A repository created with the defaults works, but it lets anyone with push access overwrite v1.4.0 with different code, keeps every image forever, and tells you nothing about known vulnerabilities.

In this tutorial you set up one repository the way you would want it in production. You will:

  • create a private repository with immutable tags, scan on push and encryption at rest
  • log in with a short-lived token piped straight into crane, so no password lands on the command line
  • copy a public nginx image into it with crane, without Docker installed
  • read the scan findings and pick out the serious ones
  • add a lifecycle policy that keeps the ten newest tagged images and removes untagged ones after a day
  • let a second AWS account pull, and nothing more

crane is a small command-line tool from Google's go-containerregistry project that talks to registries directly. It copies images registry to registry, so you do not need a Docker daemon or a local copy of the image.

Cost. ECR bills for storage per GB-month and for data transferred out of the Region; the image in this tutorial is a few tens of megabytes. Check the ECR pricing page for your Region. The clean-up step deletes the repository and everything in it.

Step 1 · Install the AWS CLI and crane

Install curl, unzip and jq, then version 2.42.4 of the AWS CLI from Amazon's versioned installer. If aws --version already shows 2.42 or later, skip that part:

Bash
sudo apt update
sudo apt install -y curl unzip jq ca-certificates
AWS_CLI_VERSION=2.42.4
cd "$(mktemp -d)"
curl -fsSLo awscliv2.zip "https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m)-${AWS_CLI_VERSION}.zip"
unzip -q -o awscliv2.zip
sudo ./aws/install
aws --version

crane ships as a single binary in each GitHub release, with a checksums.txt file beside it. Download the archive for your CPU, check it against the published checksum, and install only the crane binary:

Bash
CRANE_VERSION=0.22.1
case "$(uname -m)" in
  x86_64) CRANE_ARCH=x86_64 ;;
  aarch64) CRANE_ARCH=arm64 ;;
  *) echo "No crane build for $(uname -m) in this tutorial"; false ;;
esac
cd "$(mktemp -d)"
BASE="https://github.com/google/go-containerregistry/releases/download/v${CRANE_VERSION}"
curl -fsSLO "$BASE/go-containerregistry_Linux_${CRANE_ARCH}.tar.gz"
curl -fsSLO "$BASE/checksums.txt"
grep " go-containerregistry_Linux_${CRANE_ARCH}.tar.gz\$" checksums.txt | sha256sum -c -
tar -xzf "go-containerregistry_Linux_${CRANE_ARCH}.tar.gz" crane
sudo install -m 755 crane /usr/local/bin/crane
crane version

Neither tool gets updates from apt. To upgrade, run the same commands with a newer version number (and sudo ./aws/install --update for the AWS CLI). The AWS CLI archive is the large one; on prepaid mobile data, download it once on Wi-Fi and keep the zip.

Check it worked

aws --version starts with aws-cli/2.42.4, sha256sum -c prints go-containerregistry_Linux_x86_64.tar.gz: OK (or arm64), and crane version prints 0.22.1 or something like v0.22.1.

Step 2 · Create the repository

If you use a named profile, run export AWS_PROFILE=<your-sandbox-profile> first (replace the placeholder; /tutorials/set-up-the-aws-cli-with-sso-and-named-profiles shows how to make one). Then set the names that every later command uses:

Bash
mkdir -p ~/ecr-demo
cd ~/ecr-demo
export AWS_REGION=eu-west-1
export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
export REPO=web-demo
export REGISTRY="$ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com"
echo "$REGISTRY/$REPO"

eu-west-1 is an example. Pick the Region your containers run in, because pulls across Regions are slower and billed as data transfer. For workloads serving southern Africa, af-south-1 (Cape Town) is an option once it is enabled in the account. Keep this terminal open; the variables go when it closes.

Create the repository with three settings that the defaults leave off or loose:

Bash
aws ecr create-repository --repository-name "$REPO" \
  --image-tag-mutability IMMUTABLE \
  --image-scanning-configuration scanOnPush=true \
  --encryption-configuration encryptionType=AES256 \
  --tags Key=project,Value=ecr-demo
  • IMMUTABLE means a tag, once pushed, always points at the same image. A deploy of 1.31.10 next month runs exactly what it ran today, and a compromised CI job cannot quietly replace a released tag. If you rely on a moving tag such as latest, ECR also offers IMMUTABLE_WITH_EXCLUSION, which keeps every tag immutable except the patterns you list.
  • scanOnPush=true starts a basic vulnerability scan each time an image arrives.
  • AES256 encrypts stored layers with S3-managed keys. Use encryptionType=KMS with kmsKey=<key-arn> instead if you need your own key and its audit trail. Encryption cannot be changed after the repository exists.

AWS is deprecating the per-repository scan setting in favour of scanning rules at registry level, which match repositories by name pattern. Read the registry setting to see what applies to your account:

Bash
aws ecr get-registry-scanning-configuration

If rules is empty, the repository flag you just set decides. If your organisation already has rules, a repository that does not match a scan-on-push filter is only scanned when someone starts a scan by hand.

Check it worked

create-repository prints a repositoryUri equal to the echo above. This prints IMMUTABLE, True and AES256:

Bash
aws ecr describe-repositories --repository-names "$REPO" \
  --query 'repositories[0].[imageTagMutability, imageScanningConfiguration.scanOnPush, encryptionConfiguration.encryptionType]' \
  --output text

Step 3 · Log in without putting a password on the command line

Registries speak their own HTTP protocol, not the AWS API, so crane needs a registry password. aws ecr get-login-password swaps your AWS credentials for a token that is valid for 12 hours, in this Region only, with your own IAM permissions and no more. Pipe it straight into crane; the username is always AWS:

Bash
aws ecr get-login-password --region "$AWS_REGION" \
  | crane auth login "$REGISTRY" -u AWS --password-stdin

The token never appears in your shell history or the process list. crane stores it in ~/.docker/config.json, the same file Docker uses, so docker push would work with it too. That file is readable by your user only, but the token is a working credential until it expires, so do not copy the file into images or CI logs. When the 12 hours are up, run the command again; for machines that pull all day, the Amazon ECR credential helper fetches fresh tokens on demand instead.

Check it worked

crane prints logged in via /home/<you>/.docker/config.json. The file now has an entry for your registry:

Bash
jq -r '.auths | keys[]' ~/.docker/config.json

It prints your registry host, such as 123456789012.dkr.ecr.eu-west-1.amazonaws.com.

Step 4 · Copy a public image into the repository

Your own app images would come from a build, as in /tutorials/build-and-push-a-container-image-from-github-actions. To exercise the repository now, copy the official nginx image from the ECR Public Gallery. Most public tags are multi-platform indexes; --platform linux/amd64 copies just the one image your servers run, which keeps the repository small and gives the scanner a single image to look at. (On Graviton servers, use linux/arm64.)

Note the digest of the source image first. A digest is the SHA-256 of the image manifest, so it identifies the exact bytes whatever the tag says:

Bash
SRC=public.ecr.aws/docker/library/nginx:1.31.10-alpine
SRC_DIGEST=$(crane digest --platform linux/amd64 "$SRC")
echo "$SRC_DIGEST"

Copy it in under a tag of your own:

Bash
crane copy --platform linux/amd64 "$SRC" "$REGISTRY/$REPO:1.31.10"

The layers stream through your machine on their way from one registry to the other, roughly 20 MB for this image. If your own connection is slow or metered, run the same commands from AWS CloudShell or a small EC2 instance in the same Region, where the transfer stays inside AWS.

Now try what immutable tags are for. Copy a different nginx release onto the same tag:

Bash
if crane copy --platform linux/amd64 public.ecr.aws/docker/library/nginx:1.30.4-alpine "$REGISTRY/$REPO:1.31.10"; then
  echo "the tag was overwritten, check the repository setting"; false
fi

Check it worked

The first copy finishes without an error. The second fails with a message like tag invalid: The image tag '1.31.10' already exists in the 'web-demo' repository and cannot be overwritten because the repository is immutable, so the if prints nothing. The digest in ECR matches the source, which proves the copy is byte for byte the same image:

Bash
test "$(crane digest "$REGISTRY/$REPO:1.31.10")" = "$SRC_DIGEST" && echo "digests match"

aws ecr describe-images --repository-name "$REPO" --query 'imageDetails[].imageTags' lists a single tag, 1.31.10.

Step 5 · Read the scan findings

Basic scanning checks the operating system packages in the image (Alpine's apk packages here) against CVE feeds from the distributions, NVD and other sources. It does not look inside your application's own dependencies such as node_modules; Amazon Inspector's enhanced scanning, a separately billed service, or a tool like Trivy covers those. Each image can be scanned once every 24 hours, and the scan on push counts as that day's scan.

Wait for the scan to finish, then count findings by severity:

Bash
aws ecr wait image-scan-complete --repository-name "$REPO" --image-id imageTag=1.31.10
aws ecr describe-image-scan-findings --repository-name "$REPO" --image-id imageTag=1.31.10 \
  --query 'imageScanFindings.findingSeverityCounts'

List only the findings worth acting on first, with the package each one is in:

Bash
aws ecr describe-image-scan-findings --repository-name "$REPO" --image-id imageTag=1.31.10 \
  --query 'imageScanFindings.findings[?severity==`CRITICAL` || severity==`HIGH`].[severity, name, attributes[?key==`package_name`].value | [0], attributes[?key==`package_version`].value | [0]]' \
  --output table

A fresh official image often has no critical or high findings at all; an old one usually has several. What you do with a finding is the same either way: if a fixed package version exists, rebuild on a newer base image and push it under a new tag (the old tag stays immutable). If no fix exists yet, record why the risk is acceptable for now and check again on the next scan. The scanner is a prompt for a human decision, not a gate that knows your app.

Check it worked

The wait returns without output, and the severity counts are a small JSON object such as {"MEDIUM": 2, "LOW": 5}, or null if nothing was found. The table shows one row per critical or high finding, with a CVE ID and a package name, or is empty.

Step 6 · Add a lifecycle policy

Without a policy, every image ever pushed stays and is billed. A lifecycle policy is a list of rules that ECR applies for you. Write one with two rules:

Bash
cat > lifecycle.json <<'JSON'
{
  "rules": [
    {
      "rulePriority": 1,
      "description": "Remove untagged images one day after they were pushed",
      "selection": {
        "tagStatus": "untagged",
        "countType": "sinceImagePushed",
        "countUnit": "days",
        "countNumber": 1
      },
      "action": { "type": "expire" }
    },
    {
      "rulePriority": 2,
      "description": "Keep the ten newest tagged images",
      "selection": {
        "tagStatus": "tagged",
        "tagPatternList": ["*"],
        "countType": "imageCountMoreThan",
        "countNumber": 10
      },
      "action": { "type": "expire" }
    }
  ]
}
JSON
jq -e . lifecycle.json > /dev/null && echo "lifecycle.json is valid JSON"

How ECR reads it:

  • Each image is acted on by one rule at most, and a lower rulePriority number wins.
  • Rule 1 catches untagged images: layers left behind when a build is pushed by digest, or failed pushes. A day gives a running deploy time to finish.
  • Rule 2 sorts every tagged image from newest to oldest by push time and expires everything after the tenth. A tagged rule must name a tagPatternList or tagPrefixList; "*" matches any tag. To protect release tags from the count, give them their own rule, for example a pattern list of ["release-*"] with a higher count.
  • Images that belong to a multi-platform index are not expired while the index still exists, so rule 1 does not break multi-platform images.

Before applying a policy to a repository with real images, preview what it would remove. The preview runs the rules against the repository's current images without deleting anything:

Bash
aws ecr start-lifecycle-policy-preview --repository-name "$REPO" \
  --lifecycle-policy-text file://lifecycle.json
aws ecr get-lifecycle-policy-preview --repository-name "$REPO" \
  --query '{status: status, expiring: previewResults[].imageTags}'

Run the second command again until status is COMPLETE. With one image in the repository, nothing should be listed as expiring. Then apply the policy:

Bash
aws ecr put-lifecycle-policy --repository-name "$REPO" \
  --lifecycle-policy-text file://lifecycle.json

ECR applies the rules on its own schedule; an image that matches a rule is removed within 24 hours, and each removal is logged in CloudTrail. Removed images cannot be recovered, which is why the preview comes first.

Check it worked

The preview lists no expiring images. This prints the two rule descriptions in priority order:

Bash
aws ecr get-lifecycle-policy --repository-name "$REPO" \
  --query lifecyclePolicyText --output text | jq -r '.rules[] | "\(.rulePriority) \(.description)"'

Step 7 · Let another account pull

A common layout keeps images in one account and runs them in others, such as staging and production. Access is granted from both sides: a repository policy here says the other account may pull, and an IAM policy in the other account says which of its roles may.

Set the ID of the account that should pull (replace 111122223333 with your real second account; ECR rejects a policy naming an account that does not exist):

Bash
export PULL_ACCOUNT_ID=111122223333
cat > repo-policy.json <<JSON
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowPullFromOtherAccount",
      "Effect": "Allow",
      "Principal": { "AWS": "arn:aws:iam::$PULL_ACCOUNT_ID:root" },
      "Action": [
        "ecr:BatchGetImage",
        "ecr:BatchCheckLayerAvailability",
        "ecr:GetDownloadUrlForLayer"
      ]
    }
  ]
}
JSON
aws ecr set-repository-policy --repository-name "$REPO" --policy-text file://repo-policy.json

The three actions are exactly what a pull needs: read the manifest, check the layers, and fetch them. No push actions, no delete. A repository policy needs no Resource, because it always applies to its own repository. The root principal means the account as a whole, which hands the choice of roles to that account's administrators. To be stricter, name a single role ARN instead.

In the other account, the role that pulls needs an IAM policy allowing ecr:GetAuthorizationToken (this one is never granted by a repository policy) plus the same three actions on arn:aws:ecr:eu-west-1:<your-account-id>:repository/web-demo. With that in place, someone signed in to the other account can run:

Bash
aws ecr get-login-password --region eu-west-1 \
  | crane auth login <your-account-id>.dkr.ecr.eu-west-1.amazonaws.com -u AWS --password-stdin
crane digest <your-account-id>.dkr.ecr.eu-west-1.amazonaws.com/web-demo:1.31.10

Replace both <your-account-id> placeholders with the account that holds the repository. The other account must also have the repository's Region enabled.

Check it worked

This prints the allowed principal and the three actions:

Bash
aws ecr get-repository-policy --repository-name "$REPO" \
  --query policyText --output text | jq '.Statement[] | {Principal, Action}'

In the other account, the crane digest command prints the same digest as $SRC_DIGEST. A crane copy into web-demo from that account fails with a DENIED error, because the policy grants no push.

Step 8 · Clean up

Deleting a repository with --force deletes every image in it, permanently. The first lines stop if REPO is not the demo repository, so check the name before you run it:

Bash
cd ~/ecr-demo
case "$REPO" in
  web-demo) echo "Deleting $REPO and all its images" ;;
  *) echo "REPO is not the demo repository, stopping"; false ;;
esac
aws ecr delete-repository --repository-name "$REPO" --force
crane auth logout "$REGISTRY"
cd ~
rm -rf ~/ecr-demo

The repository policy and lifecycle policy go with the repository. If you added IAM policies in the second account for the pull, remove them there too. crane stays installed; remove it with sudo rm /usr/local/bin/crane if you no longer need it.

Check it worked

aws ecr describe-repositories --repository-names web-demo fails with RepositoryNotFoundException, jq '.auths' ~/.docker/config.json no longer lists your registry, and ~/ecr-demo is gone.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.