Docker provides a powerful API to interact with its engine programmatically. In this article, we will see how to use the Docker Engine API with Go and its SDK.
Installing the Docker Client for Go
To interact with Docker from Go, you need to install the github.com/docker/docker/client
package. We can do this using Go modules:
go get github.com/docker/docker
Additionally, make sure that Docker is running on your system.
Creating a Docker Client in Go
To get started, we need to create an instance of the Docker client:
package main
import (
"context"
"fmt"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
)
func main() {
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
panic(err)
}
defer cli.Close()
version, err := cli.ServerVersion(context.Background())
if err != nil {
panic(err)
}
fmt.Println("Docker Server Version:", version.Version)
}
The code above creates a Docker client using the system environment and prints the Docker server version.
Listing Running Containers
We can list running containers using the ContainerList
method:
func listContainers(cli *client.Client) {
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{})
if err != nil {
panic(err)
}
for _, container := range containers {
fmt.Println(container.ID[:10], container.Image, container.State)
}
}
Creating and Starting a Container
To create a new container, we use the ContainerCreate
method and then start it using ContainerStart
:
import "github.com/docker/docker/api/types/container"
func createAndStartContainer(cli *client.Client) {
resp, err := cli.ContainerCreate(
context.Background(),
&container.Config{
Image: "nginx",
},
nil, nil, nil, "my-nginx-container",
)
if err != nil {
panic(err)
}
err = cli.ContainerStart(context.Background(), resp.ID, types.ContainerStartOptions{})
if err != nil {
panic(err)
}
fmt.Println("Container started with ID:", resp.ID)
}
Conclusion
We have seen how to use the Docker Engine API with Go and its SDK to interact with Docker programmatically. This allows us to manage containers and resources in a flexible and automated way.