Skip to content

Commit

Permalink
Merge pull request #179 from testcontainers/feature/containerIP
Browse files Browse the repository at this point in the history
Added ContainerIP to retrieve ip of container from primary network
  • Loading branch information
gianarb authored Apr 14, 2020
2 parents 06b85eb + d0e9b43 commit 042661a
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
4 changes: 3 additions & 1 deletion container.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
7 changes: 7 additions & 0 deletions docker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 042661a

Please sign in to comment.