文章目录
浅言碎语
什么叫 Docker-Compose
- Docker-Compose 项目是 Docker 官方的开源项目,负责实现对 Docker 容器集群的快速编排
- Docker-Compose 将所管理的容器分为三层,分别是:
工程(project)服务(service)容器(container)
- Docker-Compose 运行目录下的所有文件(
Docker-Compose.yml,extends 文件或环境变量文件等)组成一个工程,若无特殊指定工程名即为当前目录名
- 一个工程当中可包含多个服务,每个服务中定义了容器运行的
镜像,参数,依赖 - 一个服务当中可包括多个容器实例
- 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 常用命令
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)
-p, --project-name NAME Specify an alternate project name (default: directory name)
--verbose Show more output
--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 (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 up
Usage: up [options] [--scale SERVICE=NUM...] [SERVICE...]
Options:
-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.
--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.
--abort-on-container-exit Stops all containers if any container was stopped.
Incompatible with -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)
--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.
Implies --abort-on-container-exit.
--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:
--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:
--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.
-v, --volumes Remove named volumes declared in the `volumes`
section of the Compose file and anonymous volumes
attached to containers.
--remove-orphans Remove containers for services not defined in the
Compose file
-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-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:
-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:
-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.
--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)
-l, --label KEY=VAL Add or override a label (can be used multiple times)
-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 [])
-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.
-T Disable pseudo-tty allocation. By default `docker-compose exec`
allocates a TTY.
--index=index index of the container if there are multiple
instances of a service [default: 1]
-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:
--protocol=proto tcp or udp [default: tcp]
--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 标准模板文件应该包含三大部分
versionservicesnetworks - 最关键的是
services 和 networks 两个部分
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' 不能申明 volumes、networks、构建参数version: '1' 默认每个容器都是 bridge 网络
- 只能通过容器内的 ip 访问
- 容器之间的服务发现需要用
link 模块
version:'2'
Compose 1.6.x 以上,Docker 1.10.0 以上的版本可以使用 version:'2'version: '2' 可以申明 volumes、networks、构建参数
version:'3'
Compose 1.10.x 以上,Docker 1.13.0 以上的版本可以使用 version:'3'- 为了在 Compose 和 Docker 引擎的swarm 模式之间交叉兼容 ,
version:'3' 删除了一些选项,增加了更多的选项
| 编写文件格式 | 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
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
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
- database:mysql
pid
pid: "host"
ports
ports:
- "8080"
- "80:8080"
volumes
services:
backend:
image: awesome/backend
volumes:
- type: volume
source: db-data
target: /data
volume:
nocopy: true
- type: bind
source: /var/run/postgres/postgres.sock
target: /var/run/postgres/postgres.sock
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: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 格式
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:
aliases:
- mysql
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:
cpus: '0.50'
memory: 50M
pids: 1
reservations:
cpus: '0.25'
memory: 20M
全剧终
- compose 可配置的选项是相当的多,尤其是
version: '3' - 甚至可以限制容器使用的磁盘io,配置 cpu cfs 配额等许多许多的功能,具体的,有兴趣的可以参考官方的文档
- 还是 Dockerfile 从入门到放弃 里面的那句总结 (留点头发)