How to get Docker Container in Golang | Container ID and IP Address

This tutorial explains guidance on getting a container’s IP address in Golang.

  • Utilize the os module’s Hostname() function in Golang. os.Hostname() returns the hostname if valid; otherwise, it returns an error.
  • Identify the Docker ID and name of a container using Golang.

Containers are generated through the Docker tool, and typically, Docker commands are used to retrieve container details. However, there are scenarios where it becomes necessary to write Golang code for accessing container details.

Golang Get Container IP Address example

Inside a container, write a Golang program. The os package offers the Hostname() method, which returns a string and an error.

func Hostname() (name string, err error)

the string contains the hostname of a container for successful execution. else, it returns an error.

package main

import (
 "os"
)

func main() {
 containerHostname, err := os.Hostname()
 println(containerHostname)
 println(err)

}

Golang Get Container ID and Image details

With the Docker command using the ps option, it lists container details.

Docker provides a client API for golang🔗.

To retrieve container metadata details, follow the steps below:

  • Create a Client object using either NewClientWithOpts(client.FromEnv) or NewClient() method
  • Obtain the Containers object using the client’s ContainerList() method.
  • The container object contains all container objects.
  • Iterate through each object using a range loop.
  • Print the container ID and image. Here is an example in Golang to retrieve the container ID and image.
package main

import (
 "context"
 "fmt"

 "github.com/docker/docker/api/types"
 "github.com/docker/docker/client"
)

func main() {
 client, err := client.NewClientWithOpts(client.FromEnv)
 if err != nil {
  panic(err)
 }

 containers, err := client.ContainerList(context.Background(), types.ContainerListOptions{})
 if err != nil {
  panic(err)
 }

 for _, container := range containers {
  fmt.Printf("%s %s", container.ID[:10], container.Image)
 }
}

Conclusion

In this tutorial, you have learned how to get the container ID and image details of a container in Golang.