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
}