Explain how `<<: *name` makes a reference to `&name` in docker-compose?
Asked Answered
E

1

6

Trying to understand how the docker-compose file was created as I want to replicate this into a kubernetes deployment yaml file.

In reference to a cookiecutter-django's docker-compose production.yaml file:

...
services:
  django: &django
...

By docker-compose design, the name of service here is already defined as django but then I noticed this extra bit &django. This made me wonder why its here. Further down, I noticed the following:

...
celeryworker:
  <<: *django
...

I don't understand how that works. The docker-compose docs have no reference or mention for using << let alone, making a reference to a named service like *django.

Can anyone explain how the above work and how do I replicate it to a kubernetes deployment or services yaml file (or both?) if possible?

Edit: The question that @jonsharpe shared was similar but the answer wasn't clear to me on how its used.

Eldest answered 19/7, 2020 at 13:45 Comment(2)
Does this answer your question? What is the << (double left arrow) syntax in YAML called, and where's it specced?Caruncle
Kinda close @Caruncle . I didn't fully understand the answer from that question but the answer submitted by BMitch helped a lot more in clarity.Eldest
F
7

There are three different things happening, and none of them are specifically compose syntax, rather they are yaml syntax.

First is defining an anchor with the & followed by a name. That's similar to defining a variable to use later in the yaml, with the value matching the value of the yaml object where it appears.

Next is the alias, specified with * and the same name as the anchor. That uses the anchor in the second location in the yaml file.

Last is a mapping merge using the << syntax, which merges all of the mapped values in the alias with the rest of the values in the current map, allowing you to override values in the saved anchor with values specific to that section of the compose file.

To dig more into this, try searching on "yaml anchors and aliases". The first hit for me is this blog post: https://medium.com/@kinghuang/docker-compose-anchors-aliases-extensions-a1e4105d70bd

Florentinoflorenza answered 19/7, 2020 at 16:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.