#development #docker #golang

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:

 1package main
 2
 3import (
 4    "context"
 5    "strings"
 6    "time"
 7
 8    "github.com/docker/docker/api/types"
 9    "github.com/docker/docker/client"
10    "github.com/pieterclaerhout/go-formatter"
11    "github.com/pieterclaerhout/go-log"
12)
13
14func main() {
15
16    log.PrintColors = true
17    log.PrintTimestamp = false
18
19    cli, err := client.NewEnvClient()
20    log.CheckError(err)
21
22    images, err := cli.ImageList(context.Background(), types.ImageListOptions{
23        All: false,
24    })
25
26    for _, image := range images {
27        for _, tag := range image.RepoTags {
28
29            tagParts := strings.SplitN(tag, ":", 2)
30
31            log.Infof(
32                "%-25s | %-15s | %s | %-30s | %10s",
33                tagParts[0],
34                tagParts[1],
35                image.ID[7:19],
36                time.Unix(image.Created, 0),
37                formatter.FileSize(image.Size),
38            )
39        }
40    }
41
42}

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