diff --git a/container.go b/container.go index f17ec683e9..c7a5855b74 100644 --- a/container.go +++ b/container.go @@ -2,9 +2,10 @@ package testcontainers import ( "context" - "github.com/docker/docker/api/types/container" "io" + "github.com/docker/docker/api/types/container" + "github.com/docker/docker/pkg/archive" "github.com/docker/go-connections/nat" "github.com/pkg/errors" @@ -45,6 +46,7 @@ type Container interface { Networks(context.Context) ([]string, error) // get container networks NetworkAliases(context.Context) (map[string][]string, error) // get container network aliases for a network Exec(ctx context.Context, cmd []string) (int, error) + ContainerIP(context.Context) (string, error) // get container ip } // ImageBuildInfo defines what is needed to build an image diff --git a/docker.go b/docker.go index 2b21924d63..7938c87761 100644 --- a/docker.go +++ b/docker.go @@ -243,6 +243,16 @@ func (c *DockerContainer) Networks(ctx context.Context) ([]string, error) { return n, nil } +// ContainerIP gets the IP address of the primary network within the container. +func (c *DockerContainer) ContainerIP(ctx context.Context) (string, error) { + inspect, err := c.inspectContainer(ctx) + if err != nil { + return "", err + } + + return inspect.NetworkSettings.IPAddress, nil +} + // NetworkAliases gets the aliases of the container for the networks it is attached to. func (c *DockerContainer) NetworkAliases(ctx context.Context) (map[string][]string, error) { inspect, err := c.inspectContainer(ctx) diff --git a/docker_test.go b/docker_test.go index afdde1eeb5..865456fb9c 100644 --- a/docker_test.go +++ b/docker_test.go @@ -546,6 +546,13 @@ func TestContainerCreation(t *testing.T) { if resp.StatusCode != http.StatusOK { t.Errorf("Expected status code %d. Got %d.", http.StatusOK, resp.StatusCode) } + networkIP, err := nginxC.ContainerIP(ctx) + if err != nil { + t.Fatal(err) + } + if len(networkIP) == 0 { + t.Errorf("Expected an IP address, got %v", networkIP) + } networkAliases, err := nginxC.NetworkAliases(ctx) if err != nil { t.Fatal(err)