docker专题(三)docker-compose

前言

docker-compose用一台机器即可,docker-swarm需要用多台机器

由于只有一台阿里云,所以只能在虚拟机上玩了

此文来自http://c.biancheng.net/view/3170.html的学习

环境准备

镜像下载https://mirrors.aliyun.com/centos/7.9.2009/

DVD:普通安装版,需安装到计算机硬盘才能用。文件比较大,包含一系列常用的软件。适合在虚拟机中安装学习。安装的时候可以选择性的安装。

Everything:包括各种packages。太大,挺多东西暂时用不到,不推荐。

LiveGNOME:GNOME桌面版。

LiveKDE:KDE桌面版。

Minimal:最小安装版,一般文本编辑器都没有,不推荐。

NetInstall:这个是网络安装的启动盘。

此处为了节省空间我选择了CentOS-7-x86_64-Minimal-2009.iso

结果发现ping命令不能用

参考文章:https://blog.csdn.net/qq_42074075/article/details/94360077

接着ifconfig不存在,真心是最小安装版,没脾气

搜索yum search ifconfig

安装yum install -y net-tools.x86_64

参考文章:https://blog.51cto.com/u_13760351/2428485

image
安装镜像,然后克隆三个,工具-->发送键输入到所有会话

image
image
安装docker

# 1.卸载旧的版本
$ sudo yum remove docker \
docker-client \
docker-client-latest \
docker-common \
docker-latest \
docker-latest-logrotate \
docker-logrotate \
docker-engine
#2.# 安装基本的安装包
$ sudo yum install -y yum-utils
#3.设置镜像仓库
$ sudo yum-config-manager \
--add-repo \
https://download.docker.com/linux/centos/docker-ce.repo # 默认是国外的
# 换成下面的
$ sudo yum-config-manager \
--add-repo \
https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo # 阿里云镜
# 更像软件包索引
yum makecache fast
# 4.安装docker引擎
yum install docker-ce docker-ce-cli containerd.io # docker-ce 社区版 ee 企业
#5. 启动Docker
systemctl start docker # 代表启动成功

简介

Docker Compose 与 Docker Stack 非常类似。它能够在 Docker 节点上,以单引擎模式(Single-Engine Mode)进行多容器应用的部署和管理。

部署和管理繁多的服务是非常困难的,Docker Compose就是用来解决这个问题的

Docker Compose 并不是通过脚本和各种冗长的 docker 命令来将应用组件组织起来,而是通过一个声明式的配置文件描述整个应用,从而使用一条命令完成部署。

应用部署成功后,还可以通过一系列简单的命令实现对其完整声明周期的管理。甚至,配置文件还可以置于版本控制系统中进行存储和管理。

重要概念

服务sevices:容器,应用(如单个的web、redis、mysql)

项目project:一组关联的容器(博客、web、my集群)

安装

[root@localhost ~]# sudo curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

[root@localhost ~]# chmod +x /usr/local/bin/docker-compose

[root@localhost ~]# docker-compose version
docker-compose version 1.12.0, build b31ff33
docker-py version: 2.2.1
CPython version: 2.7.13
OpenSSL version: OpenSSL 1.0.1t  3 May 2016
#安装成功

Docker-Compose yml配置文件

定义: Compose 文件是一个YAML文件,定义了 服务网络

默认使用文件名 docker-compose.yml

体验-跟着官网https://docs.docker.com/compose/gettingstarted/

1.创建project 在usr/local/composetest

[root@localhost local]# mkdir composetest
[root@localhost local]# cd composetest/
#创建脚本
[root@localhost composetest]# vim app.py
import time

import redis
from flask import Flask

app = Flask(__name__)
cache = redis.Redis(host='redis', port=6379)

def get_hit_count():
    retries = 5
    while True:
        try:
            return cache.incr('hits')
        except redis.exceptions.ConnectionError as exc:
            if retries == 0:
                raise exc
            retries -= 1
            time.sleep(0.5)

@app.route('/')
def hello():
    count = get_hit_count()
    return 'Hello World! I have been seen {} times.\n'.format(count)

保存,创建 requirements.txt

#创建vim requirements.txt
[root@localhost composetest]# vim requirements.txt
#输入
flask
redis

2.创建Dockerfile

[root@localhost composetest]# vim Dockerfile
# syntax=docker/dockerfile:1
FROM python:3.7-alpine
WORKDIR /code
ENV FLASK_APP=app.py
ENV FLASK_RUN_HOST=0.0.0.0
RUN apk add --no-cache gcc musl-dev linux-headers
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
EXPOSE 5000
COPY . .
CMD ["flask", "run"]

3.创建docker-compose.yml

[root@localhost composetest]# vim docker-compose.yml
version: "3.9"
services:
  web:
    build: .
    ports:
      - "5000:5000"
  redis:
    image: "redis:alpine"

4.运行命令docker-compose up

[root@localhost composetest]# docker-compose up
#问题1
ERROR: Version in "./docker-compose.yml" is unsupported. You might be seeing this error because you're using the wrong Compose file version. Either specify a supported version ("2.0", "2.1", "3.0", "3.1", "3.2") and place your service definitions under the `services` key, or omit the `version` key and place your service definitions at the root of the file to use version 1.
For more on the Compose file format versions, see https://docs.docker.com/compose/compose-file/
#版本不正确换为3.2

#问题2
[root@localhost composetest]# docker-compose up
ERROR: Couldn't connect to Docker daemon at http+docker://localunixsocket - is it running?

If it's at a non-standard location, specify the URL with the DOCKER_HOST environment variable.

#参考https://www.cnblogs.com/360minitao/p/12179629.html
[root@localhost composetest]# sudo groupadd docker
groupadd:“docker”组已存在
[root@localhost composetest]# sudo gpasswd -a ${USER} docker
正在将用户“root”加入到“docker”组中
[root@localhost composetest]# sudo systemctl restart docker

运行成功!!!

image

#访问
[root@localhost composetest]# curl http://172.18.0.2:5000/
Hello World! I have been seen 1 times.
[root@localhost composetest]# curl http://172.18.0.2:5000/
Hello World! I have been seen 2 times.

