Docker Compose is a great tool to deploy a development environment. By defining a
docker-compose.yml, we can specify which services are needed and how they need to interact. A new developer can just check out the project, run
docker compose up and it will orchestrate all required containers automatically.
Sometimes it is necessary that services share certain configurations. For example, it might be useful if two services share the same environment variables or volumes. This might lead to duplication, and we all know how it is: when we need to make a super-quick change, we might forget to change the other occurrence, and 5 minutes wasted on debugging…
In order to DRY up the
docker-compose.yml, we can use two concepts:
- Docker Extensions allow defining arbitrary keys in the configuration file.
- YAML Anchors define markers that can be reused in the document.
Here is an example of a config file which has been DRY’ed up using this technique:
version: '3.4' x-env: &devenv - EMAIL_HOST=smtp - API_ENDPOINT='https://api.example.com' - OTHER_SETTING=jajaja services: web: command: bash -c 'sleep 100d' environment: *devenv ports: - 4000:3000 worker: image: superworker:15 environment: *devenv
Now there is no duplication. 🍾