{

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


Golang example Getting IP address of a container

This tutorial explains how to get a container IP address in Golang.

Containers are created using Docker tool. We can operate with docker commands to get contain container details. Sometimes, We need to write a golang code to access container details

Golang Get Container IP Address example

Inside a container, Write a golang program os package provides Hostname() method that returns a string and error.

func Hostname() (name string, err error)

the string contains the hostname of a container

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 out container details.

Docker provides a client API for golang.

To get container metadata details, Follow the below steps

  • Create a Client object using NewClientWithOpts(client.FromEnv) or NewClient() method
  • get Containers object using client object client.ContainerList() method
  • containers contains all container object.
  • Iterate each object using the range loop
  • Print the container id and image.

Here is an example of Golang to get 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)
 }
}
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.