备注: 更多例子请参看 https://github.com/docker/awesome-compose

docker-compose.yml配置指令

参考 https://docs.docker.com/compose/compose-file/compose-file-v3/

https://www.runoob.com/docker/docker-compose.html

官方例子

#指定本yml 依从compose的哪个版本制定的
version: "3.9"
#服务
services:
  #服务名称
  redis:
    #镜像
    image: redis:alpine
    #端口
    ports:
      - "6379"
    #网络
    networks:
      - frontend
    #依赖
    deploy:
      replicas: 2
      update_config:
        parallelism: 2
        delay: 10s
      restart_policy:
        condition: on-failure

  db:
    image: postgres:9.4
    volumes:
      - db-data:/var/lib/postgresql/data
    networks:
      - backend
    deploy:
      placement:
        max_replicas_per_node: 1
        constraints:
          - "node.role==manager"

  vote:
    image: dockersamples/examplevotingapp_vote:before
    ports:
      - "5000:80"
    networks:
      - frontend
    depends_on:
      - redis
    deploy:
      replicas: 2
      update_config:
        parallelism: 2
      restart_policy:
        condition: on-failure

  result:
    image: dockersamples/examplevotingapp_result:before
    ports:
      - "5001:80"
    networks:
      - backend
    depends_on:
      - db
    deploy:
      replicas: 1
      update_config:
        parallelism: 2
        delay: 10s
      restart_policy:
        condition: on-failure

  worker:
    image: dockersamples/examplevotingapp_worker
    networks:
      - frontend
      - backend
    deploy:
      mode: replicated
      replicas: 1
      labels: [APP=VOTING]
      restart_policy:
        condition: on-failure
        delay: 10s
        max_attempts: 3
        window: 120s
      placement:
        constraints:
          - "node.role==manager"

  visualizer:
    image: dockersamples/visualizer:stable
    ports:
      - "8080:8080"
    stop_grace_period: 1m30s
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock"
    deploy:
      placement:
        constraints:
          - "node.role==manager"
#网络
networks:
  frontend:
  backend:
#挂在卷
volumes:
  db-data:

从例子上可以一级可以分为version(版本)、services(服务)、networks(网络)、volumes(卷)

build

指定为构建镜像上下路径

例如 webapp 服务,指定为从上下文路径 ./dir/Dockerfile 所构建的镜像:

version: "3.7"
services:
  webapp:
    build: ./dir

或者,作为具有在上下文指定的路径的对象,以及可选的 Dockerfile 和 args:

version: "3.7"
services:
  webapp:
    build:
      context: ./dir
      dockerfile: Dockerfile-alternate
      args:
        buildno: 1
      labels:
        - "com.example.description=Accounting webapp"
        - "com.example.department=Finance"
        - "com.example.label-with-empty-value"
      target: prod
  • context:上下文路径。

  • dockerfile:指定构建镜像的 Dockerfile 文件名。

  • args:添加构建参数,它们是只能在构建过程中访问的环境变量。

    #在Dockerfile中指定参数
    # syntax=docker/dockerfile:1
    
    ARG buildno
    ARG gitcommithash
    
    RUN echo "Build number: $buildno"
    RUN echo "Based on commit: $gitcommithash"
    
    #指定参数的值
    build:
      context: .
      args:
        buildno: 1
        gitcommithash: cdc3b19
    #或者以下形式
    build:
      context: .
      args:
        - buildno=1
        - gitcommithash=cdc3b19
    
  • labels:设置构建镜像的标签。

  • target:多层构建,可以指定构建哪一层。详情参考多阶段构建

  • cache_from 在构建Docker镜像时,Docker使用它的构建缓存来检查它是否可以跳过Dockerfile中的任何步骤 ,该参数告诉docker,可用缓存的镜像是什么

  • network:设置网络也可以用none禁用网络

  • shm_size: 设置/dev/shm此构建容器的分区大小

    build:
      context: .
      shm_size: '2gb'
    #或者
    build:
      context: .
      shm_size: 10000000
    

cap_add, cap_drop

添加或删除容器拥有的宿主机的内核功能

cap_add:
  - ALL # 开启全部权限
cap_drop:
  - SYS_PTRACE # 关闭 ptrace权限

cgroup_parent

为容器指定父 cgroup 组,意味着将继承该组的资源限制

cgroup_parent: m-executor-abcd

command

覆盖容器启动的默认命令, 该命令也可以是一个列表,类似于 dockerfile

command: bundle exec thin -p 3000
#或者
command: ["bundle", "exec", "thin", "-p", "3000"]

container_name

指定自定义容器名称,而不是生成默认名称

container_name: my-web-container

注 由于 Docker 容器名称必须是唯一的,因此如果您指定了自定义名称,则不能将服务扩展到 1 个以上的容器。

depends_on

设置依赖关系,服务依赖会导致一下行为

  • docker-compose up按依赖顺序启动服务。在下面的例子中,dbredis在 之前启动web
  • docker-compose up SERVICE自动包含SERVICE的依赖项。在下面的示例中,docker-compose up web还创建并启动dbredis
  • docker-compose stop按依赖顺序停止服务。在以下示例中,webdb和之前停止redis
version: "3.9"
services:
  web:
    build: .
    depends_on:
      - db
      - redis
  redis:
    image: redis
  db:
    image: postgres

注: web 服务不会等待 redis db 完全启动之后才启动。

deploy

指定与服务的部署和运行有关的配置。只在 swarm 模式下才会有用。

version: "3.9"

services:
  wordpress:
    image: wordpress
    ports:
      - "8080:80"
    networks:
      - overlay
    deploy:
      mode: replicated
      replicas: 2
      endpoint_mode: vip

  mysql:
    image: mysql
    volumes:
       - db-data:/var/lib/mysql/data
    networks:
       - overlay
    deploy:
      mode: replicated
      replicas: 2
      endpoint_mode: dnsrr

volumes:
  db-data:

networks:
  overlay:

可选参数:

endpoint_mode : 访问集群服务的方式。

