0
点赞
收藏
分享

微信扫一扫

Docker-Compose 从入门到放弃

独兜曲 2022-05-02 阅读 95

文章目录

浅言碎语

什么叫 Docker-Compose

  • Docker-Compose 项目是 Docker 官方的开源项目,负责实现对 Docker 容器集群的快速编排
  • Docker-Compose 将所管理的容器分为三层,分别是:
    • 工程(project)
    • 服务(service)
    • 容器(container)
  • Docker-Compose 运行目录下的所有文件(Docker-Compose.ymlextends 文件环境变量文件等)组成一个工程,若无特殊指定工程名即为当前目录名
    • 一个工程当中可包含多个服务,每个服务中定义了容器运行的镜像参数依赖
    • 一个服务当中可包括多个容器实例
    • Docker-Compose 并没有解决负载均衡的问题,因此需要借助其它工具实现服务发现及负载均衡
  • Docker-Compose 的工程配置文件默认为 Docker-Compose.yml
    • 可通过环境变量 COMPOSE_FILE-f 参数自定义配置文件,其定义了多个有依赖关系的服务及每个服务运行的容器
    • Docker-Compose 允许用户通过一个单独的 Docker-Compose.yml 模板文件(YAML 格式)来定义一组相关联的应用容器为一个项目(project)
  • Docker-Compose 项目由 Python 编写,调用 Docker 服务提供的 API 来对容器进行管理
    • 因此,只要所操作的平台支持 Docker API,就可以在其上利用 Compose 来进行编排管理

请给我一个 Docker-Compose

  • compose github
  • 官方提供的安装方法

yum 安装

yum install -y epel-release && \
yum install -y docker-compose

pip 安装

yum install -y epel-release && \
yum install -y python-pip
pip install --upgrade pip
pip install docker-compose

二进制文件

curl -L "https://github.com/docker/compose/releases/download/1.24.1/docker-compose-$(uname -s)-$(uname -m)" \
-o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose

Docker-Compose 常用命令

Define and run multi-container applications with Docker.

Usage:
  # [options] 类型的参数,必须出现在 [COMMAND] 类型的参数前面
  # [COMMAND] 类型的参数默认是找当前所在路径下的 docker-compose.yaml 文件
  ## 如果想要在任何路径执行 [COMMAND] 类型的参数
  ## 需要加上 -f 参数指定 docker-compose.yaml 文件的路径
  docker-compose [-f <arg>...] [options] [COMMAND] [ARGS...]
  docker-compose -h|--help

Options:
  # 指定 Compose 模板文件,默认为 docker-compose.yml,可以多次指定
  -f, --file FILE             Specify an alternate compose file (default: docker-compose.yml)
  # 指定项目名称,默认将使用所在目录名称作为项目名
  -p, --project-name NAME     Specify an alternate project name (default: directory name)
  # 输出更多调试信息
  --verbose                   Show more output
  # 不要打印ANSI控制字符
  --no-ansi                   Do not print ANSI control characters
  # 打印版本并退出
  -v, --version               Print version and exit
  # 要连接到的守护进程套接字
  -H, --host HOST             Daemon socket to connect to
  # 使用 tls 证书,需要包含 --tlsverify 参数
  --tls                       Use TLS; implied by --tlsverify
  # CA 证书路径
  --tlscacert CA_PATH         Trust certs signed only by this CA
  # TLS证书文件的路径
  --tlscert CLIENT_CERT_PATH  Path to TLS certificate file
  # TLS密钥文件的路径
  --tlskey TLS_KEY_PATH       Path to TLS key file
  # 使用TLS并验证远程
  --tlsverify                 Use TLS and verify the remote
  # 不要根据客户端证书中指定的名称检查守护程序的主机名(例如,docker 主机是IP地址)
  --skip-hostname-check       Don't check the daemon's hostname against the name specified
                              in the client certificate (for example if your docker host
                              is an IP address)
  # 指定工作目录,默认为 Compose 所在目录
  --project-directory PATH    Specify an alternate working directory
                              (default: the path of the Compose file)

