Understanding YAML Anchors and Aliases in Docker Compose


Table of contents


Introduction

Docker Compose is a popular tool for defining and running multi-container Docker applications. A Docker Compose file is written in YAML, a human-readable data serialization standard. One of the lesser-known features of YAML — and by extension, Docker Compose — is the ability to use anchors and aliases to reuse parts of a YAML document. This blog post will delve deep into understanding these concepts.

The Basics: YAML Anchors (&) and Aliases (*)

YAML allows for a neat trick called “anchoring” which, in essence, lets you create a reference or “anchor” to any value or sequence. Once anchored, this value can be referred to elsewhere in the YAML document using what’s called an “alias.”

Anchoring (&): This is the act of marking a key, value, or sequence with an identifier, effectively creating a “named reference.”

Aliasing (*): Once you’ve created an anchor, you can refer back to it using an alias.

Example:

defaults: &default_config
  timeout: 10
  retries: 3

connection1:
  <<: *default_config
  url: http://example.com

connection2:
  <<: *default_config
  url: http://another.example.com

In the above YAML, connection1 and connection2 both use the settings defined under the defaults key.

Applying Anchors and Aliases in Docker Compose

The real power of this YAML feature becomes evident when we apply it to Docker Compose files, where we often find repeated blocks of configuration.

Suppose we have two services that share some common configurations but have unique port mappings:

x-shared-configuration: &shared-config
  image: my-app-image
  environment:
    - MY_ENV=VALUE

services:
  service1:
    <<: *shared-config
    ports:
      - "8080:8080"
  
  service2:
    <<: *shared-config
    ports:
      - "8081:8081"

By using the << merge key, we tell YAML to take all the key-value pairs from our anchored mapping and add them to the current mapping. This can significantly reduce redundancy in our Docker Compose files, making them more concise and readable.

When to Use Anchors and Aliases

Here are a few cases when considering this feature in Docker Compose:

Shared Configuration: As demonstrated, when multiple services share common configurations, anchoring helps avoid repetition.

Template Services: If you have a base service configuration and want to create variations of this service with minor differences.

Readability: In larger Docker Compose files, repeated blocks of configurations can make the file harder to navigate. Anchors can help streamline the structure.

Conclusion

YAML’s anchors and aliases offer an efficient way to reuse parts of a document, making Docker Compose files more maintainable and readable. This feature, while sometimes overlooked, can be a game-changer for those looking to optimize their Docker workflows. Happy containerizing!

© 2024 Virendra Giri