YAML 中的 docker-compose.yml 破折号语法

Bas*_*asj 8 yaml docker docker-compose

docker-compose.yml文件中,为什么某些枚举使用 dash 完成-,而其他枚举则没有?

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"
Run Code Online (Sandbox Code Playgroud)

另一个例子:

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
...
Run Code Online (Sandbox Code Playgroud)

小智 7

根据:https : //docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html

破折号代表列表。

列表的所有成员都是以相同缩进级别开头的行 -

# A list of tasty fruits
- Apple
- Orange
- Strawberry
- Mango
Run Code Online (Sandbox Code Playgroud)

没有破折号意味着它们是字典的键值对。

字典以简单的key: value形式表示

martin:
  name: Martin D'vloper
  job: Developer
  skill: Elite
Run Code Online (Sandbox Code Playgroud)

根据 Docker Compose 文档:https : //docs.docker.com/compose/compose-file/compose-file-v2/

environment:
  RACK_ENV: development
  SHOW: 'true'
  SESSION_SECRET:
Run Code Online (Sandbox Code Playgroud)

是相同的:

environment:
  - RACK_ENV=development
  - SHOW=true
  - SESSION_SECRET
Run Code Online (Sandbox Code Playgroud)

请注意,docker 并不关心您在environmentkey 中使用了哪一个,只要它们是一致的。Docker-compose 语法恰好以这种方式定义它。