Commands:
  # [COMMAND] 类型的参数默认针对 docker-compose.yaml 文件内的所有容器执行操作
  ## 如果需要针对某个指定的容器操作,可以在 [COMMAND] 类型的参数后面加上指定的容器名称
  build              Build or rebuild services
  bundle             Generate a Docker bundle from the Compose file
  config             Validate and view the Compose file
  create             Create services
  down               Stop and remove containers, networks, images, and volumes
  events             Receive real time events from containers
  exec               Execute a command in a running container
  help               Get help on a command
  images             List images
  kill               Kill containers
  logs               View output from containers
  pause              Pause services
  port               Print the public port for a port binding
  ps                 List containers
  pull               Pull service images
  push               Push service images
  restart            Restart services
  rm                 Remove stopped containers
  run                Run a one-off command
  scale              Set number of containers for a service
  start              Start services
  stop               Stop services
  top                Display the running processes
  unpause            Unpause services
  up                 Create and start containers
  version            Show the Docker-Compose version information

docker-compose up

Usage: up [options] [--scale SERVICE=NUM...] [SERVICE...]

Options:
    # 在后台运行容器,打印容器名称,不能和 --abort-on-container-exit 以及 --timeout 同时使用
    -d                         Detached mode: Run containers in the background,
                               print new container names. Incompatible with
                               --abort-on-container-exit and --timeout.
    # 不使用颜色来区分不同的服务的控制输出
    --no-color                 Produce monochrome output.
    # 不启动服务所链接的容器
    --no-deps                  Don't start linked services.
    # 强制重新创建容器,不能与 -–no-recreate 同时使用
    --force-recreate           Recreate containers even if their configuration
                               and image haven't changed.
                               Incompatible with --no-recreate.
    # 如果容器已经存在,则不重新创建,不能与 -–force-recreate 同时使用
    --no-recreate              If containers already exist, don't recreate them.
                               Incompatible with --force-recreate.
    # 不自动构建缺失的服务镜像
    --no-build                 Don't build an image, even if it's missing.
    # 创建服务后不要启动它们
    --no-start                 Don't start the services after creating them.
    # 在启动容器前构建服务镜像
    --build                    Build images before starting containers.
    # 如果任何一个容器被停止,就停止所有容器。不能与 -d 同时使用
    --abort-on-container-exit  Stops all containers if any container was stopped.
                               Incompatible with -d.
    # 停止容器时的超时间[默认单位:秒](默认为10秒)。不能与 -d 同时使用
    -t, --timeout TIMEOUT      Use this timeout in seconds for container shutdown
                               when attached or when containers are already.
                               Incompatible with -d.
                               running. (default: 10)
    # 删除服务中没有在 compose 文件中定义的容器
    --remove-orphans           Remove containers for services not
                               defined in the Compose file
    # 返回所选服务容器的退出代码。不能与 --abort-on-container-exit 同时使用
    --exit-code-from SERVICE   Return the exit code of the selected service container.
                               Implies --abort-on-container-exit.
    # 设置服务运行容器的个数,将覆盖在 compose 中通过 scale 指定的参数
    --scale SERVICE=NUM        Scale SERVICE to NUM instances. Overrides the `scale`
                               setting in the Compose file if present.

docker-compose create

Usage: create [options] [SERVICE...]

Options:
    # 强制重新创建容器,不能与 -–no-recreate 同时使用
    --force-recreate       Recreate containers even if their configuration and
                           image haven't changed. Incompatible with --no-recreate.
    # 如果容器已经存在,不需要重新创建,不能与 -–force-recreate 同时使用
    --no-recreate          If containers already exist, don't recreate them.
                           Incompatible with --force-recreate.
    # 不创建镜像,即使缺失
    --no-build             Don't build an image, even if it's missing.
    # 创建容器前,生成镜像
    --build                Build images before creating containers.

docker-compose scale

docker-compose down

Usage: down [options]

Options:
    # 删除镜像
    ## all   删除 compose 文件中定义的所有镜像
    ## local 删除镜像名为空的镜像
    --rmi type              Remove images. Type must be one of:
                              'all': Remove all images used by any service.
                              'local': Remove only images that don't have a
                              custom tag set by the `image` field.
    # 删除已经在 compose 文件中定义的和匿名的附在容器上的数据卷
    -v, --volumes           Remove named volumes declared in the `volumes`
                            section of the Compose file and anonymous volumes
                            attached to containers.
    # 删除服务中没有在 compose 中定义的容器
    --remove-orphans        Remove containers for services not defined in the
                            Compose file
    # 停止容器时的超时间[默认单位:秒](默认为10秒)。
    -t, --timeout TIMEOUT   Specify a shutdown timeout in seconds.
                            (default: 10)

