Anchors and aliases in YAML - more complicated example

The YAML:

services:
  # Node.js gives OS info about the node (Host)
  nodeinfo: &function
    image: functions/nodeinfo:latest
    labels:
      function: "true"
    depends_on:
      - gateway
    networks:
      - functions
    environment:
      no_proxy: "gateway"
      https_proxy: $https_proxy
    deploy:
      placement:
        constraints:
          - 'node.platform.os == linux'
  # Uses `cat` to echo back response, fastest function to execute.
  echoit:
    <<: *function
    image: functions/alpine:health
    environment:
      fprocess: "cat"
      no_proxy: "gateway"
      https_proxy: $https_proxy

will become:
services:
  # Node.js gives OS info about the node (Host)
  nodeinfo:
    image: functions/nodeinfo:latest
    labels:
      function: "true"
    depends_on:
      - gateway
    networks:
      - functions
    environment:
      no_proxy: "gateway"
      https_proxy: $https_proxy
    deploy:
      placement:
        constraints:
          - 'node.platform.os == linux'
  # Uses `cat` to echo back response, fastest function to execute.
  echoit:
    image: functions/alpine:health
    labels:
      function: "true"
    depends_on:
      - gateway
    networks:
      - functions
    environment:
      fprocess: "cat"
      no_proxy: "gateway"
      https_proxy: $https_proxy
    deploy:
      placement:
        constraints:
          - 'node.platform.os == linux'
We want to refer to the nodeinfo service mapping. To do that, the &function anchor is placed after nodeinfo is declared, and before the first key-value pair in the mapping.

In echoit, the first key-value pair uses << as the key. This is a special key that indicates key-values from another mapping should be merged into this mapping. That other mapping is comes from the alias *function in this case. So the key-values for image, labels, depends_on, network, environment, and deploy from nodeinfo are merged into echoit, first. Then we overide the values for image and environment because they differ from nodeinfo. The end result is the same definitions, but without repeating items like labels and network.

So the nodeinfo service was used to provide the base definition for echoit, which then override specific key-values like image and environment.