Practice of using Golang to play Docker API

  • 2021-10-27 09:56:30
  • OfStack

Directory Installation of SDK
Manage local Docker
Running container
Background run container
View Container List
Stop all running containers
Gets the log for the specified container
View the Mirror List
Pull mirror image
Pull private image
Save the container as a mirror image
Manage remote Docker
Remote connection
Modify client
Summarize

Docker provides an API (called Docker Engine API) that interacts with the Docker daemon, and we can build and extend Docker applications and solutions using SDK in the official Go language.

Installing SDK

SDK can be installed with the following command:


go get github.com/docker/docker/client

Manage local Docker

This section describes how to manage a local Docker using Golang + Docker API.

Running container

The first example shows how to run the container, which is equivalent to docker run docker. io/library/alpine echo "hello world":


package main

import (
 "context"
 "io"
 "os"

 "github.com/docker/docker/api/types"
 "github.com/docker/docker/api/types/container"
 "github.com/docker/docker/client"
 "github.com/docker/docker/pkg/stdcopy"
)

func main() {
 ctx := context.Background()
 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
 if err != nil {
 panic(err)
 }

 reader, err := cli.ImagePull(ctx, "docker.io/library/alpine", types.ImagePullOptions{})
 if err != nil {
 panic(err)
 }
 io.Copy(os.Stdout, reader)

 resp, err := cli.ContainerCreate(ctx, &container.Config{
 Image: "alpine",
 Cmd: []string{"echo", "hello world"},
 }, nil, nil, "")
 if err != nil {
 panic(err)
 }

 if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
 panic(err)
 }

 statusCh, errCh := cli.ContainerWait(ctx, resp.ID, container.WaitConditionNotRunning)
 select {
 case err := <-errCh:
 if err != nil {
  panic(err)
 }
 case <-statusCh:
 }

 out, err := cli.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ShowStdout: true})
 if err != nil {
 panic(err)
 }

 stdcopy.StdCopy(os.Stdout, os.Stderr, out)
}

Background run container

You can also run the container in the background, equivalent to docker run-d bfirsh/reticulate-splines:


package main

import (
 "context"
 "fmt"
 "io"
 "os"

 "github.com/docker/docker/api/types"
 "github.com/docker/docker/api/types/container"
 "github.com/docker/docker/client"
)

func main() {
 ctx := context.Background()
 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
 if err != nil {
 panic(err)
 }

 imageName := "bfirsh/reticulate-splines"

 out, err := cli.ImagePull(ctx, imageName, types.ImagePullOptions{})
 if err != nil {
 panic(err)
 }
 io.Copy(os.Stdout, out)

 resp, err := cli.ContainerCreate(ctx, &container.Config{
 Image: imageName,
 }, nil, nil, "")
 if err != nil {
 panic(err)
 }

 if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
 panic(err)
 }

 fmt.Println(resp.ID)
}

View Container List

List the containers that are running, as with docker ps 1:


package main

import (
 "context"
 "fmt"

 "github.com/docker/docker/api/types"
 "github.com/docker/docker/client"
)

func main() {
 ctx := context.Background()
 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
 if err != nil {
  panic(err)
 }

 containers, err := cli.ContainerList(ctx, types.ContainerListOptions{})
 if err != nil {
  panic(err)
 }

 for _, container := range containers {
  fmt.Println(container.ID)
 }
}

In the case of docker ps-a, we can do this by modifying the All property in types. ContainerListOptions:


// type ContainerListOptions struct {
// Quiet bool
// Size bool
// All  bool
// Latest bool
// Since string
// Before string
// Limit int
// Filters filters.Args
// }

options := types.ContainerListOptions{
 All: true,
}
containers, err := cli.ContainerList(ctx, options)
if err != nil {
 panic(err)
}

Stop all running containers

From the above example, we can get the list of containers, so in this case, we can stop all running containers.

Note: Do not run the following code on the production server.


package main

import (
 "context"
 "fmt"

 "github.com/docker/docker/api/types"
 "github.com/docker/docker/client"
)

func main() {
 ctx := context.Background()
 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
 if err != nil {
  panic(err)
 }

 containers, err := cli.ContainerList(ctx, types.ContainerListOptions{})
 if err != nil {
  panic(err)
 }

 for _, container := range containers {
  fmt.Print("Stopping container ", container.ID[:10], "... ")
  if err := cli.ContainerStop(ctx, container.ID, nil); err != nil {
   panic(err)
  }
  fmt.Println("Success")
 }
}

Gets the log for the specified container

By specifying the ID of the container, we can get the log of the container corresponding to ID:


package main

import (
 "context"
 "io"
 "os"

 "github.com/docker/docker/api/types"
 "github.com/docker/docker/client"
)

func main() {
 ctx := context.Background()
 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
 if err != nil {
  panic(err)
 }

 options := types.ContainerLogsOptions{ShowStdout: true}

 out, err := cli.ContainerLogs(ctx, "f1064a8a4c82", options)
 if err != nil {
  panic(err)
 }

 io.Copy(os.Stdout, out)
}

View the Mirror List

Gets all local images, equivalent to docker image ls or docker images:


package main

import (
 "context"
 "fmt"

 "github.com/docker/docker/api/types"
 "github.com/docker/docker/client"
)

func main() {
 ctx := context.Background()
 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
 if err != nil {
  panic(err)
 }

 images, err := cli.ImageList(ctx, types.ImageListOptions{})
 if err != nil {
  panic(err)
 }

 for _, image := range images {
  fmt.Println(image.ID)
 }
}

Pull mirror image

Pull the specified image, equivalent to docker pull alpine:


package main

import (
 "context"
 "io"
 "os"

 "github.com/docker/docker/api/types"
 "github.com/docker/docker/client"
)