docker-compose build

Usage: build [options] [--build-arg key=val...] [SERVICE...]

Options:
    # 删除构建过程中的临时容器
    --force-rm              Always remove intermediate containers.
    # 构建镜像过程中不使用缓存
    --no-cache              Do not use cache when building the image.
    # 始终尝试通过拉取操作来获取更新版本的镜像
    --pull                  Always attempt to pull a newer version of the image.
    # 为构建的容器设置内存大小
    -m, --memory MEM        Sets memory limit for the bulid container.
    # 为服务设置 build-time 变量
    --build-arg key=val     Set build-time variables for one service.

dokcer-compose config

Usage: config [options]

Options:
    # 将镜像标签标记为摘要
    --resolve-image-digests  Pin image tags to digests.
    # 只验证配置,不输出。 
    ## 当配置正确时,不输出任何内容
    ## 当文件配置错误,输出错误信息
    -q, --quiet              Only validate the configuration, don't print
                             anything.
    # 打印服务名,一行一个
    --services               Print the service names, one per line.
    # 打印数据卷名,一行一个
    --volumes                Print the volume names, one per line.

docker-compose pull

Usage: pull [options] [SERVICE...]

Options:
    # 忽略拉取镜像过程中的错误
    --ignore-pull-failures  Pull what it can and ignores images with pull failures.
    # 多个镜像同时拉取
    --parallel              Pull multiple images in parallel.
    # 拉取镜像过程中不打印进度信息
    --quiet                 Pull without printing progress information

docker-compose push

Usage: push [options] [SERVICE...]

Options:
    # 忽略推送镜像过程中的错误
    --ignore-push-failures  Push what it can and ignores images with push failures.

docker-compose top

web1
UID    PID    PPID   C   STIME   TTY     TIME                        CMD
--------------------------------------------------------------------------------------------
root   7658   7605   0   14:57   ?     00:00:00   nginx: master process nginx -g daemon off;
101    7851   7658   0   14:57   ?     00:00:00   nginx: worker process
101    7852   7658   0   14:57   ?     00:00:00   nginx: worker process

web2
UID    PID    PPID   C   STIME   TTY     TIME                        CMD
--------------------------------------------------------------------------------------------
root   7649   7571   0   14:57   ?     00:00:00   nginx: master process nginx -g daemon off;
101    7864   7649   0   14:57   ?     00:00:00   nginx: worker process
101    7865   7649   0   14:57   ?     00:00:00   nginx: worker process

docker-compose ps

docker-compose stop

Usage: stop [options] [SERVICE...]

Options:
  # 停止容器时的超时间[默认单位:秒](默认为10秒)。
  -t, --timeout TIMEOUT      Specify a shutdown timeout in seconds.
                             (default: 10)

docker-compose start

docker-compose restart

docker-compose kill

Usage: kill [options] [SERVICE...]

Options:
    # 通过发送SIGKILL信号来强制停止服务容器
    -s SIGNAL         SIGNAL to send to the container.
                      Default signal is SIGKILL.

docker-compose pause

docker-compose unpause

docker-compose rm

Usage: rm [options] [SERVICE...]

Options:
    # 强制删除,不需要用户确认
    -f, --force   Don't ask to confirm removal
    # 如果需要,在移除之前停止容器
    -s, --stop    Stop the containers, if required, before removing
    # 删除容器所挂载的数据卷
    -v            Remove any anonymous volumes attached to containers
    # 已弃用 - 无效参数
    -a, --all     Deprecated - no effect.

docker-compose logs

Usage: logs [options] [SERVICE...]

Options:
    # 默认不同的容器用不同的颜色区分,可以选择不区分颜色
    --no-color          Produce monochrome output.
    # 动态加载
    -f, --follow        Follow log output.
    # 显示时间戳
    -t, --timestamps    Show timestamps.
    # 看尾部指定行数的输出
    --tail="all"        Number of lines to show from the end of the logs
                        for each container.

