From 7c83a5206fbe4d844e10a1a49be7a15054d9ef54 Mon Sep 17 00:00:00 2001 From: Chi-Sheng Liu Date: Wed, 14 Feb 2024 05:19:40 +0800 Subject: [PATCH] fix: Use ExtraHosts only for linux machines with native docker engine Signed-off-by: Chi-Sheng Liu --- pkg/docker/docker_util.go | 16 +++++++++++++++- pkg/docker/docker_util_test.go | 8 ++++---- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/pkg/docker/docker_util.go b/pkg/docker/docker_util.go index e9315cab..f15c2a8b 100644 --- a/pkg/docker/docker_util.go +++ b/pkg/docker/docker_util.go @@ -6,7 +6,9 @@ import ( "errors" "fmt" "io" + "io/fs" "os" + "runtime" "strings" "github.com/docker/docker/client" @@ -60,6 +62,18 @@ var ( ExtraHosts = []string{"host.docker.internal:host-gateway"} ) +// GetExtraHosts will return extra hosts for the container +func GetExtraHosts() []string { + // Linux machine with native docker engine does not have host.docker.internal and needs to add the hostname mapping manually. + if runtime.GOOS == "linux" { + // Here assume that if /var/run/docker.sock exists and is a socket file and is not symbolic link, then the docker engine is native + if fileInfo, err := os.Lstat("/var/run/docker.sock"); err == nil && fileInfo.Mode().Type() == fs.ModeSocket { + return ExtraHosts + } + } + return []string{} +} + // GetDockerClient will returns the docker client func GetDockerClient() (Docker, error) { if Client == nil { @@ -266,7 +280,7 @@ func StartContainer(ctx context.Context, cli Docker, volumes []mount.Mount, expo Mounts: volumes, PortBindings: portBindings, Privileged: true, - ExtraHosts: ExtraHosts, // add it because linux machine doesn't have this host name by default + ExtraHosts: GetExtraHosts(), }, nil, nil, name) diff --git a/pkg/docker/docker_util_test.go b/pkg/docker/docker_util_test.go index 0de840bb..48937c6c 100644 --- a/pkg/docker/docker_util_test.go +++ b/pkg/docker/docker_util_test.go @@ -196,7 +196,7 @@ func TestStartContainer(t *testing.T) { Mounts: Volumes, PortBindings: p2, Privileged: true, - ExtraHosts: ExtraHosts, + ExtraHosts: GetExtraHosts(), }, nil, nil, mock.Anything).Return(container.ContainerCreateCreatedBody{ ID: "Hello", }, nil) @@ -226,7 +226,7 @@ func TestStartContainer(t *testing.T) { Mounts: Volumes, PortBindings: p2, Privileged: true, - ExtraHosts: ExtraHosts, + ExtraHosts: GetExtraHosts(), }, nil, nil, mock.Anything).Return(container.ContainerCreateCreatedBody{ ID: "Hello", }, nil) @@ -253,7 +253,7 @@ func TestStartContainer(t *testing.T) { Mounts: Volumes, PortBindings: p2, Privileged: true, - ExtraHosts: ExtraHosts, + ExtraHosts: GetExtraHosts(), }, nil, nil, mock.Anything).Return(container.ContainerCreateCreatedBody{ ID: "", }, fmt.Errorf("error")) @@ -279,7 +279,7 @@ func TestStartContainer(t *testing.T) { Mounts: Volumes, PortBindings: p2, Privileged: true, - ExtraHosts: ExtraHosts, + ExtraHosts: GetExtraHosts(), }, nil, nil, mock.Anything).Return(container.ContainerCreateCreatedBody{ ID: "Hello", }, nil)