# Docker 集群服务一个对外的虚拟 ip。所有的请求都会通过这个虚拟 ip 到达集群服务内部的机器。
endpoint_mode: vip 
# DNS 轮询(DNSRR)。所有的请求会自动轮询获取到集群 ip 列表中的一个 ip 地址。
endpoint_mode: dnsrr

labels:在服务上设置标签。可以用容器上的 labels(跟 deploy 同级的配置) 覆盖 deploy 下的 labels。

mode:指定服务提供的模式。

  • 默认replicated:复制服务,复制指定服务到集群的机器上。
    • max_replicas_per_node: 则限制 可以在任何时间在节点上运行的副本数
    • replicas: 运行的容器数量。
  • global:全局服务,服务将部署至集群的每个节点。

placement : 指定约束和首选项的位置

version: "3.9"
services:
  db:
    image: postgres
    deploy:
      placement:
        constraints:
          - "node.role==manager"
          - "engine.labels.operatingsystem==ubuntu 18.04"
        preferences:
          - spread: node.labels.zone

resources: 配置资源约束

#redis服务被限制使用不超过 50M 的内存和0.50(单核的 50%)可用处理时间 (CPU),并保留20M内存和0.25CPU 时间(始终可用)。
version: "3.9"
services:
  redis:
    image: redis:alpine
    deploy:
      resources:
        limits:
          cpus: '0.50'
          memory: 50M
        reservations:
          cpus: '0.25'
          memory: 20M

restart_policy :重启策略, 配置是否以及如何在退出时重新启动容器

  • condition:可选 none,on-failure 或者 any(默认值:any)。
  • delay:设置多久之后重启(默认值: 5s )。
  • max_attempts:尝试重新启动容器的次数,超出次数,则不再尝试(默认值:一直重试)。
  • window:设置容器重启超时时间(默认值:0)。
version: "3.9"
services:
 redis:
   image: redis:alpine
   deploy:
     restart_policy:
       condition: on-failure
       delay: 5s
       max_attempts: 3
       window: 120s

rollback_config: 配置在更新失败的情况下应如何回滚服务

  • parallelism:一次要回滚的容器数。如果设置为0,则所有容器将同时回滚。
  • delay:每个容器组回滚之间等待的时间(默认为0s)。
  • failure_action:如果回滚失败,该怎么办。其中一个 continue 或者 pause(默认pause)。
  • monitor:每个容器更新后,持续观察是否失败了的时间 (ns|us|ms|s|m|h)(默认为 5s ) 注意:设置为 0 将使用默认 5s 。
  • max_failure_ratio:在回滚期间可以容忍的故障率(默认为0)。
  • order:回滚期间的操作顺序。其中一个 stop-first(串行回滚),或者 start-first(并行回滚)(默认 stop-first )。

update_config : 配置应如何更新服务,对于配置滚动更新很有用

  • parallelism:一次更新的容器数。
  • delay:在更新一组容器之间等待的时间。
  • failure_action:如果更新失败,该怎么办。其中一个 continue,rollback 或者pause (默认:pause)。
  • monitor:每个容器更新后,持续观察是否失败了的时间 (ns|us|ms|s|m|h) (默认 5s)注意:设置为 0 将使用默认 5s。
  • max_failure_ratio:在更新过程中可以容忍的故障率。
  • order:回滚期间的操作顺序。其中一个 stop-first(串行回滚),或者 start-first(并行回滚)(默认stop-first) 注意:仅支持 v3.4 及更高版本。
version: "3.9"
services:
  vote:
    image: dockersamples/examplevotingapp_vote:before
    depends_on:
      - redis
    deploy:
      replicas: 2
      update_config:
        parallelism: 2
        delay: 10s
        order: stop-first

devices

指定设备映射列表 . 使用与--devicedocker 客户端创建选项相同的格式。

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

dns

自定义 DNS 服务器。可以是单个值或列表。

dns: 8.8.8.8
#列表
dns:
  - 8.8.8.8
  - 9.9.9.9

自定义 DNS 搜索域。可以是单个值或列表

dns_search: example.com
#列表
dns_search:
  - dc1.example.com
  - dc2.example.com

entrypoint

覆盖默认入口点

entrypoint: /code/entrypoint.sh

入口点也可以是一个列表

entrypoint: ["php", "-d", "memory_limit=-1", "vendor/bin/phpunit"]

注: 设置entrypoint两者都会使用ENTRYPOINTDockerfile 指令覆盖在服务映像上设置的任何默认入口点,清除映像上的任何默认命令 - 这意味着如果CMDDockerfile 中有指令,则将其忽略。

env_file

从文件添加环境变量。可以是单个值或列表

如果您使用 指定了 Compose 文件docker-compose -f FILE,则其中的路径 env_file相对于该文件所在的目录。

environment部分中 声明的环境变量会覆盖这些值——即使这些值是空的或未定义的,也是如此。

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

Compose 期望 env 文件中的每一行都符合VAR=VAL格式。以 开头的行#被视为注释并被忽略。空行也会被忽略。

# Set Rails/Rack environment
RACK_ENV=development

备注: 列表中文件的顺序对于确定分配给多次出现的变量的值很重要。列表中的文件是从上到下处理的。对于在 file 中指定的相同变量a.env并在 file 中 分配了不同的值b.env,如果b.env在下面(之后)列出,则值来自b.env代表

environment

添加环境变量。您可以使用数组或字典、任何布尔值,布尔值需要用引号引起来,以确保 YML 解析器不会将其转换为 True 或 False。

environment:
  RACK_ENV: development
  SHOW: 'true'
  SESSION_SECRET:
#或者
environment:
  - RACK_ENV=development
  - SHOW=true
  - SESSION_SECRET

expose

暴露端口,但不映射到宿主机,只被连接的服务访问。

仅可以指定内部端口为参数:

expose:
 - "3000"
 - "8000"

链接到在此之外docker-compose.yml甚至 Compose 之外启动的容器,尤其是对于提供共享或公共服务的容器。 在指定容器名称和链接别名 ( )时,external_links遵循类似于 legacy 选项的语义。links CONTAINER:ALIAS