docker-compose run

Usage:
    run [options] [-v VOLUME...] [-p PORT...] [-e KEY=VAL...] [-l KEY=VALUE...]
        SERVICE [COMMAND] [ARGS...]

Options:
    # 分离模式:在后台运行容器,打印新的容器名称
    -d                    Detached mode: Run container in the background, print
                          new container name.
    # 给 run 的容器分配一个名字
    --name NAME           Assign a name to the container
    # 覆盖镜像的 entrypoint
    --entrypoint CMD      Override the entrypoint of the image.
    # 设置环境变量 (可多次使用)
    -e KEY=VAL            Set an environment variable (can be used multiple times)
    # 增加或覆盖一个 label (可多次使用)
    -l, --label KEY=VAL   Add or override a label (can be used multiple times)
    # 指定一个用户名或者 uid 执行 run
    -u, --user=""         Run as specified username or uid
    # 不启动关联的服务
    --no-deps             Don't start linked services.
    # run 执行完成后删除 run 的镜像 (分离模式下被忽略)
    --rm                  Remove container after run. Ignored in detached mode.
    # 端口映射
    -p, --publish=[]      Publish a container's port(s) to the host
    # 在启用服务端口并映射到主机的情况下运行命令
    --service-ports       Run command with the service's ports enabled and mapped
                          to the host.
    # 挂载卷
    -v, --volume=[]       Bind mount a volume (default [])
    # 禁用伪tty分配。默认情况下,“docker compose run”分配TTY
    -T                    Disable pseudo-tty allocation. By default `docker-compose run`
                          allocates a TTY.
    # 容器内的操作路径
    -w, --workdir=""      Working directory inside the container

docker-compose exec

Usage: exec [options] [-e KEY=VAL...] SERVICE COMMAND [ARGS...]

Options:
    # 分离模式:在后台运行命令
    -d                Detached mode: Run command in the background.
    # 为进程授予扩展权限
    --privileged      Give extended privileges to the process.
    # 使用指定的用户执行命令
    -u, --user USER   Run the command as this user.
    # 禁用伪tty分配。默认情况下,“docker compose run”分配TTY
    -T                Disable pseudo-tty allocation. By default `docker-compose exec`
                      allocates a TTY.
    # 如果服务有多个实例,使用 --index 指定实例 [默认:1]
    --index=index     index of the container if there are multiple
                      instances of a service [default: 1]
    # 设置环境变量(可以多次使用,API < 1.25 不支持)
    -e, --env KEY=VAL Set environment variables (can be used multiple times,
                      not supported in API < 1.25)

docker-compose port

Usage: port [options] SERVICE PRIVATE_PORT

Options:
    # 指定协议, tcp 或者 udp [默认:tcp]
    --protocol=proto  tcp or udp [default: tcp]
    # 如果服务有多个实例,使用 --index 指定实例 [默认:1]
    --index=index     index of the container if there are multiple
                      instances of a service [default: 1]

docker-compose version

docker-compose version 1.18.0, build 8dd22a9
docker-py version: 2.6.1
CPython version: 3.6.8
OpenSSL version: OpenSSL 1.0.2k-fips  26 Jan 2017

Docker-Compose 编排文件

  • YAML 的布尔值(true, false, yes, no, on, off)必须要使用引号引起来(单引号双引号均可),否则会当成字符串解析
  • 官方建议 docker-compose.yml 文件内的路径使用相对路径,官方认为这样可移植性会更好
    • 具体其实还是根据实际的规划来决定使用相对路径还是绝对路径
  • Docker-Compose 标准模板文件应该包含三大部分
    • version
    • services
    • networks
    • 最关键的是 servicesnetworks 两个部分
# 指定使用的格式版本
version: '3'
# 定义服务
services:
  # 服务的名称(容器启动后的名称)
  web:
    # 使用的镜像
    image: dockercloud/hello-world
    # 端口映射
    ports:
      - 8080:80
    # 使用的网络名称
    networks:
      - front-tier
      - back-tier
  lb:
    image: dockercloud/haproxy
    ports:
      - 80:80
    # 链接到其他服务的容器中
    links:
      - web
    networks:
      - front-tier
      - back-tier
    # 目录持久化
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock 
# 定义网络
networks:
  # 网络名称
  front-tier:
    # 网络模式
    driver: bridge
  back-tier:
    driver: bridge

