Where does container registry storage cost come from?
Registries bill stored data per GB-month. Network egress (pulls across regions or out to the internet) is billed separately, so a cleanup policy only reduces the storage portion of the bill. Storage grows in three main ways:
| Source of growth | How it accumulates | Why it persists |
|---|---|---|
| Per-commit CI images | Every build pushes a new image, often tagged with a commit SHA | Nothing removes them by default |
| Untagged images | Pushing latest or main again moves the tag, leaving the old image untagged |
The old image no longer has a tag, so few people notice it |
| Abandoned repositories | Retired services, experiments, forks | No owner reviews or deletes them |
Illustrative estimate (assumed numbers, not a benchmark)
Stored GB ≈ images per day × average unique layer size (GB) × days retained Monthly cost ≈ stored GB × price per GB-month
Assume 40 images per day, 0.2 GB of unique layers per image, and 90 days retained. That gives 40 × 0.2 × 90 = 720 GB. At a placeholder price of $0.10 per GB-month, the cost is about $72 per month. Check your provider's current pricing before you rely on this figure.
Deleting an image does not free its apparent size. Layers are content-addressed and stored once. If a base layer is shared by fifty images, it stays until the last image that references it is gone. Measure the stored bytes the registry reports before and after a cleanup rather than adding up image sizes.
This matters most for teams with high CI push volume or hundreds of repositories. If your registry costs a few dollars a month and egress or compute costs far more, use a simple policy and spend your effort on those larger costs instead.
How does an ECR lifecycle policy work?
When registry cost does matter, the main control in ECR is a lifecycle policy attached to each repository. A policy is a list of rules. Each rule has a rulePriority, a selection, and an action, and the only action is expire.
The selection filters by tagStatus: tagged, untagged, or any. Tagged rules must also narrow the match with tag prefixes (release-) or wildcard patterns (*-rc*). The selection then applies one of two limits:
- Count: keep the newest N matching images and expire the rest.
- Age: expire matching images pushed more than N days ago.
ECR evaluates rules in ascending priority order, lowest number first. Each image is claimed by the first rule whose selection matches it. That rule either keeps the image or expires it, and no later rule sees it again. Because of this, rule order sets the outcome. Put narrow, protective rules at low numbers. Put broad rules last. ECR requires a tagStatus: any rule to have the highest priority number.
images ──► [P1: tag prefix "release-", keep 20] ─► claimed: keep 20 newest, expire rest
│ unmatched
▼
[P2: untagged, older than 7 days] ───────► claimed: expire if older, else keep
│ unmatched
▼
[P3: any, keep 50] ──────────────────────► claimed: keep 50 newest, expire rest
Saving a policy does not delete anything right away. ECR applies expirations asynchronously, and this can take up to about a day. Storage savings show up in billing later. A rule that expires the wrong images also does its damage later, often after someone has stopped watching. Use the preview feature before saving a policy, because it shows the effect of a mistake before ECR applies it.
Repository images (each image is claimed by at most one rule)
│
▼
┌─────────────────────────────────┐ match ┌────────────────────────────┐
│ P1 tagged, prefix "release-" │─────────►│ keep newest 20, │
│ count limit: 20 │ │ expire the rest │
└─────────────────────────────────┘ └────────────────────────────┘
│ no match
▼
┌─────────────────────────────────┐ match ┌────────────────────────────┐
│ P2 untagged │─────────►│ expire if pushed > 7 days │
│ age limit: 7 days │ │ ago, else keep │
└─────────────────────────────────┘ └────────────────────────────┘
│ no match
▼
┌─────────────────────────────────┐ match ┌────────────────────────────┐
│ P3 any (must be last number) │─────────►│ keep newest 50 it sees, │
│ count limit: 50 │ │ expire the rest │
└─────────────────────────────────┘ └────────────────────────────┘
┌──────────────────────────────────────────────────────────────────────────┐
│ Expire decisions are not applied on save: ECR deletes asynchronously, │
│ up to about a day later. Use the preview before saving the policy. │
└──────────────────────────────────────────────────────────────────────────┘
Images pass through lifecycle rules in ascending rulePriority order, the first matching rule decides whether each image is kept or expired, and ECR applies the expirations asynchronously after the policy is saved.
How do you write and preview a baseline ECR lifecycle policy?
A baseline policy needs three rules, each with a distinct rulePriority:
- Untagged images. Set
tagStatustountagged, usecountTypesinceImagePushedwithcountUnitdays, and choose a short window such as 1 to 7 days. Untagged images are mostly layers left behind when a tag moves to a new build, and nothing should pull them by tag. - Release tags. Set
tagStatustotagged, list your release prefixes intagPrefixList(for examplevorrelease-), and useimageCountMoreThanto keep the last N. Count-based retention fits releases because rollback depth matters more than calendar age. - Dev and CI tags. Match prefixes such as
dev-orci-and expire them by age.
Priority order controls which rule claims an image. ECR evaluates rules from the lowest priority number up. Once a rule matches an image's tags, rules with a higher priority number cannot expire that image. If you give the release rule the lower number, a build tagged both v1.4.0 and ci-8812 is governed by the release rule, so the release count protects it from the CI age rule.
To preview a policy before saving it:
- Run
aws ecr start-lifecycle-policy-previewwith--repository-nameand--lifecycle-policy-textpointing at your JSON file. - Poll
aws ecr get-lifecycle-policy-previewuntil the status is complete. The result lists each image that would be expired, with its digest, its tags and theappliedRulePrioritythat caught it. - Review that list. Apply the policy with
aws ecr put-lifecycle-policyonly after the list matches what you expect.
Lifecycle policies are scoped to one repository in one region. Replicated repositories and cross-account copies do not inherit the source repository's policy. Each copy needs its own policy, or it keeps adding to storage cost without anyone noticing.
#!/usr/bin/env bash
set -euo pipefail
REPO=payments-api REGION=us-east-1 # policies are per repo AND per region
# Release rule gets the lowest number so a build tagged v1.4.0 + ci-8812 is kept.
# Prefixes in one tagPrefixList are ANDed, so dev- and ci- need separate rules.
cat > policy.json <<'EOF'
{"rules": [
{"rulePriority": 10, "description": "Keep last 20 releases",
"selection": {"tagStatus": "tagged", "tagPrefixList": ["v"],
"countType": "imageCountMoreThan", "countNumber": 20},
"action": {"type": "expire"}},
{"rulePriority": 20, "description": "Expire untagged after 3 days",
"selection": {"tagStatus": "untagged", "countType": "sinceImagePushed",
"countUnit": "days", "countNumber": 3},
"action": {"type": "expire"}},
{"rulePriority": 30, "description": "Expire dev- after 14 days",
"selection": {"tagStatus": "tagged", "tagPrefixList": ["dev-"],
"countType": "sinceImagePushed", "countUnit": "days", "countNumber": 14},
"action": {"type": "expire"}},
{"rulePriority": 40, "description": "Expire ci- after 14 days",
"selection": {"tagStatus": "tagged", "tagPrefixList": ["ci-"],
"countType": "sinceImagePushed", "countUnit": "days", "countNumber": 14},
"action": {"type": "expire"}}
]}
EOF
# Dry run: nothing is deleted by a preview.
aws ecr start-lifecycle-policy-preview --region "$REGION" \
--repository-name "$REPO" --lifecycle-policy-text file://policy.json
# Poll until the preview finishes, then list what would be expired and why.
until [ "$(aws ecr get-lifecycle-policy-preview --region "$REGION" --repository-name "$REPO" \
--query status --output text)" != "IN_PROGRESS" ]; do sleep 5; done
aws ecr get-lifecycle-policy-preview --region "$REGION" --repository-name "$REPO" \
--query 'previewResults[].[appliedRulePriority,imageDigest,join(`,`,imageTags||`[]`)]' --output table
# After reviewing the list, apply it with put-lifecycle-policy, then repeat for replica regions/accounts:
# aws ecr put-lifecycle-policy --region "$REGION" --repository-name "$REPO" --lifecycle-policy-text file://policy.json
A four-rule baseline ECR lifecycle policy, with the release rule placed first so it wins priority. The preview commands list each image that would be expired, along with the rule that caught it, before the policy is applied.
How does Artifact Registry cleanup compare to ECR lifecycle policies?
Artifact Registry's equivalent is a cleanup policy: a JSON file of named policies attached to a repository. Each policy has an action, either Delete or Keep, and a condition. Conditions filter on tag state (tagged, untagged, or any), tag prefixes, package name prefixes, version name prefixes, and age (olderThan or newerThan). There is also a separate keep rule, mostRecentVersions, that retains the newest N versions per package.
The precedence model differs from ECR's. ECR evaluates rules in priority order, and once a rule matches an image, lower-priority rules ignore it. Artifact Registry has no ordering. A version is deleted only if it matches some Delete policy and matches no Keep policy. This means Keep rules work as a safety net. A broad "delete anything older than 30 days" policy cannot remove versions tagged release- if a Keep policy covers that prefix.
The example policy below deletes untagged versions after a set age, keeps the most recent versions of each package, and keeps anything with a release tag prefix. Apply it with --dry-run first. In dry-run mode, cleanup evaluates the policy and records what it would delete in audit logs, but deletes nothing. Review those entries before you switch to enforcement, because deletions cannot be undone.
| ECR lifecycle policy | Artifact Registry cleanup policy | |
|---|---|---|
| Selection criteria | Tag status, tag prefixes or patterns | Tag state, tag/package/version prefixes, age |
| Precedence | Rule priority order; first match wins | Keep always overrides Delete |
| Count vs. age | Per rule: image count or days since push | Age in conditions; count via mostRecentVersions |
| Preview | Lifecycle policy preview | Dry-run mode with audit log output |
| Scope | One repository, one region | One repository |
# Write the cleanup policy. Keep policies override Delete policies,
# so a version matching any Keep rule is never removed.
cat > cleanup-policy.json <<'EOF'
[
{
"name": "delete-untagged-old",
"action": {"type": "Delete"},
"condition": {
"tagState": "UNTAGGED",
"olderThan": "14d"
}
},
{
"name": "keep-recent-versions",
"action": {"type": "Keep"},
"mostRecentVersions": {
"keepCount": 10
}
},
{
"name": "keep-releases",
"action": {"type": "Keep"},
"condition": {
"tagState": "TAGGED",
"tagPrefixes": ["release-"]
}
}
]
EOF
# Attach in dry-run mode: matches are recorded in audit logs, nothing is deleted.
gcloud artifacts repositories set-cleanup-policies my-docker-repo \
--project=my-project-id \
--location=us-central1 \
--policy=cleanup-policy.json \
--dry-run
# After reviewing the audit log entries, switch to enforcement.
# gcloud artifacts repositories set-cleanup-policies my-docker-repo \
# --project=my-project-id --location=us-central1 \
# --policy=cleanup-policy.json --no-dry-run
An Artifact Registry cleanup policy that deletes untagged versions older than 14 days while keeping the 10 newest versions per package and any release- tagged version, applied first in dry-run mode.
When should you avoid naive age- or count-based image retention?
Both rule types share the same blind spot: they judge images by push time and tags, not by whether anything is running them.
Count-based rules depend on push frequency. If a CI burst pushes forty builds in an afternoon, a "keep the last 30" rule can evict the image production is still running. A quiet repository has the opposite problem and keeps years-old images forever, so you keep paying to store them. Age-based rules fail the other way round. A service that is rarely redeployed can have its production image cross the age threshold while it is still serving traffic. Nothing fails until a node scales up or a pod is rescheduled, and then the image pull fails.
Deletion is effectively irreversible. Rebuilding from the same commit rarely gives you the same image: base layers, package mirrors and timestamps drift, so the digest changes. Any deployment pinned to the old digest stays broken.
"Untagged" also does not mean "orphaned." In a multi-architecture image, the per-platform manifests are usually untagged, because only the index carries the tag. Signatures, SBOMs and attestations are often stored as separate untagged artifacts. If aggressive untagged expiry removes them, image pulls on some architectures break, or signature verification fails at admission time and blocks deploys.
| Rule type | Typical risk | Failure appears when |
|---|---|---|
| Keep last N images | CI bursts evict deployed images | Next pull of the evicted digest |
| Expire after N days | Stable services lose their production image | Scale-up or pod reschedule |
| Expire untagged quickly | Platform manifests and attestations deleted | Multi-arch pull or policy check at deploy |
| Tag-prefix filters | Unmatched or mistyped tags fall into the delete set | Silently, until a rollback is needed |
How do you protect running and rollback images from cleanup?
Retention rules see tags and push dates. They do not see what is running. Three groups of images need explicit protection:
- Digest-pinned images in running workloads. A pod pinned to a digest keeps running after its tag moves. Once that digest is deleted, the next reschedule fails to pull it.
- Rollback targets. At minimum, keep the previous release for every service, plus anything your rollback runbook names.
- Images used by long-lived environments. Staging, on-prem clusters and customer installs often run versions that are months old. They also pull from the registry rarely, so recent pull activity tells you little about whether an image is still needed.
Protection is only practical if your tags make it expressible. Use a release prefix such as release- or v followed by an immutable semantic version. Turn on tag immutability so a version tag always refers to one digest. Then you can write a "keep" rule for the release prefix and let short retention handle pr-, sha- and branch tags.
Before you enable a policy, check its preview against the cluster. The script runs kubectl get pods -A, reads status.containerStatuses[].imageID to collect the resolved digests (not tags), and compares that set with the digests the ECR policy preview or Artifact Registry dry run would delete. Any overlap blocks the change. Run it against every cluster and region that pulls from the repository.
Short retention lowers cost but removes rollback options and the ability to reproduce old bugs. Long retention is cheap for a single image. The cost adds up because it is multiplied across every repository, every replicated region and every architecture variant.
#!/usr/bin/env bash
# Block an ECR lifecycle policy if its preview would expire any digest a pod is running.
# Run once per cluster context and region that pulls from this repository.
set -euo pipefail
REPO="payments-api" # placeholder repository name
POLICY="policy.json" # candidate lifecycle policy
REGION="us-east-1"
TMP=$(mktemp -d)
# 1. Resolved digests actually running (imageID, not the tag in the pod spec).
# Include init containers; strip any runtime prefix and keep only sha256:<hex>.
kubectl get pods -A -o jsonpath='{range .items[*]}{range .status.containerStatuses[*]}{.imageID}{"\n"}{end}{range .status.initContainerStatuses[*]}{.imageID}{"\n"}{end}{end}' \
| grep -o 'sha256:[a-f0-9]\{64\}' | sort -u > "$TMP/running.txt"
# 2. Ask ECR what the candidate policy would expire, without applying it.
aws ecr start-lifecycle-policy-preview --region "$REGION" \
--repository-name "$REPO" --lifecycle-policy-text "file://$POLICY" > /dev/null
aws ecr wait lifecycle-policy-preview-complete --region "$REGION" --repository-name "$REPO"
aws ecr get-lifecycle-policy-preview --region "$REGION" --repository-name "$REPO" \
--query 'previewResults[?action.type==`EXPIRE`].imageDigest' --output text \
| tr '\t' '\n' | grep -v '^$' | sort -u > "$TMP/expire.txt" || true
# 3. Any digest in both sets means the policy would break the next reschedule.
comm -12 "$TMP/running.txt" "$TMP/expire.txt" > "$TMP/overlap.txt"
if [[ -s "$TMP/overlap.txt" ]]; then
echo "BLOCKED: policy would expire running digests:" >&2
cat "$TMP/overlap.txt" >&2
exit 1
fi
echo "OK: $(wc -l < "$TMP/expire.txt") digests would expire, none are running in $(kubectl config current-context)"
A pre-apply check that collects the resolved image digests from every pod in the current cluster and fails if an ECR lifecycle policy preview would expire any of them.
What is a safe rollout process for registry retention policies?
Roll out retention in stages so that one bad rule pattern cannot remove images that a deployment still pulls.
Step-by-step rollout
- Inventory first. List repositories by stored size and last push or pull. A few large repositories usually account for most of the bill, and repositories with no recent activity are candidates for deletion rather than for a policy.
- Preview before enforcing. Run the ECR lifecycle policy preview or the Artifact Registry dry-run mode. Compare the list of images marked for removal against what is currently deployed.
- Start with low-risk repositories. CI scratch images and feature-branch builds are good first targets. Leave production service repositories until the rules have run cleanly elsewhere.
- Watch the trend, not the next hour. Both registries expire images asynchronously, so stored bytes drop with a delay. Judge the result over several days.
- Manage policies as code. Define the policy in the same module that creates the repository. Every new repository then gets a default policy, and nobody edits rules by hand in the console, so policies don't drift.
Alternatives to lifecycle rules
| Option | Fits when | Drawback |
|---|---|---|
| Scripted deletion | One-off cleanup | Someone has to maintain and run the script |
| Delete or consolidate abandoned repos | No pulls for months | Requires an owner to confirm |
| Fewer CI pushes | Every commit pushes an image | Requires changes to the CI pipeline |
| Accept the cost | Total storage is small | Cost grows unnoticed |
A shared policy template also reduces the time spent investigating cost. When every repository follows the same rules, unexpected storage growth points to the one repository that doesn't follow them. Without a template, engineers have to audit each hand-written policy one at a time.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to ecr lifecycle policy, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.