external_links:
  - redis_1
  - project_db_1:mysql
  - project_db_1:postgresql

extra_hosts

添加主机名映射。类似 docker client --add-host。

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

/etc/hosts此服务的内部容器中创建一个包含 ip 地址和主机名的条目,例如:

162.242.195.82  somehost
50.31.209.229   otherhost

healthcheck

用于检测 docker 服务是否健康运行。

healthcheck:
  test: ["CMD", "curl", "-f", "http://localhost"] # 设置检测程序
  interval: 1m30s # 设置检测间隔
  timeout: 10s # 设置检测超时时间
  retries: 3 # 设置重试次数
  start_period: 40s # 启动后,多少秒开始启动检测程序

image

指定启动容器的镜像。可以是存储库/标签或部分图像 ID。

image: redis
image: ubuntu:14.04
image: tutum/influxdb
image: example-registry.com:4000/postgresql
image: a4bc65fd # 镜像id

logging

服务的日志记录配置

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

driver:指定服务容器的日志记录驱动程序,默认值为json-file。有以下三个选项

driver: "json-file"
driver: "syslog"
driver: "none"

仅在 json-file 驱动程序下,可以使用以下参数,限制日志得数量和大小。

logging:
  driver: json-file
  options:
    max-size: "200k" # 单个文件大小为200k
    max-file: "10" # 最多10个文件

当达到文件限制上限,会自动删除旧得文件。

syslog 驱动程序下,可以使用 syslog-address 指定日志接收地址。

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

network_mode

设置网络模式。

network_mode: "bridge"
network_mode: "host"
network_mode: "none"
network_mode: "service:[service name]"
network_mode: "container:[container name/id]"

networks : 配置容器连接的网络,引用顶级 networks 下的条目

services:
  some-service:
    networks:
      some-network:
        aliases:
         - alias1
      other-network:
        aliases:
         - alias2
networks:
  some-network:
    # Use a custom driver
    driver: custom-driver-1
  other-network:
    # Use a custom driver which takes special options
    driver: custom-driver-2

aliases :同一网络上的其他容器可以使用服务名称或此别名来连接到对应容器的服务。

restart

  • no:是默认的重启策略,在任何情况下都不会重启容器。
  • always:容器总是重新启动。
  • on-failure:在容器非正常退出时(退出状态非0),才会重启容器。
  • unless-stopped:在容器退出时总是重启容器,但是不考虑在Docker守护进程启动时就已经停止了的容器
restart: "no"
restart: always
restart: on-failure
restart: unless-stopped

注:swarm 集群模式,请改用 restart_policy。

secrets

存储敏感数据,例如密码:

version: "3.1"
services:

mysql:
  image: mysql
  environment:
    MYSQL_ROOT_PASSWORD_FILE: /run/secrets/my_secret
  secrets:
    - my_secret

secrets:
  my_secret:
    file: ./my_secret.txt

security_opt

修改容器默认的 schema 标签。

security-opt:
  - label:user:USER   # 设置容器的用户标签
  - label:role:ROLE   # 设置容器的角色标签
  - label:type:TYPE   # 设置容器的安全策略标签
  - label:level:LEVEL  # 设置容器的安全等级标签

stop_grace_period

指定在容器无法处理 SIGTERM (或者任何 stop_signal 的信号),等待多久后发送 SIGKILL 信号关闭容器。

stop_grace_period: 1s # 等待 1 秒
stop_grace_period: 1m30s # 等待 1 分 30 秒 

默认的等待时间是 10 秒。

stop_signal

设置停止容器的替代信号。默认情况下使用 SIGTERM 。

以下示例,使用 SIGUSR1 替代信号 SIGTERM 来停止容器。

stop_signal: SIGUSR1

sysctls

设置容器中的内核参数,可以使用数组或字典格式。

sysctls:
  net.core.somaxconn: 1024
  net.ipv4.tcp_syncookies: 0

sysctls:
  - net.core.somaxconn=1024
  - net.ipv4.tcp_syncookies=0

tmpfs

在容器内安装一个临时文件系统。可以是单个值或列表的多个值。

tmpfs: /run

tmpfs:
  - /run
  - /tmp

ulimits

覆盖容器默认的 ulimit。

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

volumes

将主机的数据卷或着文件挂载到容器里。

version: "3.7"
services:
  db:
    image: postgres:latest
    volumes:
      - "/localhost/postgres.sock:/var/run/postgres/postgres.sock"
      - "/localhost/data:/var/lib/postgresql/data"

命令

常规套路,先看文档

[root@localhost ~]# docker-compose --help
Define and run multi-container applications with Docker.

Usage:
  docker-compose [-f <arg>...] [options] [COMMAND] [ARGS...]
  docker-compose -h|--help

Options:
  #指定具体文件
  -f, --file FILE             Specify an alternate compose file (default: docker-compose.yml)
  #指定docker-conpose的项目目录,默认当前所在目录为项目名
  -p, --project-name NAME     Specify an alternate project name (default: directory name)
  #输出更多调试信息
  --verbose                   Show more output
  -v, --version               Print version and exit
  -H, --host HOST             Daemon socket to connect to

  --tls                       Use TLS; implied by --tlsverify
  --tlscacert CA_PATH         Trust certs signed only by this CA
  --tlscert CLIENT_CERT_PATH  Path to TLS certificate file
  --tlskey TLS_KEY_PATH       Path to TLS key file
  --tlsverify                 Use TLS and verify the remote
  --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)
  --project-directory PATH    Specify an alternate working directory
                              (default: the path of the compose file)

Commands:
  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 build 构建

[root@localhost composetest]# docker-compose build --help
Build or rebuild services.

Services are built once and then tagged as `project_service`,
e.g. `composetest_db`. If you change a service's `Dockerfile` or the
contents of its build directory, you can run `docker-compose build` to rebuild it.

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.
    #key=val为服务设置build-time变量
    --build-arg key=val     Set build-time variables for one service.
[root@localhost composetest]# docker-compose build
Building web
Step 1/10 : FROM python:3.7-alpine
 ---> 93ac4b41defe
