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.
This tutorial explains how to get a container IP address in Golang.
os
module Hostname()
function in golang, os.Hostname()
returns the hostname, if valid, else return an err.Id
and name of a container using golangContainers 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.
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)
}
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.
Client
object using NewClientWithOpts(client.FromEnv)
or NewClient()
methodContainers
object using the client object client.ContainerList()
methodcontainers
contains all container objects.Iterate
each object using the range loopid
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)
}
}
🧮 Tags
Recent posts
Puppeteer Login Test example How to convert Double to Integer or Integer to double in Dart| Flutter By Example Best ways to fix 504 gateway time out in nodejs Applications Fix for Error No configuration provided for scss Multiple ways to List containers in a Docker with examplesRelated posts