We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Here's another small sample program which shows how you can access the Docker CLI from within a Go program using the Docker API.
Today, we are going to learn how to list all images which are downloaded on our system.
We first start with creating an empty project:
$ mkdir list-docker-containers
$ cd list-docker-containers
$ go mod init github.com/pieterclaerhout/go-example/go-list-docker-images
In there, we create a main.go
file containing:
package main
import (
"context"
"strings"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/pieterclaerhout/go-formatter"
"github.com/pieterclaerhout/go-log"
)
func main() {
log.PrintColors = true
log.PrintTimestamp = false
cli, err := client.NewEnvClient()
log.CheckError(err)
images, err := cli.ImageList(context.Background(), types.ImageListOptions{
All: false,
})
for _, image := range images {
for _, tag := range image.RepoTags {
tagParts := strings.SplitN(tag, ":", 2)
log.Infof(
"%-25s | %-15s | %s | %-30s | %10s",
tagParts[0],
tagParts[1],
image.ID[7:19],
time.Unix(image.Created, 0),
formatter.FileSize(image.Size),
)
}
}
}
The way it works is pretty simple. We first setup the logging (we are using go-log for this. We then create a client from the current environment (which should auto-detect your Docker installation). The, we can ask the API to use ImageList
to get the full list of running containers. Then we loop through the images and all their tags and output a nicely formatted table.
Then run our program from within the project directory and you should get a list of the images on the system in a nicely formatted table:
$ go run .
temporalio/admin-tools | 1.5.0 | c55157e36ac3 | 2020-12-23 00:03:15 +0100 CET | 244.29 MB
temporalio/auto-setup | 1.5.0 | 3548ab044e07 | 2020-12-23 00:02:35 +0100 CET | 333.88 MB
temporalio/web | 1.4.1 | d53c4f30b7b3 | 2020-12-18 18:56:48 +0100 CET | 369.83 MB
cassandra | 3.11 | 8baadf8d390f | 2020-11-26 04:13:40 +0100 CET | 405.43 MB
mysql | 8 | dd7265748b5d | 2020-11-21 02:22:38 +0100 CET | 545.31 MB
golang | 1.15.5-alpine | 1de1afaeaa9a | 2020-11-12 22:22:23 +0100 CET | 298.83 MB
redis | alpine | c1949ec48c51 | 2020-10-27 19:34:35 +0100 CET | 31.15 MB
example-environ-server | latest | 4f136e1edaa3 | 2020-09-18 17:01:37 +0200 CEST | 23.21 MB
alpine | 3.12 | a24bb4013296 | 2020-05-29 23:19:46 +0200 CEST | 5.57 MB
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.