Step 2/10 : WORKDIR /code
 ---> Using cache
 ---> 7f55091b354f
Step 3/10 : ENV FLASK_APP=app.py
 ---> Using cache
 ---> 2bbd96fd9bad
Step 4/10 : ENV FLASK_RUN_HOST=0.0.0.0
 ---> Using cache
 ---> f21a77b69dde
Step 5/10 : RUN apk add --no-cache gcc musl-dev linux-headers
 ---> Using cache
 ---> f41e76bffe66
Step 6/10 : COPY requirements.txt requirements.txt
 ---> Using cache
 ---> 11186aedc8cc
Step 7/10 : RUN pip install -r requirements.txt
 ---> Using cache
 ---> e9ecb3ba1010
Step 8/10 : EXPOSE 5000
 ---> Using cache
 ---> 5bd388588337
Step 9/10 : COPY . .
 ---> Using cache
 ---> 0bdaccdd5bd5
Step 10/10 : CMD ["flask", "run"]
 ---> Using cache
 ---> fc1c57bfc030
Successfully built fc1c57bfc030
Successfully tagged composetest_web:latest
redis uses an image, skipping

docker-compose config 查看配置信息

[root@localhost composetest]# docker-compose config --help
Validate and view the compose file.

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.
#查看配置信息
[root@localhost composetest]# docker-compose config
networks: {}
services:
  redis:
    image: redis:alpine
  web:
    build:
      context: /usr/local/composetest
    ports:
    - 5000:5000/tcp
version: '3.2'
volumes: {}

docker-compose create 为服务创建容器

[root@localhost composetest]# docker-compose create --help
Creates containers for a service.

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 up 构建,(重新)创建,启动并附加到服务的容器

[root@localhost composetest]# docker-compose up --help
Builds, (re)creates, starts, and attaches to containers for a service.

Unless they are already running, this command also starts any linked services.

The `docker-compose up` command aggregates the output of each container. When
the command exits, all containers are stopped. Running `docker-compose up -d`
starts the containers in the background and leaves them running.

If there are existing containers for a service, and the service's configuration
or image was changed after the container's creation, `docker-compose up` picks
up the changes by stopping and recreating the containers (preserving mounted
volumes). To prevent Compose from picking up changes, use the `--no-recreate`
flag.

If you want to force Compose to stop and recreate all containers, use the
`--force-recreate` flag.

Usage: up [options] [SERVICE...]

Options:
	#后台执行
    -d                         Detached mode: Run containers in the background,
                               print new container names.
                               Incompatible with --abort-on-container-exit.
	#不是有颜色来区分不同的服务的控制输出
    --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.
    #在启动容器前构建服务镜像
    --build                    Build images before starting containers.
    #停止所有容器,如果任何一个容器被停止,不能与-d同时使用
    --abort-on-container-exit  Stops all containers if any container was stopped.
                               Incompatible with -d.
	#停止容器时候的超时时间(默认为10秒)
    -t, --timeout TIMEOUT      Use this timeout in seconds for container shutdown
                               when attached or when containers are already
                               running. (default: 10)
	#删除服务中没有在compose文件中定义的容器
    --remove-orphans           Remove containers for services not
                               defined in the Compose file
    --exit-code-from SERVICE   Return the exit code of the selected service container.
                               Requires --abort-on-container-exit.
[root@localhost composetest]# docker-compose up -d
composetest_web_2 is up-to-date
composetest_web_1 is up-to-date
composetest_web_3 is up-to-date
composetest_redis_1 is up-to-date
composetest_redis_2 is up-to-date

docker-compose down 停止和删除容器、网络、卷、镜像

[root@localhost composetest]# docker-compose down --help
Stops containers and removes containers, networks, volumes, and images
created by `up`.

By default, the only things removed are:

- Containers for services defined in the Compose file
- Networks defined in the `networks` section of the Compose file
- The default network, if one is used

Networks and volumes defined as `external` are never removed.

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
#容器删除镜像未删除
[root@localhost composetest]# docker-compose down
Removing composetest_redis_1 ... done
Removing composetest_web_1 ... done
Removing network composetest_default
[root@localhost composetest]# docker ps -a
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@localhost composetest]# docker images
REPOSITORY        TAG          IMAGE ID       CREATED       SIZE
composetest_web   latest       fc1c57bfc030   9 hours ago   184MB
python            3.7-alpine   93ac4b41defe   2 days ago    41.9MB
redis             alpine       1690b63e207f   4 weeks ago   32.3MB

docker-compose events 以json的形式输出docker日志

[root@localhost composetest]# docker-compose events --help
Receive real time events from containers.

Usage: events [options] [SERVICE...]

Options:
    --json      Output events as a stream of json objects

docker-compose exec 这相当于docker exec

[root@localhost composetest]# docker-compose exec --help
Execute a command in a running container

Usage: exec [options] SERVICE COMMAND [ARGS...]

Options:
	#分离模式,后台运行命令
    -d                Detached mode: Run command in the background.
    #获取特权
    --privileged      Give extended privileges to the process.
    #指定运行的用户
    --user USER       Run the command as this user.
    #禁用分配TTY,默认docker-compose exec分配TTY
    -T                Disable pseudo-tty allocation. By default `docker-compose exec`
                      allocates a TTY.
	#当一个服务拥有多个容器时,可通过该参数登陆到该服务下的任何服务,例如:docker-compose exec –index=1 web /bin/bash ,web服务中包含多个容器
    --index=index     index of the container if there are multiple
                      instances of a service [default: 1]

[root@localhost composetest]# cat docker-compose.yml 
version: "3.2"
services:
  web:
    build: .
    ports:
      - "5000:5000"
  redis:
    image: "redis:alpine"
#有配置文件可知service为redis和web
[root@localhost composetest]# docker-compose exec web echo 'hello'
hello
[root@localhost composetest]# docker-compose exec web sh
/code # ls
Dockerfile          __pycache__         app.py              docker-compose.yml  requirements.txt
/code # 

docker-compose images 查看镜像列表

