containerip.go 830 B

123456789101112131415161718192021222324252627282930313233
  1. package internal
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/docker/docker/client"
  6. )
  7. // GetContainerIPAddress returns the first non-empty IP address of the container with the given name.
  8. // It returns the IP address as a string or an error.
  9. func GetContainerIPAddress(containerName string) (string, error) {
  10. ctx := context.Background()
  11. cli, err := client.NewClientWithOpts(client.FromEnv)
  12. if err != nil {
  13. return "", err
  14. }
  15. // Get container details
  16. containerJSON, err := cli.ContainerInspect(ctx, containerName)
  17. if err != nil {
  18. return "", err
  19. }
  20. // Loop through all networks and return the first IP address found
  21. for _, net := range containerJSON.NetworkSettings.Networks {
  22. if net.IPAddress != "" {
  23. return net.IPAddress, nil
  24. }
  25. }
  26. return "", fmt.Errorf("no IP address found for container %q", containerName)
  27. }