Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add nerdctl build --add-host option support #3786

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions cmd/nerdctl/builder/builder_build.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ If Dockerfile is not present and -f is not specified, it will look for Container
SilenceErrors: true,
}
helpers.AddStringFlag(buildCommand, "buildkit-host", nil, "", "BUILDKIT_HOST", "BuildKit address")
buildCommand.Flags().StringArray("add-host", nil, "Add a custom host-to-IP mapping (format: \"host:ip\")")
buildCommand.Flags().StringArrayP("tag", "t", nil, "Name and optionally a tag in the 'name:tag' format")
buildCommand.Flags().StringP("file", "f", "", "Name of the Dockerfile")
buildCommand.Flags().String("target", "", "Set the target build stage to build")
Expand Down Expand Up @@ -92,6 +93,10 @@ func processBuildCommandFlag(cmd *cobra.Command, args []string) (types.BuilderBu
if err != nil {
return types.BuilderBuildOptions{}, err
}
extraHosts, err := cmd.Flags().GetStringArray("add-host")
if err != nil {
return types.BuilderBuildOptions{}, err
}
platform, err := cmd.Flags().GetStringSlice("platform")
if err != nil {
return types.BuilderBuildOptions{}, err
Expand Down Expand Up @@ -232,6 +237,7 @@ func processBuildCommandFlag(cmd *cobra.Command, args []string) (types.BuilderBu
Stdin: cmd.InOrStdin(),
NetworkMode: network,
ExtendedBuildContext: extendedBuildCtx,
ExtraHosts: extraHosts,
}, nil
}

Expand Down
29 changes: 29 additions & 0 deletions cmd/nerdctl/builder/builder_build_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -957,3 +957,32 @@ func TestBuildAttestation(t *testing.T) {

testCase.Run(t)
}

func TestBuildAddHost(t *testing.T) {
nerdtest.Setup()

testCase := &test.Case{
Require: test.Require(
nerdtest.Build,
),
Cleanup: func(data test.Data, helpers test.Helpers) {
helpers.Anyhow("rmi", "-f", data.Identifier())
},
Setup: func(data test.Data, helpers test.Helpers) {
dockerfile := fmt.Sprintf(`FROM %s
RUN ping -c 5 alpha
RUN ping -c 5 beta
`, testutil.CommonImage)
buildCtx := data.TempDir()
err := os.WriteFile(filepath.Join(buildCtx, "Dockerfile"), []byte(dockerfile), 0o600)
assert.NilError(helpers.T(), err)
data.Set("buildCtx", buildCtx)
},
Command: func(data test.Data, helpers test.Helpers) test.TestableCommand {
return helpers.Command("build", data.Get("buildCtx"), "-t", data.Identifier(), "--add-host", "alpha:127.0.0.1", "--add-host", "beta:127.0.0.1")
},
Expected: test.Expects(0, nil, nil),
}

testCase.Run(t)
}
3 changes: 2 additions & 1 deletion docs/command-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -714,8 +714,9 @@ Flags:
- :whale: `--label`: Set metadata for an image
- :whale: `--network=(default|host|none)`: Set the networking mode for the RUN instructions during build.(compatible with `buildctl build`)
- :whale: `--build-context`: Set additional contexts for build (e.g. dir2=/path/to/dir2, myorg/myapp=docker-image://path/to/myorg/myapp)
- :whale: `--add-host`: Add a custom host-to-IP mapping (format: `host:ip`)

Unimplemented `docker build` flags: `--add-host`, `--squash`
Unimplemented `docker build` flags: `--squash`

### :whale: nerdctl commit

Expand Down
2 changes: 2 additions & 0 deletions pkg/api/types/builder_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ type BuilderBuildOptions struct {
NetworkMode string
// Pull determines if we should try to pull latest image from remote. Default is buildkit's default.
Pull *bool
// ExtraHosts is a set of custom host-to-IP mappings.
ExtraHosts []string
}

// BuilderPruneOptions specifies options for `nerdctl builder prune`.
Expand Down
23 changes: 23 additions & 0 deletions pkg/cmd/builder/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,14 @@ func generateBuildctlArgs(ctx context.Context, client *containerd.Client, option
}
}

if len(options.ExtraHosts) > 0 {
hosts, err := parseExtraHosts(options.ExtraHosts)
if err != nil {
return "", nil, false, "", nil, nil, err
}
buildctlArgs = append(buildctlArgs, "--opt=add-hosts="+strings.Join(hosts, ","))
}

return buildctlBinary, buildctlArgs, needsLoading, metaFile, tags, cleanup, nil
}

Expand Down Expand Up @@ -605,3 +613,18 @@ func readOCIIndexFromPath(path string) (*ocispec.Index, error) {
}
return ociIndex, nil
}

func parseExtraHosts(extraHosts []string) ([]string, error) {
hosts := make([]string, 0, len(extraHosts))
for _, hostIPMapping := range extraHosts {
host, ip, ok := strings.Cut(hostIPMapping, ":")
if !ok {
host, ip, ok = strings.Cut(hostIPMapping, "=")
}
if !ok || host == "" || ip == "" {
return nil, fmt.Errorf("invalid host %s", hostIPMapping)
}
hosts = append(hosts, host+"="+ip)
}
return hosts, nil
}