[root@localhost composetest]# docker-compose images --help
List images used by the created containers.
Usage: images [options] [SERVICE...]

Options:
-q     Only display IDs
[root@localhost composetest]# docker-compose images
     Container          Repository       Tag       Image Id      Size   
-----------------------------------------------------------------------
composetest_redis_1   redis             alpine   1690b63e207f   30.8 MB 
composetest_web_1     composetest_web   latest   fc1c57bfc030   175 MB  

[root@localhost composetest]# docker-compose images -q
1690b63e207f6651429bebd716ace700be29d0110a0cfefff5038bb2a7fb6fc7
fc1c57bfc03073c479385be1f3711083b7df02eb63be4d4601c09b722038bf12

docker-compose kill 运行容器的强制通过发送SIGKILL信号来停止。可以选择传递信号

[root@localhost composetest]# docker-compose kill --help
Force stop service containers.

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

Options:
    -s SIGNAL         SIGNAL to send to the container.
                      Default signal is SIGKILL.
[root@localhost composetest]# docker-compose kill
Killing composetest_web_1 ... done
Killing composetest_redis_1 ... done
[root@localhost composetest]# docker ps -a
CONTAINER ID   IMAGE             COMMAND                  CREATED          STATUS                       PORTS     NAMES
01a8e7366fbb   composetest_web   "flask run"              21 minutes ago   Exited (137) 7 seconds ago             composetest_web_1
c201a3425f0d   redis:alpine      "docker-entrypoint.s…"   21 minutes ago   Exited (137) 7 seconds ago             composetest_redis_1

docker-compose logs 查看服务容器的输出。默认情况下,docker-compose将对不同的服务输出使用不同的颜色来区分。可以通过–no-color来关闭颜色。

[root@localhost composetest]# docker-compose logs --help
View output from containers.

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

Options:
    --no-color          Produce monochrome output.
    #跟踪日志输出持续输出ctrl+c退出
    -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.
#截取了部分日志
[root@localhost composetest]# docker-compose logs -f
Attaching to composetest_web_1, composetest_redis_1
web_1    |  * Serving Flask app 'app.py' (lazy loading)
web_1    |  * Environment: production
web_1    |    WARNING: This is a development server. Do not use it in a production deployment
web_1    |  * Serving Flask app 'app.py' (lazy loading)
web_1    |  * Environment: production
web_1    |    WARNING: This is a development server. Do not use it in a production deployment.
web_1    |    Use a production WSGI server instead.
web_1    |  * Debug mode: off
web_1    |  * Running on all addresses.
web_1    |    WARNING: This is a development server. Do not use it in a production deployment.
web_1    |  * Running on http://172.19.0.3:5000/ (Press CTRL+C to quit)
redis_1  | 1:C 02 Jul 2021 18:14:55.980 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
redis_1  | 1:C 02 Jul 2021 18:14:55.980 # Redis version=6.2.4, bits=64, commit=00000000, modified=0, pid=1, just started
redis_1  | 1:M 02 Jul 2021 18:37:23.267 # Server initialized
redis_1  | 1:M 02 Jul 2021 18:37:23.268 * Loading RDB produced by version 6.2.4
redis_1  | 1:M 02 Jul 2021 18:37:23.268 * RDB age 1334 seconds
redis_1  | 1:M 02 Jul 2021 18:37:23.268 * RDB memory usage when created 0.77 Mb
redis_1  | 1:M 02 Jul 2021 18:37:23.268 * DB loaded from disk: 0.000 seconds
redis_1  | 1:M 02 Jul 2021 18:37:23.268 * Ready to accept connections

docker-compose pause 暂停容器

[root@localhost composetest]# docker-compose pause --help
Pause services.

Usage: pause [SERVICE...]
[root@localhost composetest]# clear
[root@localhost composetest]# docker-compose pause web
Pausing composetest_web_1 ... done

[root@localhost composetest]# docker-compose pause
Pausing composetest_redis_1 ... done
Pausing composetest_web_1 ... error

ERROR: for composetest_web_1  Container 01a8e7366fbb1d2c34bc361a157a3abdbd2c8b654bcd48c0e56847d2c22452a0 is already paused

docker-compose unpause 停止暂停

[root@localhost composetest]# docker-compose unpause --help
Unpause services.

Usage: unpause [SERVICE...]
[root@localhost composetest]# docker-compose unpause
Unpausing composetest_web_1 ... done
Unpausing composetest_redis_1 ... done

docker-compose port 打印端口绑定的公共端口

[root@localhost composetest]# docker-compose port --help
Print the public port for a port binding.

Usage: port [options] SERVICE PRIVATE_PORT

Options:
	#指定端口协议,TCP(默认值)或者UDP
    --protocol=proto  tcp or udp [default: tcp]
    #如果同意服务存在多个容器,指定命令对象容器的序号(默认为1)
    --index=index     index of the container if there are multiple
                      instances of a service [default: 1]
[root@localhost composetest]# docker-compose port web 5000
0.0.0.0:5000
[root@localhost composetest]# docker-compose port --index 2  web 5000
ERROR: No container found for web_2
[root@localhost composetest]# docker-compose port --index 1  web 5000
0.0.0.0:5000

docker-compose ps 容器列表

[root@localhost ~]# docker-compose ps --help
List containers.

Usage: ps [options] [SERVICE...]

Options:
    -q    Only display IDs
[root@localhost composetest]# docker-compose ps
       Name                      Command               State           Ports          
-------------------------------------------------------------------------------------
composetest_redis_1   docker-entrypoint.sh redis ...   Up      6379/tcp               
composetest_web_1     flask run                        Up      0.0.0.0:5000->5000/tcp 
[root@localhost composetest]# docker-compose ps -q
c201a3425f0d1a8b496a691fa0ef740cc6c91453a56b16946c5de4617fce7fea
01a8e7366fbb1d2c34bc361a157a3abdbd2c8b654bcd48c0e56847d2c22452a0

docker-compose pull 提取与在docker-compose.yml 文件中定义的服务相关联的映像,但不会基于这些映像启动容器。

[root@localhost composetest]# docker-compose pull --help
Pulls images for services.

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

