Bake 中的继承
目标可以使用inherits属性。例如,假设您有一个构建 Docker 的目标
image 的 API API
target "app-dev" {
args = {
GO_VERSION = "1.23"
}
tags = ["docker.io/username/myapp:dev"]
labels = {
"org.opencontainers.image.source" = "https://github.com/username/myapp"
"org.opencontainers.image.author" = "moby.whale@example.com"
}
}您可以创建使用相同的构建配置的新目标,但使用
生产版本的属性略有不同。在此示例中,app-releasetarget 继承了app-devtarget,但会覆盖tags属性并添加新的platforms属性:
target "app-release" {
inherits = ["app-dev"]
tags = ["docker.io/username/myapp:latest"]
platforms = ["linux/amd64", "linux/arm64"]
}常见的可重用目标
一种常见的继承模式是定义一个通用目标,其中包含
项目中所有或多个构建目标的 shared 属性。为
example,则以下_commontarget 定义一组通用的 build
参数:
target "_common" {
args = {
GO_VERSION = "1.23"
BUILDKIT_CONTEXT_KEEP_GIT_DIR = 1
}
}然后,您可以继承_commontarget 应用于其他目标以应用共享的
属性:
target "lint" {
inherits = ["_common"]
dockerfile = "./dockerfiles/lint.Dockerfile"
output = ["type=cacheonly"]
}
target "docs" {
inherits = ["_common"]
dockerfile = "./dockerfiles/docs.Dockerfile"
output = ["./docs/reference"]
}
target "test" {
inherits = ["_common"]
target = "test-output"
output = ["./test"]
}
target "binaries" {
inherits = ["_common"]
target = "binaries"
output = ["./build"]
platforms = ["local"]
}覆盖继承的属性
当一个目标继承另一个目标时,它可以覆盖任何继承的
属性。例如,以下目标会覆盖args属性
从继承的目标:
target "app-dev" {
inherits = ["_common"]
args = {
GO_VERSION = "1.17"
}
tags = ["docker.io/username/myapp:dev"]
}这GO_VERSIONargument 在app-release设置为1.17,覆盖GO_VERSION参数app-dev目标。
有关覆盖属性的更多信息,请参阅覆盖 配置页面。
从多个目标继承
这inheritsattribute 是一个列表,这意味着你可以重用
多个其他目标。在以下示例中,app-release 目标重用
属性app-dev和_common目标。
target "_common" {
args = {
GO_VERSION = "1.23"
BUILDKIT_CONTEXT_KEEP_GIT_DIR = 1
}
}
target "app-dev" {
inherits = ["_common"]
args = {
BUILDKIT_CONTEXT_KEEP_GIT_DIR = 0
}
tags = ["docker.io/username/myapp:dev"]
labels = {
"org.opencontainers.image.source" = "https://github.com/username/myapp"
"org.opencontainers.image.author" = "moby.whale@example.com"
}
}
target "app-release" {
inherits = ["app-dev", "_common"]
tags = ["docker.io/username/myapp:latest"]
platforms = ["linux/amd64", "linux/arm64"]
}当从多个目标继承属性时,如果存在冲突,
在 inherits (继承) 列表中最后显示的目标优先。上一个
example 定义BUILDKIT_CONTEXT_KEEP_GIT_DIR在_commontarget 和
在app-dev目标。
这app-releaseTarget 会同时继承app-devtarget 和_common目标。
这BUILDKIT_CONTEXT_KEEP_GIT_DIR参数设置为 0app-dev目标
和 1 在_common目标。这BUILDKIT_CONTEXT_KEEP_GIT_DIRargument 在
这app-releasetarget 设置为 1,而不是 0,因为_common目标出现
inherits 列表中的 last 中。
重用目标中的单个属性
如果您只想从 target 继承单个属性,则可以引用
使用点表示法的另一个目标的属性。例如,在
在 Bake 文件后面,barTarget 重用tags属性foo目标:
target "foo" {
dockerfile = "foo.Dockerfile"
tags = ["myapp:latest"]
}
target "bar" {
dockerfile = "bar.Dockerfile"
tags = target.foo.tags
}