Skip to main content

Implementing Docker Image Tagging Strategies

Design an immutable Docker image tagging strategy with git SHAs and semantic versions, then push, pin and clean up images in Docker Hub and ECR.

44 Terms

Overview and What You Will Learn

A Docker tag is a movable label that points at an image, and the only truly immutable identifier is the content digest (sha256:...). If you deploy by a tag that someone can overwrite, "the same version" in staging and production may be two different images. A good strategy tags every build with its git commit SHA, adds a semantic version for releases, makes tags immutable in the registry, and deploys by exact tag or digest.

In this lab you will:

  • Reproduce the latest problem and see why it breaks traceability
  • Tag builds with git SHA and semantic version in CI
  • Authenticate and push to Docker Hub, AWS ECR and a private registry
  • Turn on tag immutability and lifecycle rules so storage costs stay under control

Why This Matters in Production

Consider a trading team at a company like Zerodha that promotes a build from staging to production. If both environments pull trading-engine:latest and someone pushed a new build in between, production runs code that was never tested. Immutable, traceable tags remove that whole class of error, and they let an on-call engineer answer "which commit is running right now?" in seconds.

Core Principles

A tag is a pointer, a digest is the content. Several tags can point at one digest, and a tag can be moved to a different digest at any time unless the registry forbids it.

flowchart LR A[git commit
a3f9c2d] --> B[CI build] B --> C[(Registry)] C --> D[tag a3f9c2d] C --> E[tag v3.1.0] D --> F([digest sha256:84f9...]) E --> F F --> G[Deploy by tag or digest] classDef src fill:#EDE9FE,color:#1E293B classDef reg fill:#DBEAFE,color:#1E293B classDef out fill:#10B981,color:#FFFFFF class A,B src class C,D,E reg class F,G out
Identifier Stability
Digest @sha256:... Immutable, byte-for-byte identical
Git SHA tag Immutable by practice, traceable to a commit
Semantic version v3.1.0 Stable if the registry enforces immutability
latest or floating v3 Moves on every push, never use in production

Detailed Step-by-Step Practical Lab

Milestone 1: See Why latest Is Dangerous

Pushing the same tag twice silently replaces the earlier image. Anything that references that tag now gets different bytes.

Bash
docker build -t registry.razorpay.in/payment-api:latest .
docker push registry.razorpay.in/payment-api:latest
# Staging pulls latest and tests pass.
# 10:00 - engineer B pushes a different build with the same tag
docker build -t registry.razorpay.in/payment-api:latest .
docker push registry.razorpay.in/payment-api:latest
# Production now pulls latest and gets B's untested image.
# Which commit is this? The tag cannot tell you.
docker inspect registry.razorpay.in/payment-api:latest --format '{{.Created}}'
Milestone 2: Tag Every Build with Its Commit

Tag with the short git SHA on every build, and add the semantic version only for releases. Both tags point at the same image.

Bash
GIT_SHA=$(git rev-parse --short=7 HEAD)
IMAGE=registry.razorpay.in/payment-api
docker build \
--label org.opencontainers.image.revision="$(git rev-parse HEAD)" \
--label org.opencontainers.image.source="https://github.com/razorpay/payment-api" \
-t ${IMAGE}:${GIT_SHA} \
-t ${IMAGE}:v3.1.0 \
.
docker push ${IMAGE}:${GIT_SHA}
docker push ${IMAGE}:v3.1.0
# Find the digest that was pushed
docker inspect --format '{{index .RepoDigests 0}}' ${IMAGE}:v3.1.0
# registry.razorpay.in/payment-api@sha256:84f9c2b1d3e5...

Environments then use the most specific tag that fits: the SHA tag for dev and CI, the release tag for staging and production, or the digest when you want a hard guarantee.

YAML
# Kubernetes or Compose image reference, pinned to a release
image: registry.razorpay.in/payment-api:v3.1.0
# Strictest form: tag for humans, digest for the machine
image: registry.razorpay.in/payment-api:v3.1.0@sha256:84f9c2b1d3e5...
Milestone 3: Generate Tags Automatically in GitHub Actions

The docker/metadata-action computes tags and labels from the git context, so no one hand-types a version.

YAML
# .github/workflows/release.yml
name: Release image
on:
push:
tags: ["v*.*.*"]
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write # for OIDC login to AWS
steps:
- uses: actions/checkout@v4
- id: meta
uses: docker/metadata-action@v5
with:
images: 123456789012.dkr.ecr.ap-south-1.amazonaws.com/payment-api
tags: |
type=sha,format=short
type=semver,pattern={{version}}
flavor: |
latest=false
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/github-ecr-push
aws-region: ap-south-1
- uses: aws-actions/amazon-ecr-login@v2
- uses: docker/build-push-action@v6
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}

latest=false stops the action adding a latest tag. The OIDC role means CI holds no long-lived AWS keys.

Milestone 4: Authenticate to Docker Hub Without Rate-Limit Surprises

Docker Hub limits pulls per IP address and per account, and the numbers change over time, so check Docker's current documentation. Anonymous pulls from shared CI runners are the usual cause of toomanyrequests errors.

Bash
# Use an access token, never your account password
echo "$DOCKERHUB_TOKEN" | docker login -u rahul-devops --password-stdin
# Pull through your own registry or cache to avoid the limit entirely
docker pull registry.razorpay.in/mirror/nginx:1.25

Create the token under Account Settings, Personal access tokens, with the minimum scope (read-only for pull-only CI).

