In the docker-compose.yml
files, why are certain enumerations done with a dash -
, and others without?
services:
web: # the enumeration of [build, ports, volumes, environment] doesn't use a -
build: .
ports:
- "5000:5000" # why the - here? could we remove it and have ports: "5000:5000"?
volumes:
- .:/code # why the - here?
environment:
FLASK_ENV: development # why no - here?
redis:
image: "redis:alpine"
Another example:
version: '2'
services:
db:
image: mysql:5.7
volumes:
- ./mysql:/var/lib/mysql # could we remove this - prefix?
restart: always
environment:
MYSQL_ROOT_PASSWORD: somewordpress # no - in this enumeration, why?
MYSQL_DATABASE: wordpress
MYSQL_USER: wordpress
MYSQL_PASSWORD: wordpress
wordpress:
depends_on:
- db # would it be ok without - ?
image: wordpress:latest
volumes:
- ./wp:/var/www/html # same
...
4
Answers
After further tests, I noticed that
fails with:
so it's either:
or
according to YAML Multi-Line Arrays.
According to: https://docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html
Dashes represent Lists.
No Dashes Means that they are Key Value Pairs to a Dictionary.
According to the Docker Compose Documentation at: https://docs.docker.com/compose/compose-file/compose-file-v2/
is the same as:
Notice, that docker doesn’t care which one you use in the
environment
key , as long as they are consistent. Docker-compose syntax just happens to define it that way.This comes directly from YAML syntax specification.
-<value>
<name>: <value>
The dash in YAML denotes an array of elements (values only).
The other syntax in YAML, of
key: value
is a dictionary (key-value pairs).So, for example,
ports
is an array of values, with one value: "5000:5000". The:
here has no significance from the YAML standpoint.As another example, and clarification about the
environment
directive in docker compose:The
environment
definition in fact supports two formats.When defined like this:
it is a YAML dictionary of key-value pairs.
When defined like this:
it is an array of values, and once again, the
=
here has no significance from YAML standpoint, it is passed as is to the consumer that processes it (docker-compose binary in this case).