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

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

  • use the os module Hostname() function in golang, os.Hostname() returns the hostname, if valid, else return an err.
  • Find the Docker Id and name of a container using golang

Containers are created using the 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. The os package provides the 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 the Containers object using the client object client.ContainerList() method
  • containers contains all container objects.
  • 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)
 }
}