Programming

Code Reuse in Docker-Compose Using YAML Anchor Feature

Code Reuse in Docker-Compose Using YAML Anchor Feature. Meaning of ampersand (&) in the docker-compose.yml file. Local MongoDB cluster using docker-compose
Photo by Christopher Gower on Unsplash
...
services:
spilo1: &spilo
image: spilo
...
hostname: spilo1
container_name: demo-spilo1
spilo2:
<<: *spilo
hostname: spilo2
container_name: demo-spilo2
...

YAML also has a handy feature called ‘anchors’, which let you easily duplicate content across your document.

base: &base_anchor
name: Everyone has same name

foo:
# inheriting base
<<: *base_anchor
age: 10

Example — Local MongoDB cluster using docker-compose

version: '3.3'
services:
mongo-test-1:
container_name: mongo-test-1
image: mongo:4.4.15
tmpfs: /data/db
ports:
- "27017:27017"
entrypoint: [ "/usr/bin/mongod", "--bind_ip_all", "--replSet", "dbrs" ]
mongo-test-2:
container_name: mongo-test-2
image: mongo:4.4.15
tmpfs: /data/db
ports:
- "27018:27017"
volumes:
- ./initdb-script:/initdb-script:Z
entrypoint: [ "/usr/bin/mongod", "--bind_ip_all", "--replSet", "dbrs" ]
mongo-test-3:
container_name: mongo-test-3
image: mongo:4.4.15
tmpfs: /data/db
ports:
- "27019:27017"
entrypoint: [ "/usr/bin/mongod", "--bind_ip_all", "--replSet", "dbrs" ]
version: '3.3'
services:
mongo-test-1: &mongo
container_name: mongo-test-1
image: mongo:4.4.15
tmpfs: /data/db
ports:
- "27017:27017"
entrypoint: [ "/usr/bin/mongod", "--bind_ip_all", "--replSet", "dbrs" ]
mongo-test-2:
<<: *mongo
container_name: mongo-test-2
ports:
- "27018:27017"
volumes:
- ./initdb-script:/initdb-script:Z
mongo-test-3:
<<: *mongo
container_name: mongo-test-3
ports:
- "27019:27017"
To inherit content in docker-compose. Makes code more precise and readable. https://medium.com/@anasanjaria/list/git-and-code-reviews-6dc76dbc03ea
How YAML anchor helps us in reducing code, making it more precise and readable

Source Code

Resources

Want to connect?
http://anasanjaria.bio.link/
Want to subscribe to my newsletter?
https://medium.com/subscribe/@anasanjaria

--

--

Follow me for back-end development. https://anasanjaria.bio.link

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store