Compose file
Docker Compose 是官方提供的编排工具,功能强大,简单易用。
Compose 最重要的莫过于编写编排文件。Docker-compose 文件的编写依赖于丰富的指令,所以理解各个指令的含义是首要的学习目标。 Docker Compose 文件用于创建互相关联的容器服务,下面是一个典型的 Compose 文件范例。
services:
  frontend:
    image: awesome/webapp
    ports:
      - "443:8043"
    networks:
      - front-tier
      - back-tier
    configs:
      - httpd-config
    secrets:
      - server-certificate
  backend:
    image: awesome/database
    volumes:
      - db-data:/etc/data
    networks:
      - back-tier
    profiles:
      - test
volumes:
  db-data:
    driver: flocker
    driver_opts:
      size: "10GiB"
configs:
  httpd-config:
    external: true
secrets:
  server-certificate:
    external: true
networks:
  # The presence of these objects is sufficient to define them
  front-tier: {}
  back-tier: {}
下面我们将对 Compose 文件中所用到的指令进行说明。
version
version 参数表示使用哪个版本的 compose 语法,一般是向下兼容。
- version: '2' 表示兼容 2 版本的语法
- version: '3.8' 表示兼容 3.8 版本的语法
Services
command
command 指令会覆盖 Dockerfile 中定义的 CMD 变量对应的值。
例如: command: bundle exec thin -p 3000
除了支持上述单一指令之外,也支持多指令的编写。
多指令
version: '3.1'
services:
  db:
    image: postgres
  web:
    build: .
    command:
      - /bin/bash
      - -c
      - |
        python manage.py migrate
        python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    links:
      - db
以上编排中的 command 相当于 docker run 下的:command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000"
如果多指令涉及变量,也可以写成:
    command:
      - /bin/bash
      - -c
      - |
        var=$$(echo 'foo')
        echo $$var # prints foo
entrypoint
entrypoint 用法与 command 类似,也支持多命令。
deploy
包含对容器的生命周期、资源约束等的配置项。包括:
- endpoint_mode
- labels
- mode
- placement
- replicas
- resources
- restart_policy
- rollback_config
- update_config
更多详情参考官网文档 deploy
blkio_config
对块 IO 进行设置的参数项
cpu
一类对 CPU 资源进行约束设置的参数项,包括:
- cpu_count
- cpu_percent
- cpu_shares
- cpu_period
- cpu_quota
- cpu_rt_runtime
- cpt_rt_period
- cpus
- cpuset
build
build 是基于 Dockerfile 构建镜像后再启动容器服务的一组配置参考。
build 与 image 可以同时使用,当无法在镜像仓库中找到所需镜像之时,系统便开始构建镜像,且镜像会保持到仓库
services:
  frontend:
    image: awesome/webapp
    build: ./webapp
  backend:
    image: awesome/database
    build:
        context: backend
        dockerfile: ../backend.Dockerfile
  custom:
    build: ~/custom
与 docker build 命令类似,还有 labels, args 等更多的参数。
cap
cap 包含 cap_add, cap_drop 两个参数。它是对 capabilities 的一种按需设置。在运行容器的时候可以通过指定 --privileded 参数来开启容器的所有CAP,可以通过--cap-add 和 --cap-drop 这两个参数来调整.
Capabilities 是 Linux 中对 root 用户的特殊权限的一种划分。
cap_add
  - ALL