Docker-Compose 从入门到放弃

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: Docker-Compose 从入门到放弃

浅言碎语

什么叫 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

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 -version 命令来验证是否安装成功

Docker-Compose 常用命令

docker-compose 命令只能管理 docker-compose 启动的容器,无法管理 docker run 启动的容器

docker-compose -h 可以查看帮助文档

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

创建容器,但不运行容器

docker-compose create 要被弃用了,官方建议可以使用 docker-compose up --no-start

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 scale 要被弃用了,官方建议可以使用 docker-compose up --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

构建或重构容器

需要 docker-compose.yml 文件中使用了 build 选项

容器一旦构建后,将会带上一个标记名。可以随时在项目目录下运行 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

验证并查看 compose 文件语法格式
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

拉取 docker-compose.yaml 文件内的镜像
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

推送 docker-compose.yaml 文件内的镜像
Usage: push [options] [SERVICE...]

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

docker-compose top

查看正在运行的 compose 项目进程

可以看到启动的容器名称(web1、web2)和相关的进程信息(UID、PID、PPID、C、STIME、TTY 、TIME、CMD)

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

删除 stoped 状态下的容器

docker-compose killdocker-compose stop 命令执行过的容器,都可以被 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.
删除一个非 stopped 状态的容器,会返回 No stopped containers

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 命令的详细版本
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 两个部分
docker-compose.yaml 模板
# 指定使用的格式版本
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

docker-compose.yaml 文件格式的版本
  • 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'

不同版本的 version 对应的 Docker 版本,详细的历史,可以看官方文档

docker 官方关于 version 的解释

编写文件格式 Docker 引擎发布
撰写规范 19.03.0+
3.8 19.03.0+
3.7 18.06.0+
3.6 18.02.0+
3.5 17.12.0+
3.4 17.09.0+
3.3 17.06.0+
3.2 17.04.0+
3.1 1.13.1+
3.0 1.13.0+
2.4 17.12.0+
2.3 17.06.0+
2.2 1.13.0+
2.1 1.12.0+
2.0 1.10.0+

image

  • 指定服务的镜像名称或镜像ID
  • 如果镜像在本地不存在,Compose 将会尝试拉取镜像
services:
  web:
    image: dockercloud/hello-world

build

  • 服务除了可以基于指定的镜像,还可以基于一份Dockerfile
  • 在使用up启动时执行构建任务,构建标签是 build
  • 可以指定 Dockerfile 文件所在的路径

    • Compose 将会利用 Dockerfile 自动构建镜像,然后使用构建的镜像启动服务容器
    • Dockerfile 文件的名称必须是 Dockerfile
  • 一个服务里面,imagebuid 只能存在一个

    • 如果都存在,Compose 会构建镜像并且把镜像命名为 image 指向的那个名字
  • build 生成的镜像名称格式:<项目名称_服务名称>:latest

    • 如果需要对于生成的镜像做统一管理,可以配合 image 选择来定义生成的镜像名称
build: /path/to/build/dir

context

context 选项可以是 Dockerfile 的存放路径,也可以是到链接到 git仓库的 url

context 选项默认使用指定路径下以 Dockerfile 命名的 Dockerfile 文件

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

dockerfile

自定义 Dockerfile 文件名称,需要使用 dockerfile 选项

