Backgroud

  • docker-compose是为了方便启动多个容器
  • docker-compose1.xdocker compose2.x,2023年6月后,1.x不再更新

install

clean up workspace

  • 删除所有容器:docker container rm $(docker container ls -aq),强制删除docker container rm -f $(docker container ls -aq)
  • 删除所有镜像:docker image rm $(docker image ls -q)
  • -a列出所有容器,-q获取id

json vs yaml

  • json

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    {
    "name": "docker-compose tutorial",
    "price": 123,
    "is_good": true,
    "tags": ["software", "devops"],
    "author":{
    "first_name": "hello",
    "last_name": "world"
    }
    }
  • yaml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    ---
    name: docker-compose tutorial
    price: 123
    is_good: true
    tags:
    - software
    - devops
    author:
    first_name: hello
    last_name: world
  • json解析速度比yaml快(yaml所有都视为字符串,数字需要额外处理); json通常用于数据交换,yaml通常用于配置文件

compose file

  • docker-compose会默认启动文件名为docker-compose.yml的文件,docker compose会默认启动compose.yaml后者优先级较高
  • 使用docker-compose启动的服务,会创建一个默认网络用于服务通信,名字通常为启动路径名_default,即docker-compose.ymlhello文件夹下,则为hello_default
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
version: "3.8"

service:
web:
# 使用 docker-compose build 就会在指定路径下寻找 Dockerfile 文件,并构建镜像
# 也可以使用 docker-compose up --build 构建并启动服务
# --no-cache 不适用缓存,重新构建
build: ./frontend
# 端口映射 主机端口: 容器内地址
ports:
- 3000:3000
api:
build: ./backend
ports:
- 3001:3001
# 指定后端连接数据库地址,DB_URL 是视频演示的特定值,与程序相关
# 其中 mongodb:// 是固定写法
# db 为下面数据库服务名称
# databasename 为指定数据库名
enviroment:
- DB_URL: mongodb://db/databasename
db:
image: mongo:4.0-xenial
ports:
- 27017:27017
# 指定持久化卷映射
volumes:
- myvolunme:/data/db

# 声明卷,用于持久化
volumes:
myvolunme:

compose model

image-20231105175443185

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# 官网示例
services:
frontend:
image: example/webapp
ports:
- "443:8043"
networks:
- front-tier
- back-tier
configs:
- httpd-config
secrets:
- server-certificate

backend:
image: example/database
volumes:
- db-data:/etc/data
networks:
- back-tier

volumes:
db-data:
driver: flocker
driver_opts:
size: "10GiB"

configs:
httpd-config:
external: true

secrets:
server-certificate:
external: true

networks:
# The presence of these objects is sufficient to define them
front-tier: {}
back-tier: {}
  • 2 services, backed by Docker images: webapp and database
  • 1 secret (HTTPS certificate), injected into the frontend
  • 1 configuration (HTTP), injected into the frontend
  • 1 persistent volume, attached to the backend
  • 2 networks

参考