Milestone 5: Push to AWS ECR with Immutable Tags

ECR integrates with IAM and can reject any push that would overwrite an existing tag. Set that when you create the repository.

Bash
AWS_REGION=ap-south-1
AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
ECR_URI=${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com
# Login tokens last 12 hours
aws ecr get-login-password --region ${AWS_REGION} | \
docker login --username AWS --password-stdin ${ECR_URI}
# Create the repository with immutable tags and scan on push
aws ecr create-repository \
--repository-name payment-api \
--region ${AWS_REGION} \
--image-tag-mutability IMMUTABLE \
--image-scanning-configuration scanOnPush=true
docker tag payment-api:build ${ECR_URI}/payment-api:v3.1.0
docker push ${ECR_URI}/payment-api:v3.1.0
# Pushing the same tag again is now rejected
docker push ${ECR_URI}/payment-api:v3.1.0
# tag invalid: The image tag 'v3.1.0' already exists in the repository and cannot be overwritten

Immutable tags and floating tags such as v3 or latest cannot coexist, because floating tags must be moved on every release. In an immutable repository, deploy by exact version.

Security

Prefer short-lived credentials from OIDC or an instance role over static IAM user keys. A leaked static key gives an attacker standing push access, which means they can plant a malicious image under a trusted name.

Milestone 6: Control Storage Cost with Lifecycle Rules

Without cleanup, registries grow forever and you pay for every untagged layer from failed builds. In ECR a lifecycle policy expires images automatically. Here it is expressed in Terraform so it lives in version control.

HCL
resource "aws_ecr_repository" "payment_api" {
name = "payment-api"
image_tag_mutability = "IMMUTABLE"
image_scanning_configuration {
scan_on_push = true
}
}
resource "aws_ecr_lifecycle_policy" "payment_api" {
repository = aws_ecr_repository.payment_api.name
policy = jsonencode({
rules = [
{
rulePriority = 1
description = "Expire untagged images after 7 days"
selection = {
tagStatus = "untagged"
countType = "sinceImagePushed"
countUnit = "days"
countNumber = 7
}
action = { type = "expire" }
},
{
rulePriority = 2
description = "Keep the 30 most recent release images"
selection = {
tagStatus = "tagged"
tagPrefixList = ["v"]
countType = "imageCountMoreThan"
countNumber = 30
}
action = { type = "expire" }
}
]
})
}
Bash
# Inspect what is stored and untagged
aws ecr describe-images \
--repository-name payment-api \
--region ap-south-1 \
--query 'imageDetails[?imageTags==`null`].imageDigest' \
--output text
# Preview what a policy would delete before you apply it
aws ecr start-lifecycle-policy-preview \
--repository-name payment-api \
--lifecycle-policy-text file://lifecycle-policy.json \
--region ap-south-1
Milestone 7: Use a Private Registry When Cloud Is Not an Option

Self-hosted registries such as Harbor add role-based access, replication and built-in scanning for air-gapped or regulated environments. The workflow is the same: log in, tag with the full registry path, push.

Bash
docker login harbor.zerodha.in -u rahul@devops.in
docker tag trading-engine:build harbor.zerodha.in/trading/engine:v4.1.0
docker push harbor.zerodha.in/trading/engine:v4.1.0
# Path format: registry / project / repository : tag

Production Best Practices & Common Pitfalls

  1. Tag every build with the git SHA. It is the link from a running container back to source.
  2. Add semantic versions for releases only. They are the human-readable promotion names.
  3. Turn on tag immutability. Let the registry enforce what convention only suggests.
  4. Ban latest in deployment manifests. Add a policy check in CI or admission control.
  5. Deploy by digest for critical services. A digest cannot be moved or tampered with.
  6. Set lifecycle rules at repository creation. Never retrofit cleanup after the bill arrives.
  7. Store OCI labels. Revision and source labels make an image self-describing.
Common Mistake

Putting the repository name in the ECR login endpoint. Log in to ACCOUNT.dkr.ecr.REGION.amazonaws.com only, then include the repository in the image name.

Tip

docker buildx imagetools inspect IMAGE:TAG shows the digest and every platform in a multi-architecture image without pulling it.

Remember

Two tags can point at the same digest. v3.1.0 and a3f9c2d from the same build are the same image referenced two ways.

Quick Reference & Troubleshooting Commands

Command Description
docker tag SRC DEST Add another tag to an image
docker inspect --format '{{index .RepoDigests 0}}' IMG Show the digest
aws ecr describe-images --repository-name NAME List images and tags
aws ecr put-image-tag-mutability --image-tag-mutability IMMUTABLE Lock tags on an existing repo
docker image prune -a --filter "until=24h" Remove old local images on a build agent
Symptom Likely cause and fix
no basic auth credentials Not logged in, run docker login
toomanyrequests Docker Hub limit, authenticate or use a mirror
denied: requested access to the resource is denied Missing IAM permissions such as ecr:BatchCheckLayerAvailability and ecr:PutImage
tag invalid ... cannot be overwritten Immutable repo, publish a new version tag
ECR login suddenly fails 12 hour token expired, log in again

Resources

Explore More in Docker Images and Registry Management

All 4 Topics

Frequently Asked Questions

Is Implementing Docker Image Tagging Strategies free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Implementing Docker Image Tagging Strategies topic cover?

Design an immutable Docker image tagging strategy with git SHAs and semantic versions, then push, pin and clean up images in Docker Hub and ECR.

Found a mistake, an outdated step or a broken link?