官方文档
Compose file version 3 reference | Docker Documentation
模板文件(docker-compose.yaml)
我们常用的 docker-compose.yaml 模板(直接复制):
version: '3'
services:
backend:
# 镜像配置
image: <image address>
# 容器配置
container_name: <container name>
# 网络配置
hostname: <hostname>
network_mode: host
ports:
- "<host port>:<container port>"
# 服务管理配置
restart: always
# 运行命令、及其环境信息
volumes:
- /etc/localtime:/etc/localtime
environment:
- <key>=<value>
# 覆盖 ENTRYPOINT 参数
entrypoint: /bin/entrypoint
command: ["ls", "-l"]
运行命令
docker-compose, run a script after container has started? – Stack Overflow
运行多行命令(多行脚本):
version: '3'
services:
backend:
...
entrypoint:
- sh
- -c
command:
- |
while true
do
// do some stuff
done
环境变量(Environment)
Environment variables in Compose | Docker Documentation
docker-compose invalid type, it should be a string – DevOps Stack Exchange
供 Container 使用的环境变量
这里的“环境变量”是指“在运行时传递到容器中的环境变量”,等价于 docker run –env 命令。
使用如下形式定义环境变量(注意 environment 为数组):
version: '3'
services:
api:
image: 'node:6-alpine'
env_file:
- ./Docker/api/api.env
environment:
- NODE_ENV=production
供 YAML 使用的环境变量
Environment variables in Compose | Docker Documentation
通过定义 .env 文件(或通过 docker-compose –env-file /path/to/envfile 参数),来指定环境变量文件的路径。
然后,我们便能够在 docker-compose.yaml 中使用这些环境变量:
version: '3'
services:
web:
image: "webapp:${TAG}"
注意事项:
1)引号问题:在 .env 中定义的环境变量,其 <VALUE> 不要使用引号(除非需要)。引号会被视为 <VALUE> 的成分;
资源限制(Resource Limits)
How to specify Memory & CPU limit in docker compose version 3 – Stack Overflow
version: "3.6"
services:
example-container:
deploy:
# 资源限制
resources:
limits:
cpus: '0.50'
memory: 500M
针对 Compose file reference Version 3 配置,需要使用 –compatibility 选项启动服务:
docker-compose --compatibility up -d
日志轮转(Logging)
version: "3.6"
services:
example-container:
# 日志处理
logging:
driver: "json-file"
options:
max-size: "500M"
max-file: "3"
存储数据(Volume)
version: "3.9"
services:
web:
image: nginx:alpine
volumes:
- type: volume
source: data-web
target: /data
volume:
nocopy: true
- type: bind
source: ./static
target: /opt/app/static
- type: volume
source: nfs-storage-foo
target: /srv/nfs
volume:
nocopy: true
db:
image: postgres:latest
volumes:
- "/var/run/postgres/postgres.sock:/var/run/postgres/postgres.sock"
- "data-db:/var/lib/postgresql/data"
volumes:
data-web:
data-db:
nfs-storage-foo:
driver_opts:
type: "nfs"
o: "addr=10.40.0.199,nolock,soft,rw"
device: ":/docker/example"
常用工具
将 docker run 转化为 Docker Compose 文件:
1)https://github.com/magicmark/composerize
2)Composerize
转义字符
美元符号
escaping – How can I escape a $ dollar sign in a docker compose file? – Stack Overflow
在 docker-compose.yaml 中,通过 $$ 来表示 $ 符号,以防止被解析为变量;
参考文献
Option network_mode: host in docker compose file not working as expected – Open Source Projects / Compose – Docker Forums
Compose file version 3 reference | Docker Documentation
Convox Docs