How to Build a Docker Image Tag Script in Python

Generate consistent Docker image tags from service names and versions with automatic normalization.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 13 views 0 copies

Python code

20 lines
Python 3.9+
#!/usr/bin/env python3
"""Mock script for building docker image tags."""


def build_tag(service_name: str, version: str, registry: str = "docker.io") -> str:
    """Construct a docker image tag."""
    safe_name = service_name.lower().replace("_", "-")
    return f"{registry}/{safe_name}:{version}"


if __name__ == "__main__":
    # Demonstrate tag generation for multiple services
    services = [
        ("payment_service", "v1.2.3"),
        ("user-api", "v2.0.0"),
        ("ORDER_SERVICE", "v0.9.1-rc1"),
    ]

    for name, version in services:
        print(build_tag(name, version, "registry.example.com"))

Output

stdout
registry.example.com/payment-service:v1.2.3
registry.example.com/user-api:v2.0.0
registry.example.com/order-service:v0.9.1-rc1

How it works

The build_tag function normalizes service names by lowercasing and replacing underscores with dashes, matching Docker's naming conventions. The function uses an f-string to compose the full image reference in the standard registry/name:tag format. The if __name__ == "__main__" guard lets the function be imported elsewhere without triggering the demo loop. The default registry parameter makes the function reusable across different environments without repeating the registry value.

Common mistakes

  • Forgetting to handle uppercase service names before building the tag
  • Using underscores in image names, which Docker rejects
  • Hardcoding the registry instead of passing it as a parameter

Variations

  1. Use `re.sub(r'[^a-z0-9.\-_]', '-', name)` for more aggressive sanitization
  2. Add a `digest` param to support SHA256-pinned image references

Real-world use cases

  • CI pipelines that build and tag images before pushing to ECR or GCR automatically.
  • Release automation scripts that stamp version commits with mirror-image tag references.
  • Multi-service deployment tools that need a uniform naming convention for dozens of containers.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.