version

  • version:'1' (已弃用)
    • Compose 1.6.x 以下的版本可以使用 version: '1'
    • version: '1' 不能申明 volumesnetworks构建参数
    • version: '1' 默认每个容器都是 bridge 网络
      • 只能通过容器内的 ip 访问
      • 容器之间的服务发现需要用 link 模块
  • version:'2'
    • Compose 1.6.x 以上,Docker 1.10.0 以上的版本可以使用 version:'2'
    • version: '2' 可以申明 volumesnetworks构建参数
  • version:'3'
    • Compose 1.10.x 以上,Docker 1.13.0 以上的版本可以使用 version:'3'
    • 为了在 Compose 和 Docker 引擎的swarm 模式之间交叉兼容 ,version:'3' 删除了一些选项,增加了更多的选项
编写文件格式Docker 引擎发布
撰写规范19.03.0+
3.819.03.0+
3.718.06.0+
3.618.02.0+
3.517.12.0+
3.417.09.0+
3.317.06.0+
3.217.04.0+
3.11.13.1+
3.01.13.0+
2.417.12.0+
2.317.06.0+
2.21.13.0+
2.11.12.0+
2.01.10.0+

image

services:
  web:
    image: dockercloud/hello-world

build

build: /path/to/build/dir

context

build:
  context: /path/to/build/dir

dockerfile

build: 
  context: /path/to/build/dir
  # 名称要 context 指向的路径下存在
  dockerfile: Dockerfile-build

args

build: 
  context: /path/to/build/dir
  dockerfile: Dockerfile-build
  args: 
    os_version: 7
    use_user: work
build: 
  context: /path/to/build/dir
  dockerfile: Dockerfile-build
  args: 
    - os_version=7
    - use_user=work

command

version: '3'
services:
  nginx:
    image: nginx:mainline-alpine
    command: nginx -g 'daemon off;'
version: '3'
services:
  nginx:
    image: nginx:mainline-alpine
    command: [nginx, -g, 'daemon off;']

container_name

version: '3'
services:
  nginx:
    image: nginx:mainline-alpine
    container_name: web_static

links

links:
  # 服务名称
  - web
  # 服务名称:别名
  - web:static
172.17.2.186  web
172.17.2.186  static

depends_on

version: '3'
services:
  web:
    depends_on:
      - db
      - redis
  redis:
    image: redis
  db:
    image: mariadb

restart

# 任何情况下都不重启(默认策略)
restart: "no"
# 始终重启,直到容器被删除
restart: always
# 退出代码提示错误时重启
restart: on-failure
# 不在乎退出代码都会重启,直到服务停止或删除
restart: unless-stopped

pull_policy

# 始终都会拉取
pull_policy: always
# 从不拉取,如果本地不存在则报错
pull_policy: never
# 本地不存在时拉取
pull_policy: missing
# 如果已存在,重构镜像
pull_policy: build

ulimits

ulimits:
  nproc: 65535
  nofile:
    soft: 20000
    hard: 40000

user

extra_hosts

extra_hosts:
  - "somehost:162.242.195.82"
  - "otherhost:50.31.209.229"

external_links

external_links:
  # redis 为外包容器的 NAME
  - redis
  # database 为外包容器的 NAME
  # mysql 为服务别名
  - database:mysql

pid

pid: "host"

ports

ports: 
  - "8080"
  - "80:8080"

volumes

services:
  backend:
    image: awesome/backend
    volumes:
      # type: 挂载类型 'volume'、'bind'、'tmpfs'、'npipe'
      - type: volume
        # 挂载的来源(宿主机路径,或者下方顶级 volumes 定义的卷),不适用于 tmpfs 挂载
        source: db-data
        # 映射到容器内的路径
        target: /data
        # 配置额外的选项
        volume:
          # 禁止从容器复制数据
          nocopy: true
      - type: bind
        source: /var/run/postgres/postgres.sock
        target: /var/run/postgres/postgres.sock
