diff --git a/daemon/container_operations.go b/daemon/container_operations.go index dd6703fb1b..1704a0ecb8 100644 --- a/daemon/container_operations.go +++ b/daemon/container_operations.go @@ -674,6 +674,18 @@ func (daemon *Daemon) updateNetworkConfig(container *container.Container, n libn if addShortID { endpointConfig.Aliases = append(endpointConfig.Aliases, shortID) } + if container.Name != container.Config.Hostname { + addHostname := true + for _, alias := range endpointConfig.Aliases { + if alias == container.Config.Hostname { + addHostname = false + break + } + } + if addHostname { + endpointConfig.Aliases = append(endpointConfig.Aliases, container.Config.Hostname) + } + } } if err := validateNetworkingConfig(n, endpointConfig); err != nil { diff --git a/integration/container/run_linux_test.go b/integration/container/run_linux_test.go index ec088ecad7..e2c1c524a4 100644 --- a/integration/container/run_linux_test.go +++ b/integration/container/run_linux_test.go @@ -10,6 +10,7 @@ import ( containertypes "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/versions" "github.com/docker/docker/integration/internal/container" + net "github.com/docker/docker/integration/internal/network" "gotest.tools/assert" is "gotest.tools/assert/cmp" "gotest.tools/poll" @@ -93,3 +94,37 @@ func TestNISDomainname(t *testing.T) { assert.Equal(t, 0, res.ExitCode) assert.Check(t, is.Equal(domainname, strings.TrimSpace(res.Stdout()))) } + +func TestHostnameDnsResolution(t *testing.T) { + skip.If(t, testEnv.DaemonInfo.OSType != "linux") + + defer setupTest(t)() + client := testEnv.APIClient() + ctx := context.Background() + + const ( + hostname = "foobar" + ) + + // using user defined network as we want to use internal DNS + netName := "foobar-net" + net.CreateNoError(t, context.Background(), client, netName, net.WithDriver("bridge")) + + cID := container.Run(t, ctx, client, func(c *container.TestContainerConfig) { + c.Config.Hostname = hostname + c.HostConfig.NetworkMode = containertypes.NetworkMode(netName) + }) + + poll.WaitOn(t, container.IsInState(ctx, client, cID, "running"), poll.WithDelay(100*time.Millisecond)) + + inspect, err := client.ContainerInspect(ctx, cID) + assert.NilError(t, err) + assert.Check(t, is.Equal(hostname, inspect.Config.Hostname)) + + // Clear hosts file so ping will use DNS for hostname resolution + res, err := container.Exec(ctx, client, cID, + []string{"sh", "-c", "echo 127.0.0.1 localhost | tee /etc/hosts && ping -c 1 foobar"}) + assert.NilError(t, err) + assert.Check(t, is.Equal("", res.Stderr())) + assert.Equal(t, 0, res.ExitCode) +}