Options:
	#忽略拉取镜像过程中的错误
    --ignore-pull-failures  Pull what it can and ignores images with pull failures.
    #多个镜像同时拉取
    --parallel              Pull multiple images in parallel.
[root@localhost composetest]# docker-compose pull 
Pulling redis (redis:alpine)...
alpine: Pulling from library/redis
5843afab3874: Already exists
9db2305878ef: Pull complete
3558750a1d54: Pull complete
240d71d1acc7: Pull complete
2a888d25337f: Pull complete
22e6fbce362a: Pull complete
Digest: sha256:442fbfdeccf203c277827cfd8e7e727ce411611e1a6caeda9cca8115ed17b9cc
Status: Downloaded newer image for redis:alpine
[root@localhost composetest]# docker-compose pull --parallel
Pulling web ... done
Pulling redis ... done

docker-compose push 推送服务依的镜像

[root@localhost composetest]# docker-compose push --help
Pushes images for services.

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

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

docker-compose restart 重启

[root@localhost composetest]# docker-compose restart --help
Restart running containers.

Usage: restart [options] [SERVICE...]

Options:
 #指定重启前停止容器的超时时间
  -t, --timeout TIMEOUT      Specify a shutdown timeout in seconds.
                             (default: 10)

[root@localhost composetest]# docker-compose restart 
Restarting composetest_web_1 ... done
Restarting composetest_redis_1 ... done
[root@localhost composetest]# docker-compose restart -t 10
Restarting composetest_web_1 ... done
Restarting composetest_redis_1 ... done

docker-compose rm 移除容器

[root@localhost composetest]# docker-compose rm --help
Removes stopped service containers.

By default, anonymous volumes attached to containers will not be removed. You
can override this with `-v`. To list all volumes, use `docker volume ls`.

Any data which is not in a volume will be lost.

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.
#查看容器
[root@localhost composetest]# docker-compose ps
       Name                      Command               State           Ports          
-------------------------------------------------------------------------------------
composetest_redis_1   docker-entrypoint.sh redis ...   Up      6379/tcp               
composetest_web_1     flask run                        Up      0.0.0.0:5000->5000/tcp 
#查看镜像
[root@localhost composetest]# docker-compose images
     Container          Repository       Tag       Image Id      Size   
-----------------------------------------------------------------------
composetest_redis_1   redis             alpine   500703a12fa4   30.8 MB 
composetest_web_1     composetest_web   latest   fc1c57bfc030   175 MB  
#移除停止的容器
[root@localhost composetest]# docker-compose rm
No stopped containers
#停止容器
[root@localhost composetest]# docker-compose stop
Stopping composetest_redis_1 ... done
Stopping composetest_web_1 ... done
#移除容器
[root@localhost composetest]# docker-compose rm
Going to remove composetest_redis_1, composetest_web_1
Are you sure? [yN] y
Removing composetest_redis_1 ... done
Removing composetest_web_1 ... done
#查看compose容器
[root@localhost composetest]# docker-compose ps
Name   Command   State   Ports 
------------------------------
#查看compose镜像
[root@localhost composetest]# docker-compose images
Container   Repository   Tag   Image Id   Size 
----------------------------------------------
#查看镜像
[root@localhost composetest]# docker images
REPOSITORY        TAG          IMAGE ID       CREATED                  SIZE
redis             alpine       500703a12fa4   Less than a second ago   32.3MB
composetest_web   latest       fc1c57bfc030   10 hours ago             184MB
python            3.7-alpine   93ac4b41defe   2 days ago               41.9MB
redis             <none>       1690b63e207f   4 weeks ago              32.3MB
[root@localhost composetest]# docker ps -a
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

docker-compose run 针对服务运行一次性命令

[root@localhost composetest]# docker-compose run --help
Run a one-off command on a service.

For example:

    $ docker-compose run web python manage.py shell

By default, linked services will be started, unless they are already
running. If you do not want to start linked services, use
`docker-compose run --no-deps SERVICE COMMAND [ARGS...]`.

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

Options:
    #后台执行
    -d                    Detached mode: Run container in the background, print
                          new container name.
	#命名
    --name NAME           Assign a name to the container
    --entrypoint CMD      Override the entrypoint of the image.
    -e KEY=VAL            Set an environment variable (can be used multiple times)
    -u, --user=""         Run as specified username or uid
    --no-deps             Don't start linked services.
    --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 [])
    -T                    Disable pseudo-tty allocation. By default `docker-compose run`
                          allocates a TTY.
    -w, --workdir=""      Working directory inside the container

[root@localhost composetest]# docker-compose run web echo 'hello'
hello
[root@localhost composetest]# docker-compose ps
       Name                      Command               State           Ports          
-------------------------------------------------------------------------------------
composetest_redis_1   docker-entrypoint.sh redis ...   Up      6379/tcp               
composetest_web_1     flask run                        Up      0.0.0.0:5000->5000/tcp 
[root@localhost composetest]# docker ps -a
CONTAINER ID   IMAGE             COMMAND                  CREATED          STATUS                      PORTS                                       NAMES
f843a97b2586   composetest_web   "echo hello"             16 seconds ago   Exited (0) 15 seconds ago                                               composetest_web_run_1
7cbb498ed8a4   composetest_web   "flask run"              5 minutes ago    Up 5 minutes                0.0.0.0:5000->5000/tcp, :::5000->5000/tcp   composetest_web_1
357bc89222e0   redis:alpine      "docker-entrypoint.s…"   5 minutes ago    Up 5 minutes                6379/tcp                                    composetest_redis_1
[root@localhost composetest]# docker ps
CONTAINER ID   IMAGE             COMMAND                  CREATED         STATUS         PORTS                                       NAMES
7cbb498ed8a4   composetest_web   "flask run"              5 minutes ago   Up 5 minutes   0.0.0.0:5000->5000/tcp, :::5000->5000/tcp   composetest_web_1
357bc89222e0   redis:alpine      "docker-entrypoint.s…"   5 minutes ago   Up 5 minutes   6379/tcp                                    composetest_redis_1