# 定义一个名为 db-data 的卷,可以给多个服务挂载
volumes:
  db-data:
volumes:
  # 使用绝对路径挂载数据卷
  - /opt/data:/var/lib/mysql
  # 使用绝对路径挂载数据卷,并配置访问模式
  - ~/configs:/etc/configs/:ro

volumes_from

volumes_from:
  # 指定服务
  - service_name
  # 指定服务,并配置访问模式
  - service_name:ro
  # container: 是固定格式, container_name 指定外部容器的名称
  - container:container_name
  # 指定外部容器,并配置访问模式
  - container:container_name:rw

dns

dns:
  - 8.8.8.8
  - 114.114.114.114

dns_search

dns_search:
  - dc1.example.com
  - dc2.example.com

entrypoint

entrypoint:
  - php
  - -d
  - zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-20100525/xdebug.so
  - -d
  - memory_limit=-1
  - vendor/bin/phpunit

env_file

env_file:
  - ./common.env
  - ./apps/web.env
  - /opt/secrets.env

env_file 格式

# Set Rails/Rack environment
RACK_ENV=development
VAR="quoted"

environment

environment:
  - RACK_ENV=development
  - SHOW=true

devices

devices:
  - "/dev/ttyUSB1:/dev/ttyUSB0

expose

expose:
  - "3000"
  - "8000"

extends

webapp:
  build: ./webapp
  environment:
    - DEBUG=false
    - SEND_EMAILS=false
web:
  extends:
    file: common.yml
    service: webapp
  ports:
    - "8000:8000"
  links:
    - db
  environment:
    - DEBUG=true
db:
  image: mysql

labels

labels:
  - "com.example.description=Accounting webapp"
  - "com.example.department=Finance"
  - "com.example.label-with-empty-value"

logging

logging:
  driver: syslog
  options:
    syslog-address: "tcp://192.168.0.42:123"

network_mode

# 和宿主机相同的模式
network_mode: "host"
# 禁用网络
network_mode: "none"
# 只能访问指定的服务
network_mode: "service:[service name]"

networks

services:
  frontend:
    image: awesome/webapp
    networks:
      - front-tier
      - back-tier

  monitoring:
    image: awesome/monitoring
    networks:
      - admin

  backend:
    image: awesome/backend
    networks:
      back-tier:
        aliases:
          - database
      admin:
        # 声明网络上 admin 服务的备用主机名为 mysql
        # 同一网络上的其他容器可以使用服务名称或此别名连接到服务的容器
        aliases:
          - mysql
# 顶级 networks
networks:
  front-tier:
    driver: bridge
  back-tier:
  admin:

静态 ip

services:
  frontend:
    image: awesome/webapp
    networks:
      front-tier:
        ipv4_address: 172.16.238.10
        ipv6_address: 2001:3984:3989::10

networks:
  front-tier:
    ipam:
      driver: default
      config:
        - subnet: "172.16.238.0/24"
        - subnet: "2001:3984:3989::/64"

未声明顶级networks

version: '3'
services:
  web:
    image: nginx:latest
    container_name: web
    depends_on:
      - db
    ports:
      - "9090:80"
    links:
      - db
  db:
    image: mysql:5.7
    volumes:
      - /data/db_data:/var/lib/mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: 1234.com
      MYSQL_DATABASE: web
      MYSQL_USER: web
      MYSQL_PASSWORD: 1234.com

resources

services:
  frontend:
    image: awesome/webapp
    deploy:
      resources:
        limits:
          # CPU 最多可用核心数
          cpus: '0.50'
          memory: 50M
          # 限制容器内进程的数量(必须是整数)
          pids: 1
        reservations:
          # 宿主机最少要有的空闲 cpu 核心数
          cpus: '0.25'
          # 宿主机最少要有的空闲内存大小
          memory: 20M

全剧终

  • compose 可配置的选项是相当的多,尤其是 version: '3'
  • 甚至可以限制容器使用的磁盘io,配置 cpu cfs 配额等许多许多的功能,具体的,有兴趣的可以参考官方的文档
    • Compose specification
  • 还是 Dockerfile 从入门到放弃 里面的那句总结 (留点头发)
举报

相关推荐

0 条评论