docker-compose用于定义和运行多个docker容器。采用YAML文件配置应用服务,可从配置文件启动相关服务,一条命令能够启动多个容器。node
compose将所管理的容器分为三层:工程(project)、服务(service)、容器(container)。compose运行目录下的全部文件组成一个工程,一个工程包含多个服务,每一个服务中定义了容器运行的镜像、参数、依赖,一个服务可包含多个容器实例。mysql
应用compose通常分为3步:linux
用Dockerfile定义app环境,使app能够在任何地方reproduced。nginx
用docker-compose.yml定义services,使相关services在隔离环境下一块儿运行。git
docker-compose up,启动compose和整个apps。github
一个docker-compose.yml示例以下:web
version: '3' services: web: build: . ports: - "5000:5000" volumes: - .:/code - logvolume01:/var/log links: - redis redis: image: redis
volumes: logvolume01: {}
compose特性:redis
单主机上隔离环境,compose工程间相互独立。用命令行选项-p或COMPOSE_PROJECT环境变量定义工程名。sql
容器建立时保留volume上数据。docker
仅仅在容器改变时再建立容器。compose缓存了配置,restart时compose re-use存在的未改变的容器。
compose file支持变量,能够经过变量为不一样环境定制composition。
目前docker-compose能够安装到macOS,Windows和64-bit Linux系统下。
linux下镜像位于 Compose repository release page on GitHub,安装方法以下:
sudo curl -L"https://github.com/docker/compose/releases/download/1.24.0/docker-compose-$(uname -s)-$(uname -m)"-o /usr/local/bin/docker-compose sudo chmod +x /usr/local/bin/docker-compose docker-compose --version docker-compose version 1.24.0, build 1110ad01
若要安装其余版本能够修改版本号1.24.0。
或pip安装:
pip install docker-compose
卸载compose:
sudo rm /usr/local/bin/docker-compose
或pip卸载(加入compose用pip安装的话):
pip uninstall docker-compose
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),env:COMPOSE_FILE -p, --project-name NAME Specify an alternate project name (default: directory name),env:COMPOSE_PROJECT_NAME --verbose Show more output --log-level LEVEL Set log level (DEBUG, INFO, WARNING, ERROR, CRITICAL) --no-ansi Do not print ANSI control characters -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 --project-directory PATH Specify an alternate working directory (default: the path of the Compose file) --compatibility If set, Compose will attempt to convert deploy keys in v3 files to their non-Swarm equivalent 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 up或docker-compose up -d(后台运行)。
docker-compose -f docker-compose.yaml up -d
docker-compose -f docker-compose.yaml up -d consul
up/run/start区别:
docker-compose up用于start或restart全部定义在docker-compose.yml内的服务。
docker-compose run用于一次性或临时的任务,相似docker run -it(打开交互终端执行命令后退出并返回容器的退出状态)。
docker-compose start用于restart原来建立但中止的容器,毫不会建立新容器。
logs:日志输出信息
--no-color 单色输出,不显示其余颜. -f, --follow 跟踪日志输出,就是能够实时查看日志 -t, --timestamps 显示时间戳 --tail 从日志的结尾显示,--tail=200
更新容器
当服务的配置发生更改时,可以使用docker-compose up命令更新配置。此时,compose会删除旧容器并建立新容器,新容器会以不一样的IP地址加入网络,名称保持不变,任何指向旧容器的链接都会被关闭,从新找到新容器并链接上去。
compose配置文件的格式有多个版本:1,2,2.x和3.x,不一样docker版本对应不一样版本compose file。Compose file是YAML文件,用于定义services、networks和volumes,默认为./docker-compose.yml。详细语法介绍可参考:Compose file version 3 reference。
YAML(Yet Another Markup Language),是一个JSON的超集,意味着任何有效JSON文件也都是一个YAML文件。它规则以下:
1)大小写敏感
2)使用缩进表示层级关系,但不支持tab缩进,只支持空格
3)缩进的数量不重要但至少一个空格,只要相同层级使用相同数量的空格便可
4)“#”表示注释,从这个字符开始,直到行末,都会被解析器无视
compose的YAML只使用两种类型:Maps和Lists,Maps的子项能够是Lists,Lists的子项也能够是Maps。
Maps:就是一个字典,即key:value的键值对。
image: postgres
Lists:就是一个列表。
ports: - "8000" - "8080" - "8090"
咱们能够看到,能够有任何数量的项在列表中,项的定义以破折号(-)开头,而且和父元素之间存在缩进。
版本3的compose file示例以下:
version: "3" 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: 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四大部分,处于top层。其余包含的子项(sub-options)要相应缩进。
docker-compose.yml定义的每一个服务都必须经过image指定镜像或build指令(须要Dockerfile)来自动构建。在Dockerfile指定的选项,默认状况下会被compose自动获取不须要在compose文件中指定。
》version:指定docker-compose.yml文件的写法格式(版本)
》services:多个容器的集合
》image:指定服务的镜像名称或镜像ID。若是镜像在本地不存在,compose会尝试拉取这个镜像。
services:
web:
image: nginx
在 services 标签下的第二级标签是 web,这个名字是用户本身自定义,它就是服务名称。
》build:配置构建时,compose会利用它来自动构建镜像,该值能够是一个路径,也能够是一个对象,用于指定Dockfile参数。
build: ./dir --------------- build: context: ./dir dockerfile: Dockerfile args: buildno: 1
depends_on:容器依赖,解决启动前后顺序问题。
command:覆盖容器启动后默认执行的命令,能够是一个列表
command: bundle exec thin -p 3000 ---------------------------------- command: [“bundle”,”exec”,”thin”,”-p”,”3000”]
dns:配置 dns 服务器,能够是一个值或列表
dns: 8.8.8.8 ------------ dns: - 8.8.8.8 - 9.9.9.9
dns_search:配置 DNS 搜索域,能够是一个值或列表
dns_search: example.com ------------------------ dns_search: - dc1.example.com - dc2.example.com
environment:环境变量配置,能够用数组或字典两种方式
environment: RACK_ENV: development SHOW: 'ture' ------------------------- environment: - RACK_ENV=development - SHOW=ture
env_file:从文件中获取环境变量,能够指定一个文件路径或路径列表,其优先级低于 environment 指定的环境变量
env_file: .env --------------- env_file: - ./common.env
expose:暴露端口,只将端口暴露给链接的服务,而不暴露给主机
expose: - "3000" - "8000"
network:分为两部分Top-level networks
key和Service-level networks
key。Service-level:Networks to join, referencing entries under the top-level networks
key.
By default Compose sets up a single network for your app. Each container for a service joins the default network and
is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.
在容器建立时会建立相应的网络,容器建立后加入相应的网络,即此网络下可访问到该容器。
Here’s an example Compose file defining two custom networks. The proxy
service is isolated from the db
service,
because they do not share a network in common - only app
can talk to both.
version: "3" services: proxy: build: ./proxy networks: - frontend app: build: ./app networks: - frontend - backend db: image: postgres networks: - backend networks: frontend: # Use a custom driver driver: custom-driver-1 backend: # Use a custom driver which takes special options driver: custom-driver-2 driver_opts: foo: "1" bar: "2"
参考:https://docs.docker.com/compose/networking/。
network_mode:设置网络模式
network_mode: "bridge" network_mode: "host" network_mode: "none" network_mode: "service:[service name]" network_mode: "container:[container name/id]"
ports:对外暴露的端口定义,和 expose 对应,使用host:container格式或者只指定容器端口,宿主机会随机映射端口。建议使用字符串格式,数字有时会解析错误。
ports: # 暴露端口信息 - "宿主机端口:容器暴露端口" - "8763:8763" - "8763:8763"
links:将指定容器链接到当前链接,能够设置别名,避免ip方式致使的容器重启动态改变的没法链接状况
links: # 指定服务名称:别名
- docker-compose-eureka-server:compose-eureka
volumes:卷挂载路径,挂载一个目录或一个已经存在的数据卷容器,能够直接使用host:container格式,或者host:container:ro,后者对于容器来讲,数据卷是只读的,可有效保护宿主机的文件系统。compose可使用相对路径。
volumes: // 只是指定一个路径,Docker 会自动在建立一个数据卷(这个路径是容器内部的)。 - /var/lib/mysql // 使用绝对路径挂载数据卷 - /opt/data:/var/lib/mysql // 以 Compose 配置文件为中心的相对路径做为数据卷挂载到容器。 - ./cache:/tmp/cache // 使用用户的相对路径(~/ 表示的目录是 /home/<用户目录>/ 或者 /root/)。 - ~/configs:/etc/configs/:ro // 已经存在的命名的数据卷。 - datavolume:/var/lib/mysql
You can mount a host path as part of a definition for a single service, and there is no need to define it in the top level volumes key.
单个容器使用不必定义顶层volume。
But, if you want to reuse a volume across multiple services, then define a named volume in the top-level volumes key.
多个服务要共用volume时须要定义顶层volumes。
Note: The top-level volumes key defines a named volume and references it from each service’s volumes list.
参考: