Reduce docker-compose files with YAML magic

May 6, 2019
Last update: Sep 22, 2020
~ 1 min

If you find yourself writing long docker-compose files because you need to specify the same things over and over again inside of the single services: fear no more!

Photo by Guillaume Bolduc on Unsplash

Without further ado:

version: '3.4' # min version 3.4

x-default: &default
  restart: always
  env_file: .env


    <<: *default
    image: node
    # blablabla

    <<: *default
    image: postgres

Thats it! Now both web and db inherit the properties of x-default.

The x- prefix is a docker specific thing and is required. YAML support references also without the prefix. Also note that version 3.4 or higher is required.

btw: I recently was looking into Sentry and found this docker-compose file. Thats how I discovered it.