docker-compose scale 设置为服务运行的容器数量

[root@localhost composetest]# docker-compose scale --help
Set number of containers to run for a service.

Numbers are specified in the form `service=num` as arguments.
For example:

    $ docker-compose scale web=2 worker=3

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

Options:
  -t, --timeout TIMEOUT      Specify a shutdown timeout in seconds.
                             (default: 10)
#添加端口
[root@localhost composetest]# vim docker-compose.yml
version: "3.2"
services:
  web:
    build: .
    ports:
      - "5000:5000"
      - "5001:5001"
      - "5002:5002"
  redis:
    image: "redis:alpine"
#启动三个web服务,两个redis服务
[root@localhost composetest]# docker-compose scale web=3 redis=2
Creating and starting composetest_web_1 ... done
Creating and starting composetest_web_2 ... error
Creating and starting composetest_web_3 ... error

ERROR: for composetest_web_3  Cannot start service web: driver failed programming external connectivity on endpoint composetest_web_3 (ce49c9fe8c31f2dcc0d3bfddf109c4e941970a943ee35900a29e8db1a5e28d7e): Bind for 0.0.0.0:5002 failed: port is already allocated

ERROR: for composetest_web_2  Cannot start service web: driver failed programming external connectivity on endpoint composetest_web_2 (5f6f95a6a6a78e9aa2e556717f96339484047554fdfc8930525d4db5ebb7b6c6): Bind for 0.0.0.0:5002 failed: port is already allocated
Creating and starting composetest_redis_1 ... done
Creating and starting composetest_redis_2 ... done
#端口占用,删除原来的容器,修改docker-compose-yml文件,去掉端口映射,重新执行命令
[root@localhost composetest]# docker-compose scale web=3 redis=2
Creating and starting composetest_web_1 ... done
Creating and starting composetest_web_2 ... done
Creating and starting composetest_web_3 ... done
Creating and starting composetest_redis_1 ... done
Creating and starting composetest_redis_2 ... done
[root@localhost composetest]# docker-compose ps
       Name                      Command               State    Ports   
-----------------------------------------------------------------------
composetest_redis_1   docker-entrypoint.sh redis ...   Up      6379/tcp 
composetest_redis_2   docker-entrypoint.sh redis ...   Up      6379/tcp 
composetest_web_1     flask run                        Up      5000/tcp 
composetest_web_2     flask run                        Up      5000/tcp 
composetest_web_3     flask run                        Up      5000/tcp 

docker-compose start 启动已存在的容器

[root@localhost composetest]# docker-compose start --help
Start existing containers.

Usage: start [SERVICE...]
[root@localhost composetest]# docker-compose ps
       Name                      Command                State     Ports 
-----------------------------------------------------------------------
composetest_redis_1   docker-entrypoint.sh redis ...   Exit 0           
composetest_redis_2   docker-entrypoint.sh redis ...   Exit 0           
composetest_web_1     flask run                        Exit 137         
composetest_web_2     flask run                        Exit 137         
composetest_web_3     flask run                        Exit 137         
[root@localhost composetest]# docker-compose start web
Starting web ... done
[root@localhost composetest]# docker-compose ps
       Name                      Command               State     Ports   
------------------------------------------------------------------------
composetest_redis_1   docker-entrypoint.sh redis ...   Exit 0            
composetest_redis_2   docker-entrypoint.sh redis ...   Exit 0            
composetest_web_1     flask run                        Up       5000/tcp 
composetest_web_2     flask run                        Up       5000/tcp 
composetest_web_3     flask run                        Up       5000/tcp 
#会启动所有服务名为web的容器

docker-compose stop 停止运行中的容器

[root@localhost composetest]# docker-compose stop --help
Stop running containers without removing them.

They can be started again with `docker-compose start`.

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

Options:
  -t, --timeout TIMEOUT      Specify a shutdown timeout in seconds.
                             (default: 10)

[root@localhost composetest]# docker-compose stop
Stopping composetest_redis_1 ... done
Stopping composetest_redis_2 ... done
Stopping composetest_web_2 ... done
Stopping composetest_web_1 ... done
Stopping composetest_web_3 ... done

docker-compose top 显示正在运行的进程。

[root@localhost composetest]# docker-compose top --help
Display the running processes

Usage: top [SERVICE...]
[root@localhost composetest]# docker-compose top
composetest_redis_1
  UID      PID    PPID    C   STIME   TTY     TIME             CMD         
--------------------------------------------------------------------------
polkitd   22689   22669   0   04:50   ?     00:00:00   redis-server *:6379 

composetest_redis_2
  UID      PID    PPID    C   STIME   TTY     TIME             CMD         
--------------------------------------------------------------------------
polkitd   22875   22830   0   04:50   ?     00:00:00   redis-server *:6379 

composetest_web_1
UID     PID    PPID    C   STIME   TTY     TIME                          CMD                       
--------------------------------------------------------------------------------------------------
root   22884   22856   0   04:50   ?     00:00:00   /usr/local/bin/python /usr/local/bin/flask run 

composetest_web_2
UID     PID    PPID    C   STIME   TTY     TIME                          CMD                       
--------------------------------------------------------------------------------------------------
root   22722   22696   0   04:50   ?     00:00:00   /usr/local/bin/python /usr/local/bin/flask run 

composetest_web_3
UID     PID    PPID    C   STIME   TTY     TIME                          CMD                       
--------------------------------------------------------------------------------------------------
root   23013   22994   0   04:51   ?     00:00:00   /usr/local/bin/python /usr/local/bin/flask run 

docker-compose version

[root@localhost composetest]# docker-compose version --help
Show version informations

Usage: version [--short]

Options:
    --short     Shows only Compose's version number.
[root@localhost composetest]# docker-compose version
docker-compose version 1.12.0, build b31ff33
docker-py version: 2.2.1
CPython version: 2.7.13
OpenSSL version: OpenSSL 1.0.1t  3 May 2016
[root@localhost composetest]# docker-compose version --short
1.12.0
posted @ 2021-07-07 11:27  zhao56  阅读(876)  评论(0编辑  收藏  举报