skip to Main Content

I find top-level keys like volumes and networks in many docker compose yml files, for example here and in this repository:

networks:
    network:

volumes:
    db:

Only keys are declared and no values are found. I notice that all these two keywords have already been defined in services, then I wonder why adding those keywords globally again, and should they already have appeared in predefined services?

GPT answered that:

Adding top-level keys to Docker Compose allows you to define multiple services that can be run together in an application. This can be useful when creating complex applications with multiple components that are connected to each other. It also provides an easy way to configure and scale your application.

I don’t think its first sentence is correct since without those keys I can also define multiple services that can cooperate in an application.

Could anyone please verify that? Thanks.

2

Answers


  1. Chosen as BEST ANSWER

    Top-level elements, for instance networks top-level element, volumes top-level element, are just like the mostly used services top-level element, and they are used to define networks and volumes which can be used in services defined in the services top-level element.


  2. These things can be configured. One example is adding configuration to a specific networks:. Say you have a set of containers, but you also need to interact with containers in another Compose setup. You could define that other network with a specific name:

    networks:
      other:
        external: true
        name: other_default
    
    services:
      one:
        networks: [default, other]
      two:
        networks: [default, other]
    

    This saves us from repeating the configuration every time a network or volume appears, since they can appear in multiple services.

    In principle it would be possible for Compose to scan the list of services and create everything with default settings if required. Requiring the top-level lists of volumes: and networks: would simplify the implementation a little bit. It is also a little bit of protection against typos; Docker doesn’t give you a lot of that, but if you

    services:
      one:
        volumes:
          - exchange:/data
      two:
        volumes:
          - echxange:/data
    
    volumes:
      exchange:
    

    Compose will notice that the misspelled echxange doesn’t exist and complain.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search