Challenge your understanding of docker-compose.yml structure by answering questions focused on its essential components, correct usage, and configuration nuances. Enhance your knowledge of service definitions, volumes, networking, and syntax practices in the context of modern container orchestration.
In a docker-compose.yml file, which key should be included under a service to specify the container image, such as 'redis:latest'?
Explanation: The 'image' key is used to specify which container image to use for a given service. 'container' is not a valid directive in docker-compose.yml structure. 'service' is used at a higher, more structural level, not as a service property. 'build' is used to indicate a build context or Dockerfile, not a pre-built image. Only 'image' directly points to a downloadable image.
Which of the following options correctly defines a named volume and attaches it to a service in docker-compose.yml?
Explanation: To use named volumes, you define their names under the global 'volumes:' section and then reference them in the service's 'volumes:' block. Only referencing the volume locally without declaring it globally can cause configuration issues for named volumes. 'storage' and 'attach-volumes' are not recognized keywords in the yaml file hierarchy. Proper declaration allows for reuse and clarity.
If you want two services to communicate privately within a docker-compose project, which structure should you use in docker-compose.yml?
Explanation: The correct way to enable private inter-service communication is by defining a network under the 'networks' key and specifying it in both service definitions. The 'group' key is not a valid part of the structure, and 'share_network' is not recognized in this context. Using 'links' is deprecated and does not facilitate secure, custom networking as 'networks' does.
How should you define environment variables for a service within the docker-compose.yml file?
Explanation: Environment variables should be defined as key-value pairs under the 'environment' key within each service block. Using a global 'env' key or a 'config' section with an 'environment_var:' prefix are not valid in docker-compose.yml syntax. The correct key is singular 'environment,' while 'environments' is also incorrect.
Which feature allows you to reuse configuration fragments within docker-compose.yml by defining a section with '&' and referencing it elsewhere with '*'?
Explanation: YAML anchors (using '&') and aliases (using '*') allow parts of the configuration to be defined once and reused elsewhere within the file. Service mirroring and option duplication are not standard YAML or docker-compose concepts. Keyword repeats is not a feature, but YAML anchors and aliases directly support reusability and cleaner configurations.