Docker Compose 是一个定义和运行多容器应用程序的工具。它是开启流线型高效开发和部署体验的关键。
Compose 简化了对整个应用程序堆栈的控制,使得在一个易于理解的 YAML 配置文件中轻松管理服务、网络和卷。然后,使用一个命令,从配置文件创建并启动所有服务。
安装
仓库安装
sudo apt-get update |
手动安装
DOCKER_CONFIG=${DOCKER_CONFIG:-$HOME/.docker} |
卸载
docker info --format '{{range .ClientInfo.Plugins}}{{if eq .Name "compose"}}{{.Path}}{{end}}{{end}}' |
示例
- app.py
import time |
- reuqirements.txt
flask |
- Dockerfile
# syntax=docker/dockerfile:1 |
- compose.yml
services: |
- 启动
docker compose up --watch |
- 验证
docker compose watch |
- 拆分 yaml 文件
infra.yaml
services: |
compose.yaml
include: |
指定工程名
在撰写中,默认项目名称派生自项目目录的基本名称。但是,您可以使用-p参数灵活地设置自定义项目名称。
环境变量
使用环境变量将配置信息传递给容器运行时。
环境变量是包含数据的键值对,这些数据可以被运行在 Docker 容器内的进程使用。它们通常用于配置应用程序设置和其他可能在不同环境(如开发、测试和生产)之间变化的参数。
.env文件
- .env
TAG=v1.5 |
- compose.yml
services: |
- 测试
docker compose config |
- yaml 配置
env_file: |
environment 属性(推荐)
web: |
--env-file参数
docker compose --env-file ./config/.env.dev up |
-e参数
docker compose run -e DEBUG=1 web python console.py |
优先级
- Set using docker compose run -e in the CLI
Substituted from your shell - Set using just the environment attribute in the Compose file
- Use of the –env-file argument in the CLI
Use of the env_file attribute in the Compose file - Set using an .env file placed at base of your project directory
- Set in a container image in the ENV directive. Having any ARG or ENV setting in a Dockerfile evaluates only if there is no Docker Compose entry for environment, env_file or run –env.
使用
profiles
profiles 通过有选择地启动服务,帮助您调整 Compose 应用程序模型,以适应各种用途和环境。这是通过将每个服务分配给零个或多个 profiles 来实现的。如果未分配,则始终启动该服务;如果分配,则仅在 profiles 激活时启动该服务。
示例
在这里,服务前端和 phpmyadmin 分别分配给 profiles 前端和调试,因此只有在各自的 profiles 启用时才会启动。
services: |
开启 profile
docker compose --profile debug up |
隐式开启
services: |
Only start backend and db |
但请记住,docker compose 只会自动启动命令行上服务的 profiles,而不会启动任何依赖项的 profiles。
watch
使用 watch 可以在编辑和保存代码时自动更新和预览正在运行的 Compose 服务。
常用:Sync、Rebuild、Sync + Restart
services: |
docker compose up --watch |
secret
secret 是任何不应该通过网络传输或未加密存储在 Dockerfile 或应用程序源代码中的数据,例如密码、证书或 API 密钥。
services: |
控制启动顺序
depends_on
网络
默认情况下,Compose 为应用程序设置了一个单独的网络。服务的每个容器都加入默认网络,并且该网络上的其他容器都可以访问,并且可以通过服务的名称发现。
LinkContainers
链接允许您定义额外的别名,通过这些别名,一个服务可以从另一个服务访问。它们不是启用服务通信所必需的。默认情况下,任何服务都可以以该服务的名称访问任何其他服务。在下面的示例中,可以通过 web 以主机名 db 和 database 访问 db
services: |
自定义网络
services: |
配置默认网络
services: |
使用已存在网络
services: |
语法
# 指定compose file版本 会在版本弃用是发送警告 |
参考文档
Docker Compose
compose-file reference
- 本文作者: Tiny Beer
- 本文链接: https://tinybeer.github.io/2024/06/13/docker-compose/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!
