DRY Docker Compose ConsoleOut

less than 1 minute read

Docker Compose offers couple of ways to utilize code re-usability through out your YAML file.

How to re-use

Utilizing YAML’s anchors & aliases we already can get a very decent amount of re-usability, but docker-compose extension fields are making all deal a bit more eye friendly.

Example

version: '3.7'

# Templates:
x-base: &base-service-template
  init: true
  build:
    context: .
  env_file: 
    - .env
  networks:
    - local
  
x-productservice: $product-service-template
  env_file:
    - .env
    - ./ProductService/product_env
      
services:
  userservice:
    <<: *base-service-template
    image: userservice.image
    container_name: userservice.container
    build:
      dockerfile: ./UserService/Dockerfile
    ports:
      - "5001:80"
    
  productservice:
    <<: *base-service-template
    <<: *product-service-template
    image: productservice.image
    container_name: productservice.container
    build:
      dockerfile: ./ProductService/Dockerfile
    env_file: 
      - ./ProductService/product_env
    ports:
      - "5651:80"

networks:
  local:
    name: local

Conclusion

Maybe it looks a bit weird, but when you take in consideration how much configuration items one can actually reuse this way, not to mention how much easier is to maintain them there is not much doubt left regarding the usefulness of extension field.
One should also keep an eye on docker template, which are currently an experimental feature. The template resembles the way k8s deals with YAML manifest for its different resource types, which IMO is a good thing.

Leave a comment