Home Explore Blog CI



docker

1st chunk of `content/manuals/build/bake/inheritance.md`
5054237e7d08742507c817922ff248bf23fd0048e7b2969a000000010000095b
---
title: Inheritance in Bake
linkTitle: Inheritance
weight: 30
description: Learn how to inherit attributes from other targets in Bake
keywords: buildx, buildkit, bake, inheritance, targets, attributes
---

Targets can inherit attributes from other targets, using the `inherits`
attribute. For example, imagine that you have a target that builds a Docker
image for a development environment:

```hcl {title=docker-bake.hcl}
target "app-dev" {
  args = {
    GO_VERSION = "{{% param example_go_version %}}"
  }
  tags = ["docker.io/username/myapp:dev"]
  labels = {
    "org.opencontainers.image.source" = "https://github.com/username/myapp"
    "org.opencontainers.image.author" = "moby.whale@example.com"
  }
}
```

You can create a new target that uses the same build configuration, but with
slightly different attributes for a production build. In this example, the
`app-release` target inherits the `app-dev` target, but overrides the `tags`
attribute and adds a new `platforms` attribute:

```hcl {title=docker-bake.hcl}
target "app-release" {
  inherits = ["app-dev"]
  tags = ["docker.io/username/myapp:latest"]
  platforms = ["linux/amd64", "linux/arm64"]
}
```

## Common reusable targets

One common inheritance pattern is to define a common target that contains
shared attributes for all or many of the build targets in the project. For
example, the following `_common` target defines a common set of build
arguments:

```hcl {title=docker-bake.hcl}
target "_common" {
  args = {
    GO_VERSION = "{{% param example_go_version %}}"
    BUILDKIT_CONTEXT_KEEP_GIT_DIR = 1
  }
}
```

You can then inherit the `_common` target in other targets to apply the shared
attributes:

```hcl {title=docker-bake.hcl}
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"]
}
```

## Overriding inherited attributes

When a target inherits another target, it can override any of the inherited
attributes. For example, the following target overrides the `args` attribute
from the inherited target:

Title: Inheritance in Bake
Summary
Bake allows targets to inherit attributes from other targets using the `inherits` attribute. This allows for creating common, reusable targets with shared attributes and overriding specific attributes for different build configurations. Inheritance simplifies the build configuration by promoting code reuse and reducing redundancy.