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"]
}
当从多个目标继承属性并且存在冲突时,`inherits`列表中最后出现的目标优先。前面的示例在`_common`目标中定义了`BUILDKIT_CONTEXT_KEEP_GIT_DIR`,并在`app-dev`目标中将其覆盖。
`app-release`目标同时继承`app-dev`目标和`_common`目标。`BUILDKIT_CONTEXT_KEEP_GIT_DIR`参数在`app-dev`目标中设置为0,在`_common`目标中设置为1。`app-release`目标中的`BUILDKIT_CONTEXT_KEEP_GIT_DIR`参数设置为1,而不是0,因为`_common`目标在`inherits`列表中最后出现。
重用目标中的单个属性
如果您只想从目标继承单个属性,则可以使用点表示法引用另一个目标中的属性。例如,在下面的Bake文件中,`bar`目标重用了`foo`目标的`tags`属性
target "foo" {
dockerfile = "foo.Dockerfile"
tags = ["myapp:latest"]
}
target "bar" {
dockerfile = "bar.Dockerfile"
tags = target.foo.tags
}