How to control Docker with pure Go

Frikky
2 min readJun 18, 2019

Ever tried googling how to interface with Docker from Golang? Yes? Here are some Golang examples for building Docker images from Dockerfiles (a little confusing and annoying), running custom containers (VERY annoying to configure the first time) and stopping / removing containers (trivial).

ISSUE: Most of all examples I’ve previously found are defined as seen below. I have specific examples for custom configurations instead of this.

// Some Golang code to explain the issue here. Most examples don't // add any configuration properties, just "nil". 
resp, err := cli.ContainerCreate(ctx, &container.Config{
Image: "alpine",
Cmd: []string{"echo", "hello world"},
}, nil, nil, "")

First, let’s find the Docker API version to be used.

# Get the docker version
$ docker version
Server: Docker Engine - Community
Engine:
Version: 18.09.6
API version: 1.39 (minimum version 1.12)
Go version: go1.10.8
Git commit: 481bc77
Built: Sat May 4 01:59:36 2019
OS/Arch: linux/amd64
Experimental: false
# As seen above, my API server version is 1.39, so lets set the environment variable.
export DOCKER_API_VERSION=1.39

Building an image from a Dockerfile (Config: https://godoc.org/github.com/docker/docker/api/types#ImageBuildOptions):

Deploying a container with custom network and environment configurations (port 8080 natted)

A possible issue you may find with this example is that the “vendor” folder is recursively added to your GOPATH (github.com/docker/docker/vendor). If it doesn’t run or throws some error related to networking, delete this folder.

# Delete the folder
rm -rf $GOPATH/src/github.com/docker/docker/vendor

Stop and remove a container:

What’s the real issue here thought? Why is it so hard to do this? The lack of good examples seems obvious. I used the technique I described in my previous article regarding the same, which involves finding your function and walking every parameter backwards based on the Godocs. This is kind of what the Docs are for, but as a newbie to godocs, it’s a real struggle.

All examples can be found here:

Hope it helps. If you have another approach, please reach out

--

--