How to Build a Docker Image Tag Script in Python
Generate consistent Docker image tags from service names and versions with automatic normalization.
Python code
20 lines#!/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
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
- Use `re.sub(r'[^a-z0-9.\-_]', '-', name)` for more aggressive sanitization
- 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
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.