func main() {
 ctx := context.Background()
 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
 if err != nil {
  panic(err)
 }

 out, err := cli.ImagePull(ctx, "alpine", types.ImagePullOptions{})
 if err != nil {
  panic(err)
 }

 defer out.Close()

 io.Copy(os.Stdout, out)
}

Pull private image

In addition to public images, we usually use one private image, which can be a private image on DockerHub or a self-managed image warehouse, such as harbor. At this time, we need to provide the corresponding credentials before we can pull the mirror image.

It is worth noting that when using Go SDK of Docker API, credentials are transmitted in clear text, so be sure to use HTTPS if you are a self-built mirror repository!


package main

import (
 "context"
 "encoding/base64"
 "encoding/json"
 "io"
 "os"

 "github.com/docker/docker/api/types"
 "github.com/docker/docker/client"
)

func main() {
 ctx := context.Background()
 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
 if err != nil {
  panic(err)
 }

 authConfig := types.AuthConfig{
  Username: "username",
  Password: "password",
 }
 encodedJSON, err := json.Marshal(authConfig)
 if err != nil {
  panic(err)
 }
 authStr := base64.URLEncoding.EncodeToString(encodedJSON)

 out, err := cli.ImagePull(ctx, "alpine", types.ImagePullOptions{RegistryAuth: authStr})
 if err != nil {
  panic(err)
 }

 defer out.Close()
 io.Copy(os.Stdout, out)
}

Save the container as a mirror image

We can save an existing container as a mirror image through commit:


package main

import (
 "context"
 "io"
 "os"

 "github.com/docker/docker/api/types"
 "github.com/docker/docker/api/types/container"
 "github.com/docker/docker/client"
 "github.com/docker/docker/pkg/stdcopy"
)

func main() {
 ctx := context.Background()
 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
 if err != nil {
 panic(err)
 }

 reader, err := cli.ImagePull(ctx, "docker.io/library/alpine", types.ImagePullOptions{})
 if err != nil {
 panic(err)
 }
 io.Copy(os.Stdout, reader)

 resp, err := cli.ContainerCreate(ctx, &container.Config{
 Image: "alpine",
 Cmd: []string{"echo", "hello world"},
 }, nil, nil, "")
 if err != nil {
 panic(err)
 }

 if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
 panic(err)
 }

 statusCh, errCh := cli.ContainerWait(ctx, resp.ID, container.WaitConditionNotRunning)
 select {
 case err := <-errCh:
 if err != nil {
  panic(err)
 }
 case <-statusCh:
 }

 out, err := cli.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ShowStdout: true})
 if err != nil {
 panic(err)
 }

 stdcopy.StdCopy(os.Stdout, os.Stderr, out)
}

0

Manage remote Docker

Of course, in addition to managing the local Docker, we can also manage the remote Docker by using Golang + Docker API.

Remote connection

The default Docker runs over a non-networked Unix socket and can only communicate locally (/var/run/docker. sock) and cannot be connected directly to Docker remotely.
We need to edit the configuration file/etc/docker/daemon. json and modify the following (change 192.168. 59.3 to your own IP address), then restart Docker:


package main

import (
 "context"
 "io"
 "os"

 "github.com/docker/docker/api/types"
 "github.com/docker/docker/api/types/container"
 "github.com/docker/docker/client"
 "github.com/docker/docker/pkg/stdcopy"
)

func main() {
 ctx := context.Background()
 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
 if err != nil {
 panic(err)
 }

 reader, err := cli.ImagePull(ctx, "docker.io/library/alpine", types.ImagePullOptions{})
 if err != nil {
 panic(err)
 }
 io.Copy(os.Stdout, reader)

 resp, err := cli.ContainerCreate(ctx, &container.Config{
 Image: "alpine",
 Cmd: []string{"echo", "hello world"},
 }, nil, nil, "")
 if err != nil {
 panic(err)
 }

 if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
 panic(err)
 }

 statusCh, errCh := cli.ContainerWait(ctx, resp.ID, container.WaitConditionNotRunning)
 select {
 case err := <-errCh:
 if err != nil {
  panic(err)
 }
 case <-statusCh:
 }

 out, err := cli.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ShowStdout: true})
 if err != nil {
 panic(err)
 }

 stdcopy.StdCopy(os.Stdout, os.Stderr, out)
}

1

Modify client

When creating client, you need to specify the address of the remote Docker, so that you can manage the remote Docker just like the local Docker 1:


package main

import (
 "context"
 "io"
 "os"

 "github.com/docker/docker/api/types"
 "github.com/docker/docker/api/types/container"
 "github.com/docker/docker/client"
 "github.com/docker/docker/pkg/stdcopy"
)

func main() {
 ctx := context.Background()
 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
 if err != nil {
 panic(err)
 }

 reader, err := cli.ImagePull(ctx, "docker.io/library/alpine", types.ImagePullOptions{})
 if err != nil {
 panic(err)
 }
 io.Copy(os.Stdout, reader)

 resp, err := cli.ContainerCreate(ctx, &container.Config{
 Image: "alpine",
 Cmd: []string{"echo", "hello world"},
 }, nil, nil, "")
 if err != nil {
 panic(err)
 }

 if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
 panic(err)
 }

 statusCh, errCh := cli.ContainerWait(ctx, resp.ID, container.WaitConditionNotRunning)
 select {
 case err := <-errCh:
 if err != nil {
  panic(err)
 }
 case <-statusCh:
 }

 out, err := cli.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ShowStdout: true})
 if err != nil {
 panic(err)
 }

 stdcopy.StdCopy(os.Stdout, os.Stderr, out)
}

2

Summarize

There are many products that can manage Docker, and they are implemented in this way, such as portainer.


Related articles: