Bake中的继承
目标可以使用inherits
属性从其他目标继承属性。例如,假设你有一个为目标构建开发环境的 Docker 镜像的目标:
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-release 目标继承了 app-dev 目标,但覆盖了 tags 属性并添加了一个新的 platforms 属性:
target "app-release" {
inherits = ["app-dev"]
tags = ["docker.io/username/myapp:latest"]
platforms = ["linux/amd64", "linux/arm64"]
}常用可重用目标
一种常见的继承模式是定义一个包含项目中所有或大多数构建目标的共享属性的通用目标。例如,以下 _common 目标定义了一组通用的构建参数:
target "_common" {
args = {
GO_VERSION = "1.23"
BUILDKIT_CONTEXT_KEEP_GIT_DIR = 1
}
}然后,您可以在其他目标中继承_common目标以应用共享属性:
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"]
}在 app-release 中的 GO_VERSION 参数被设置为 1.17,覆盖了来自 app-dev 目标的 GO_VERSION 参数。
有关覆盖属性的更多信息,请参阅 覆盖配置 页面。
从多个目标继承
inherits 属性是一个列表,这意味着您可以重用来自多个其他目标的属性。在以下示例中,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"]
}当从多个目标继承属性且存在冲突时,继承列表中最后出现的目标优先。上一个示例在 _common 目标中定义了 BUILDKIT_CONTEXT_KEEP_GIT_DIR,并在 app-dev 目标中覆盖了它。
目标 app-release 继承了 app-dev 目标和 _common 目标。
参数 BUILDKIT_CONTEXT_KEEP_GIT_DIR 在 app-dev 目标中设置为 0,
在 _common 目标中设置为 1。由于继承列表中 _common 目标最后出现,
app-release 目标中的 BUILDKIT_CONTEXT_KEEP_GIT_DIR 参数被设置为 1,而不是 0。
从目标中重用单个属性
如果你只想从目标继承一个属性,可以使用点表示法引用另一个目标的属性。例如,在以下 Bake 文件中,bar 目标重用了 foo 目标中的 tags 属性:
target "foo" {
dockerfile = "foo.Dockerfile"
tags = ["myapp:latest"]
}
target "bar" {
dockerfile = "bar.Dockerfile"
tags = target.foo.tags
}