构建依赖镜像
为了减少推送/拉取时间和镜像大小,Compose 应用程序的一个常见做法是让服务尽可能共享基础层。通常会为所有服务选择相同的操作系统基础镜像。但当你的镜像共享相同的系统包时,你还可以进一步共享镜像层。此时需要解决的挑战是避免在所有服务的 Dockerfile 中重复完全相同的 Dockerfile 指令。
为了说明,本页假设你希望所有服务都使用 alpine
基础镜像构建并安装系统包 openssl
。
多阶段 Dockerfile
推荐的方法是将共享声明分组到一个 Dockerfile 中,并使用多阶段功能,以便服务镜像可以从此共享声明构建。
Dockerfile
FROM alpine as base
RUN /bin/sh -c apk add --update --no-cache openssl
FROM base as service_a
# build service a
...
FROM base as service_b
# build service b
...
Compose 文件
services:
a:
build:
target: service_a
b:
build:
target: service_b
将另一个服务的镜像用作基础镜像
一个流行的模式是将一个服务的镜像作为基础镜像在另一个服务中使用。由于 Compose 不解析 Dockerfile,它无法自动检测服务之间的这种依赖关系,从而无法正确地排序构建执行。
a.Dockerfile
FROM alpine
RUN /bin/sh -c apk add --update --no-cache openssl
b.Dockerfile
FROM service_a
# build service b
Compose 文件
services:
a:
image: service_a
build:
dockerfile: a.Dockerfile
b:
image: service_b
build:
dockerfile: b.Dockerfile
传统的 Docker Compose v1 用于按顺序构建镜像,这使得此模式可以开箱即用。Compose v2 使用 BuildKit 来优化构建并并行构建镜像,因此需要明确声明依赖关系。
推荐的方法是将依赖的基础镜像声明为额外的构建上下文
Compose 文件
services:
a:
image: service_a
build:
dockerfile: a.Dockerfile
b:
image: service_b
build:
dockerfile: b.Dockerfile
additional_contexts:
# `FROM service_a` will be resolved as a dependency on service "a" which has to be built first
service_a: "service:a"
使用 additional_contexts
属性,你可以引用由另一个服务构建的镜像,而无需显式命名它
b.Dockerfile
FROM base_image
# `base_image` doesn't resolve to an actual image. This is used to point to a named additional context
# build service b
Compose 文件
services:
a:
build:
dockerfile: a.Dockerfile
# built image will be tagged <project_name>_a
b:
build:
dockerfile: b.Dockerfile
additional_contexts:
# `FROM base_image` will be resolved as a dependency on service "a" which has to be built first
base_image: "service:a"
使用 Bake 构建
使用 Bake 可以让你传递所有服务的完整构建定义,并以最有效的方式协调构建执行。
要启用此功能,请在你的环境中设置 COMPOSE_BAKE=true
环境变量来运行 Compose。
$ COMPOSE_BAKE=true docker compose build
[+] Building 0.0s (0/1)
=> [internal] load local bake definitions 0.0s
...
[+] Building 2/2 manifest list sha256:4bd2e88a262a02ddef525c381a5bdb08c83 0.0s
✔ service_b Built 0.7s
✔ service_a Built
你还可以通过编辑 $HOME/.docker/config.json
配置文件将 Bake 选择为默认的 builder
{
...
"plugins": {
"compose": {
"build": "bake"
}
}
...
}