构建依赖镜像

要求: Docker Compose 2.22.0 及更高版本

为了减少推送/拉取时间和镜像大小,Compose 应用程序的常见做法是让服务尽可能共享基础层。通常,您会为所有服务选择相同的操作系统基础镜像。但是,当您的镜像共享相同的系统软件包时,您还可以通过共享镜像层进一步优化。需要解决的挑战是避免在所有服务中重复完全相同的 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    

Bake 也可以通过编辑您的 `$HOME/.docker/config.json` 配置文件来选择作为默认构建器。

{
  ...
  "plugins": {
    "compose": {
      "build": "bake"
    }
  }
  ...
}

其他资源

© . This site is unofficial and not affiliated with Kubernetes or Docker Inc.