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 localhost into hosts based on network mode #11445

Merged
merged 1 commit into from
Sep 5, 2021
Merged
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
16 changes: 16 additions & 0 deletions libpod/container_internal_linux.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//go:build linux
// +build linux

package libpod
Expand Down Expand Up @@ -1942,9 +1943,24 @@ func (c *Container) generateHosts(path string) (string, error) {
}
hosts := string(orig)
hosts += c.getHosts()

hosts = c.appendLocalhost(hosts)

return c.writeStringToRundir("hosts", hosts)
}

// based on networking mode we may want to append the localhost
// if there isn't any record for it and also this shoud happen
// in slirp4netns and similar network modes.
func (c *Container) appendLocalhost(hosts string) string {
if !strings.Contains(hosts, "localhost") &&
!c.config.NetMode.IsHost() {
hosts += "127.0.0.1\tlocalhost\n::1\tlocalhost\n"
}

return hosts
}

// appendHosts appends a container's config and state pertaining to hosts to a container's
// local hosts file. netCtr is the container from which the netNS information is
// taken.
Expand Down
29 changes: 29 additions & 0 deletions libpod/container_internal_linux_test.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//go:build linux
// +build linux

package libpod
Expand All @@ -7,6 +8,7 @@ import (
"os"
"testing"

"github.com/containers/podman/v3/pkg/namespaces"
spec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/stretchr/testify/assert"
)
Expand Down Expand Up @@ -68,3 +70,30 @@ func TestGenerateUserGroupEntry(t *testing.T) {
}
assert.Equal(t, group, "567:x:567:567\n")
}

func TestAppendLocalhost(t *testing.T) {
{
c := Container{
config: &ContainerConfig{
ContainerNetworkConfig: ContainerNetworkConfig{
NetMode: namespaces.NetworkMode("slirp4netns"),
},
},
}

assert.Equal(t, "127.0.0.1\tlocalhost\n::1\tlocalhost\n", c.appendLocalhost(""))
assert.Equal(t, "127.0.0.1\tlocalhost", c.appendLocalhost("127.0.0.1\tlocalhost"))
}
{
c := Container{
config: &ContainerConfig{
ContainerNetworkConfig: ContainerNetworkConfig{
NetMode: namespaces.NetworkMode("host"),
},
},
}

assert.Equal(t, "", c.appendLocalhost(""))
assert.Equal(t, "127.0.0.1\tlocalhost", c.appendLocalhost("127.0.0.1\tlocalhost"))
}
}