Skip to content

docker

Helpers for working with the Docker Engine API.

docker collects everyday Docker Engine API helpers: container names and Compose labels, mount translation, network selection, exec, log streaming, progress rendering, and cached volume usage. It works with the github.com/moby/moby/client SDK.

Module
go.getarcane.app/docker
Reference
pkg.go.dev
Terminal window
go get go.getarcane.app/docker@latest
import "go.getarcane.app/docker"
name := docker.ContainerNameFromNames(summary.Names) // "/web" -> "web"
project := docker.ComposeProjectLabel(summary.Labels)
service := docker.ComposeServiceLabel(summary.Labels)
excluded := docker.ExcludedContainerNameSet("watchtower, traefik")
if docker.ContainerNameExcluded(summary.Names, excluded) {
return
}
Function Description
ComposeProjectLabel / ComposeServiceLabel Trimmed com.docker.compose.project / .service label values
ContainerNameFromNames First container name, without Docker’s leading slash
ExcludedContainerNameSet / ContainerNameExcluded Parse and test a comma-separated exclusion setting
ContainerAnswersToHostname Reports whether a container is reachable as a hostname by name, Compose service, or DNS alias

ExecInContainer runs a command, splits the multiplexed output into stdout and stderr, and returns the exit code. A non-zero exit code is not an error. The caller decides what it means.

var stdout, stderr bytes.Buffer
code, err := docker.ExecInContainer(ctx, cli, containerID, client.ExecCreateOptions{
Cmd: []string{"pg_dump", "-U", "postgres", "app"},
}, &stdout, &stderr)

For lower-level streams, StartStdCopy demultiplexes in a goroutine and WaitStdCopy waits for it, treating a normal end of stream as success.

logs := make(chan string)
go func() {
defer close(logs)
_ = docker.StreamContainerLogs(ctx, reader, logs, true /* follow */, inspect.Config.Tty)
}()
for line := range logs {
fmt.Println(line)
}
Function Description
StreamContainerLogs Handles both raw TTY streams and multiplexed stdout/stderr
StreamMultiplexedLogs Demultiplexes and sends non-empty lines
ReadAllLogs Same as above, for non-follow streams
ReadLogLines Sends each line from any reader with an optional prefix
IsExpectedStreamEndError Tells a normal end of stream apart from a real failure
NewLogLineWriter Wraps an io.Writer so each written line becomes a {"log":"..."} NDJSON frame

RenderJSONMessageStream(reader, out) renders a pull, push, build, or load JSON message stream the way the Docker CLI prints it in non-TTY mode. Daemon-reported errors are returned unchanged.

The docker/types package defines ProgressWriterKey, a context key for passing an io.Writer that receives progress output, such as one wrapping an HTTP response.

These helpers let a helper container see the same files as the current container. They work whether those files come from bind mounts or named volumes.

Function Description
MountForDestination Mirrors an existing mount at a new target
MountForSubpath Exposes a subtree of an existing mount. Named volumes use VolumeOptions.Subpath, so this works on Docker Desktop and Docker-in-Docker
MountForEnclosingPath Like MountForSubpath, but the subpath doesn’t need to exist yet. Useful for restores
NestedMounts Mirrors every mount nested below a path, parents before children
PreserveVolumeMounts Pins anonymous volumes to their names so a recreated container reuses them
// The current container mounts /app/data, and we want a helper container to see
// /app/data/projects/demo at /workspace.
m := docker.MountForSubpath(self.Mounts, "/app/data/projects/demo", "/workspace")
Function Description
SelectAutoNetworkMode Chooses the network a helper container should share, preferring user-defined networks
SelectDockerHostReachableNetworkMode Chooses a network from which a TCP DOCKER_HOST (for example, a socket proxy) is reachable
IsDefaultNetwork Reports whether a name is one of Docker’s built-in networks
BuildNetworkUsageMaps Indexes network attachments by ID and by name

Volume usage (docker system df -v) is slow, so it is cached for each daemon:

Function Description
GetVolumeUsageData Current data. Concurrent callers share one in-flight refresh
GetVolumeUsageDataStaleWhileRevalidate Returns the cached snapshot immediately (as mo.Option) and refreshes in the background
FetchVolumeUsageData Skips the cache
InvalidateVolumeUsageCache Clears the cache after a change
GetContainersUsingVolume / FilterContainersUsingVolume Containers that mount a volume. For batches, list containers once and use Filter…