Why Lifecycle Policies?
Every time your CI/CD pipeline runs docker push, you're adding roughly 200MB–1GB of data to your AWS bill. Without a policy, that data sits there forever. Lifecycle policies allow you to define rules like:
- "Keep only the last 10 images."
- "Delete anything older than 14 days."
- "Expire untagged images immediately."
The "Perfect" Policy for Dev/Staging
For most teams, the best balance between "safety" and "savings" is a two-rule policy.
1. The "Untagged" Rule (Priority 1)
When you push a new image with the same tag (like :latest), the old image becomes "untagged." These are orphaned layers that serve no purpose. Delete them after 24 hours.
2. The "Age" Rule (Priority 2)
Delete any image that hasn't been pushed in the last 30 days. This ensures that even if you stop a project, its storage costs don't haunt you for years.
The JSON Configuration
{
"rules": [
{
"rulePriority": 1,
"description": "Cleanup orphaned/untagged images",
"selection": {
"tagStatus": "untagged",
"countType": "sinceImagePushed",
"countUnit": "days",
"countNumber": 1
},
"action": { "type": "expire" }
},
{
"rulePriority": 2,
"description": "Delete images older than 30 days",
"selection": {
"tagStatus": "any",
"countType": "sinceImagePushed",
"countUnit": "days",
"countNumber": 30
},
"action": { "type": "expire" }
}
]
}
Critical Concepts: sinceImagePushed vs. imageCountMoreThan
-
sinceImagePushed: Best for time-based compliance. (e.g., "We only keep 30 days of history"). -
imageCountMoreThan: Best for storage predictability. (e.g., "I only ever want to pay for 10 images per repo").
How to Test Without Breaking Production
The biggest fear is deleting an image that a production server might need during an auto-scaling event.
The "Lifecycle Policy Preview" is your best friend.
- Navigate to your ECR Repo -> Lifecycle Policy.
- Click Actions -> Create Preview.
- AWS will generate a list of exactly which images would be deleted if the policy ran right now. Check this list against your current production version before hitting save.
The 24-Hour Rule
Remember: ECR policies are not instantaneous. After you click "Save," AWS schedules a background task. It usually takes 24 hours for the images to actually disappear from your console and for the storage metrics to drop in CloudWatch.
Pro-Tip: Infrastructure as Code (Terraform)
Don't click around the console for 50 repos. Add this to your Terraform module:
resource "aws_ecr_lifecycle_policy" "default" {
repository = aws_ecr_repository.app.name
policy = <<EOF
{
"rules": [
{
"rulePriority": 1,
"description": "Keep last 30 images",
"selection": {
"tagStatus": "any",
"countType": "imageCountMoreThan",
"countNumber": 30
},
"action": {
"type": "expire"
}
}
]
}
EOF
}
Top comments (0)