使用 dockerfile 选项来构建,必须指定构建路径(context

dockerfile 指令不能跟 image 同时使用,否则 Compose 将不确定根据哪个指令来生成最终的服务镜像

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

args

DockerfileARG 一样,在构建前后使用

相关的可以看我另一篇博客:Dockerfile 从入门到放弃

有两种写法,都支持

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

指定容器名称

compose 的容器名称默认格式:<项目名称_服务名称_序号>

需要自定义容器名称时,可以使用 container_name

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

links

链接到其它服务中的容器
links:
  # 服务名称
  - web
  # 服务名称:别名
  - web:static
links 会在容器内创建 hosts 解析
172.17.2.186  web
172.17.2.186  static

depends_on

解决容器之间的依赖和启动顺序

只有在 redisdb 启动的情况下,才会启动 web

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 参数
ulimits:
  nproc: 65535
  nofile:
    soft: 20000
    hard: 40000

user

容器运行时使用的用户

默认是镜像指定的用户,没有配置的情况下,默认使用 root 用户

extra_hosts

给容器添加 hosts 解析 [只有 linux 可以]

格式必须是:<域名>:<IP>

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

external_links

链接 docker-compose.yaml 以外的容器,比如一些单独使用 docker run 命令启动的容器

链接的外部容器,必须和当前 docker-compose.yaml 的容器处于同一个网络中

比如:

docker-compose.yaml 内定义了使用名为 net-web 的网络,链接的外部容器 --net 参数也必须时 net-web

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

pid

设置容器 pid 模式为主机 pid 模式

和宿主机共享进程命名空间,容器使用 pid 标签能够访问和操纵其他容器和宿主机的命名空间

pid: "host"

ports

用于映射端口

  • 使用 <宿主机端口>:<容器内端口> 的格式(类似 docker run -p
  • 或者单独指定容器内的端口,宿主机将会随机映射端口 (类似 docker run -P
ports: 
  - "8080"
  - "80:8080"

volumes

挂载一个目录或者一个已存在的数据卷容器

  • 如果挂在的目录是给单一的服务使用,只需要在对应的服务部分使用 volumes
  • 如果是多个服务公用的目录,需要在顶级 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:

可以直接使用 <宿主机路径>:<容器内路径> 或者 <宿主机路径>:<容器内路径>:<访问模式>

访问模式:

  • rw:可读可写(默认的权限)
  • ro:只读模式(read only
  • z: SELinux 选项表示绑定挂载主机内容在多个容器之间共享
  • Z: SELinux 选项表示绑定挂载主机内容是私有的,对其他容器不共享

    • 在没有 SELinux 的平台上,SELinux 重新标记绑定挂载选项会被忽略。
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
dns:
  - 8.8.8.8
  - 114.114.114.114

dns_search

dns 搜索域
dns_search:
  - dc1.example.com
  - dc2.example.com

entrypoint

指定容器运行时执行的命令,会覆盖 Dockerfile 的 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 里面
env_file:
  - ./common.env
  - ./apps/web.env
  - /opt/secrets.env

env_file 格式

  • 每一行必须是 变量[=[变量值]]
  • #空格 表示注释
  • 只写 变量,没有=变量值,表示 unset 取消变量
# Set Rails/Rack environment
RACK_ENV=development
VAR="quoted"

environment

定义容器内的环境变量
environment:
  - RACK_ENV=development
  - SHOW=true
如果同时设置了 env_fileenvironment ,以 environment 的为准

devices

指定设备映射关系
devices:
  - "/dev/ttyUSB1:/dev/ttyUSB0

expose

只能指定容器内暴露的端口
expose:
  - "3000"
  - "8000"

extends

调用其他模板文件

有一个基础模板,名称为 common.yml

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
  • extends 使用限制

    • 要避免出现循环依赖
    • extends 不会继承 linksvolumes_from 中定义的容器和数据卷资源
  • 推荐在基础模板中只定义一些可以共享的镜像和环境变量
  • 在扩展模板中具体指定应用变量、链接、数据卷等信息

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

定义服务容器使用的网络配置,引用 顶级 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

顶级 networks 配置必须包含一个 ipam 子网配置

可以配置 ipv4 或者 ipv6

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

例如:

  • 项目所在目录的名称为:app

docker-compose.yaml 内容如下

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
执行 docker-compose up -d 命令后,会生成一个名称为 app_default 的网络,可以通过 docker network ls 命令查看

resources

容器使用的资源闲置

  • limits:容器最高使用资源
  • reservations:容器最低资源要求
services:
  frontend:
    image: awesome/webapp
    deploy:
      resources:
        limits:
          # CPU 最多可用核心数
          cpus: '0.50'
          memory: 50M
          # 限制容器内进程的数量(必须是整数)
          pids: 1
        reservations:
          # 宿主机最少要有的空闲 cpu 核心数
          cpus: '0.25'
          # 宿主机最少要有的空闲内存大小
          memory: 20M
memory 单位格式: b(bytes)k 或者 kbm 或者 mbg 或者 gb

全剧终

  • compose 可配置的选项是相当的多,尤其是 version: '3'
  • 甚至可以限制容器使用的磁盘io,配置 cpu cfs 配额等许多许多的功能,具体的,有兴趣的可以参考官方的文档

  • 还是 Dockerfile 从入门到放弃 里面的那句总结 (留点头发)
目录
相关文章
|
1月前
|
关系型数据库 MySQL Java
Docker Compose详细教程(从入门到放弃)
Docker Compose详细教程(从入门到放弃)
186 0
|
2月前
|
运维 虚拟化 开发者
Docker-全面详解(学习总结---从入门到深化)
Docker-全面详解(学习总结---从入门到深化)
48 1
|
3月前
|
大数据 数据管理 Docker
【Datahub系列教程】Datahub入门必学——DatahubCLI之Docker命令详解
【Datahub系列教程】Datahub入门必学——DatahubCLI之Docker命令详解
248 0
|
2天前
|
监控 Docker 容器
Docker从入门到精通:Docker log 命令学习
了解 Docker 日志管理对容器监控至关重要。`docker logs` 命令用于查看和管理容器日志,例如,`docker logs &lt;container_name&gt;` 显示容器日志,`-f` 或 `--follow` 实时跟踪日志,`--tail` 显示指定行数,`--timestamps` 添加时间戳,`--since` 按日期筛选。Docker 支持多种日志驱动,如 `syslog`,可通过 `--log-driver` 配置。有效管理日志能提升应用程序的稳定性和可维护性。
5 0
|
6天前
|
机器学习/深度学习 数据挖掘 Docker
《Docker 简易速速上手小册》第1章 Docker 基础入门(2024 最新版)
《Docker 简易速速上手小册》第1章 Docker 基础入门(2024 最新版)
20 1
|
14天前
|
存储 Ubuntu 关系型数据库
Docker从入门到精通:ubuntu系统安装docker
本文介绍了Docker的安装过程。首先,文章简述了Docker的组成部分:镜像(如模板用于创建容器服务)、容器(运行应用的独立实体)和仓库(存储镜像的库)。接着,针对Ubuntu系统,详细阐述了卸载旧版本Docker、更新软件包、安装依赖、添加Docker官方GPG密钥和软件源、安装Docker以及配置用户组的步骤。最后,通过启动Docker、验证安装是否成功(运行`hello-world`镜像)和查看Docker版本来确认安装完成。
53 12
|
22天前
|
Ubuntu Linux Shell
docker学习笔记3,从入门到精通
docker学习笔记3,从入门到精通
|
22天前
|
应用服务中间件 Shell nginx
docker学习笔记2,入门到精通
docker学习笔记2,入门到精通
|
22天前
|
Ubuntu 网络协议 Docker
docker学习笔记1,入门到精通
docker学习笔记1,入门到精通
|
2月前
|
Java Linux Docker
Docker入门到实战
Docker入门到实战、Centos7安装Docker