Multiple Image Tags with Docker Compose

Recently I answered a question on Stack Overflow

How to use multiple image tags with docker-compose?

The validated answer was based on extends, but it cannot by used anymore in Compose file format 3.x. As suggested by a user, the Extension fields capability added in the version 3.4 of Docker Compose can replace it to achieve the same goal: reuse a single definition to set several tags.

Use YAML extension to define multiple tags

Here is how to use YAML extensions in this case.

version: "3.4"
# Define common behavior
  build: ubi-httpd
  # Other settings can also be shared
  image: ubi-httpd:latest

# Define one service by wanted tag
  # Use the extension as is
  # Override the image tag
    << : *default-ubi-httpd
    image: ubi-httpd:1
    << : *default-ubi-httpd
    image: ubi-httpd:1.0
  # Using an environment variable defined in a .env file for e.g.
    << : *default-ubi-httpd
    image: "ubi-httpd:${UBI_HTTPD_PATCH}"

It uses an .env file to define environment variables.

$ cat .env
# ---- UBI HTTP ----- #

Build images

Images can be built now with all the defined tags.

$ docker-compose build
# ...

$ docker images | grep ubi-httpd
# ubi-httpd  1       8cc412411805  3 minutes ago  268MB
# ubi-httpd  1.0     8cc412411805  3 minutes ago  268MB
# ubi-httpd  1.0.1   8cc412411805  3 minutes ago  268MB
# ubi-httpd  latest  8cc412411805  3 minutes ago  268MB

Images could also be pushed in the same way.