docker

package
v0.11.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 7, 2026 License: GPL-3.0, LGPL-3.0 Imports: 18 Imported by: 0

Documentation

Overview

Package docker provides a thin abstraction over the Docker CLI.

Index

Constants

View Source
const (
	ComposeProjectLabel         = "com.docker.compose.project"
	ComposeServiceLabel         = "com.docker.compose.service"
	ComposeContainerNumberLabel = "com.docker.compose.container-number"
	ComposeOneoffLabel          = "com.docker.compose.oneoff"
	ComposeConfigHashLabel      = "com.docker.compose.config-hash"
	ComposeConfigFilesLabel     = "com.docker.compose.project.config_files"
	ComposeNetworkLabel         = "com.docker.compose.network"
	ComposeVolumeLabel          = "com.docker.compose.volume"
)

Docker Compose compatibility labels. See https://github.com/docker/compose/blob/main/pkg/api/labels.go

View Source
const MaxBridgeEndpoints = 1023

MaxBridgeEndpoints is the number of containers a Docker bridge network holds at most: a Linux bridge has 1,024 ports (BR_MAX_PORTS), and the kernel reserves port 0. Docker fails to connect another container with "exchange full" (EXFULL).

View Source
const MaxConcurrentCalls = 16

MaxConcurrentCalls is the number of docker commands a Client from NewClient runs at once; further calls wait for one to finish. Creating a cluster probes every node in its own goroutine, so without a bound a large cluster forks hundreds of docker processes that compete with the booting nodes for the daemon. Long-lived streams (Executor.Start, such as docker events) do not count. No call waits for another while it runs, so the bound cannot deadlock.

Variables

View Source
var ErrAddressPoolsExhausted = errors.New("the Docker daemon's default address pools are used up")

ErrAddressPoolsExhausted reports that the Docker daemon has no subnet left in its default address pools for a new network (CreateNetwork).

Functions

func IsAlreadyExists added in v0.11.0

func IsAlreadyExists(err error) bool

IsAlreadyExists reports whether err is docker's error for a network name that another network has: docker network create exits 1 with "network with name x already exists". Like IsNotFound, it needs the *cmdexec.ExitError and its stderr, so that a daemon that cannot be reached does not count.

func IsNotFound added in v0.9.0

func IsNotFound(err error) bool

IsNotFound reports whether err is a docker CLI "resource not found" error rather than a genuine failure. Callers that want the info from a single inspect or rm call can use this to distinguish missing resources without issuing a second existence probe.

Docker exits 1 for many failures, so the exit code alone is not enough: a volume that is still in use exits 1 too, and so does the CLI when it cannot reach the daemon ("... connect: no such file or directory"). The error has to be an *cmdexec.ExitError whose stderr names a missing resource in one of the forms the docker CLI and daemon use: "No such container: x", "No such image: x", "error: no such object: x", "get x: no such volume", "No such network: x" or "network x not found".

func IsVolumeInUse added in v0.9.0

func IsVolumeInUse(err error) bool

IsVolumeInUse reports whether err indicates the volume is still held by a just-removed container. dockerd releases volume mounts asynchronously after `docker rm -f`, so callers tearing down a cluster race the daemon and can retry this specific error.

func SortedLabelFlags added in v0.7.0

func SortedLabelFlags(labels Labels) []string

SortedLabelFlags returns --label k=v flag pairs in sorted key order. Returns nil when labels is nil or empty.

Types

type Client

type Client struct {
	Executor cmdexec.Executor
	Command  string // docker executable path (default: "docker")
	// contains filtered or unexported fields
}

Client provides operations against the Docker CLI.

func NewClient

func NewClient(executor cmdexec.Executor) *Client

NewClient returns a Client that runs docker commands through the given executor, at most MaxConcurrentCalls at once.

func (*Client) AppendFile

func (c *Client) AppendFile(ctx context.Context, container ContainerName, path, content string) error

AppendFile appends content to a file in a running container via docker exec.

func (*Client) ConnectNetwork

func (c *Client) ConnectNetwork(ctx context.Context, network NetworkName, container ContainerName) error

ConnectNetwork connects a container to a network.

func (*Client) ContainerExists

func (c *Client) ContainerExists(ctx context.Context, name ContainerName) (bool, error)

ContainerExists returns true if the given container exists (running or stopped).

func (*Client) CopyFilesToContainer

func (c *Client) CopyFilesToContainer(ctx context.Context, container ContainerName, destDir string, files map[string]File) error

CopyFilesToContainer writes files into a container directory via docker cp. Each file carries its own content and permissions. The container may be running or stopped. Keys are sorted for deterministic tar output.

func (*Client) CopyFromContainer

func (c *Client) CopyFromContainer(ctx context.Context, container ContainerName, srcPath string) ([]byte, error)

CopyFromContainer reads a single file from a container via docker cp. The container may be running or stopped.

func (*Client) CopyToContainer

func (c *Client) CopyToContainer(ctx context.Context, container ContainerName, destDir string, files FileContents) error

CopyToContainer writes files into a container directory via docker cp. All files are written with mode 0644. Use CopyFilesToContainer for explicit per-file permissions.

func (*Client) CreateConfigOnlyNetwork added in v0.11.0

func (c *Client) CreateConfigOnlyNetwork(ctx context.Context, name NetworkName, labels Labels) (NetworkID, error)

CreateConfigOnlyNetwork creates a configuration-only network (docker network create --config-only) and returns its ID. Such a network has no driver: Docker takes no subnet from its address pools for it, creates no bridge device, and attaches no container to it. Like every network create, it fails when another network has the name (see IsAlreadyExists).

func (*Client) CreateContainer

func (c *Client) CreateContainer(ctx context.Context, args ...string) (ContainerID, error)

CreateContainer creates a container without starting it (docker create). Use StartContainer to start it afterwards. Returns the container ID.

func (*Client) CreateNetwork

func (c *Client) CreateNetwork(ctx context.Context, name NetworkName, labels Labels) (NetworkID, error)

CreateNetwork creates a Docker network and returns its ID. Docker takes its subnet from the daemon's default address pools. Labels are applied as --label flags when non-nil.

func (*Client) CreateNetworkWithSubnet added in v0.11.0

func (c *Client) CreateNetworkWithSubnet(ctx context.Context, name NetworkName, labels Labels, ipam NetworkIPAM) (NetworkID, error)

CreateNetworkWithSubnet creates a Docker network with the subnet that ipam configures and returns its ID. Docker accepts a container's --ip only on such a network. Labels are applied as --label flags when non-nil.

func (*Client) CreateVolume

func (c *Client) CreateVolume(ctx context.Context, name VolumeName, labels Labels) error

CreateVolume creates a Docker volume. Labels are applied as --label flags when non-nil.

func (*Client) DisconnectNetwork

func (c *Client) DisconnectNetwork(ctx context.Context, network NetworkName, container ContainerName) error

DisconnectNetwork disconnects a container from a network.

func (*Client) Endpoint added in v0.11.0

func (c *Client) Endpoint(ctx context.Context) (Endpoint, error)

Endpoint returns the address at which the docker CLI reaches the daemon, chosen as the CLI chooses it: DOCKER_HOST, else the docker endpoint of the context that DOCKER_CONTEXT names, else of the current context of the CLI's configuration (`docker context use`), else the default socket. Without DOCKER_HOST it runs `docker context inspect`, which resolves the context without contacting the daemon.

func (*Client) Exec

func (c *Client) Exec(ctx context.Context, container ContainerName, command ...string) (string, error)

Exec runs a command inside a container and returns its stdout.

func (*Client) ExecAllowNonZero added in v0.9.0

func (c *Client) ExecAllowNonZero(ctx context.Context, container ContainerName, command ...string) (string, error)

ExecAllowNonZero is like Exec but returns stdout even when the inner command exits non-zero. The returned error is non-nil iff the exec itself failed (daemon unreachable, container missing, stopped or paused); command-level non-zero exits are surfaced via the stdout return. Intended for commands whose stdout is meaningful on failure (e.g. systemctl is-active, which exits non-zero whenever any listed unit is inactive but still prints the unit states).

func (*Client) ExecWithStdin

func (c *Client) ExecWithStdin(ctx context.Context, container ContainerName, stdin io.Reader, command ...string) error

ExecWithStdin runs a command inside a container, piping stdin to it.

func (*Client) ImageExists

func (c *Client) ImageExists(ctx context.Context, image string) (bool, error)

ImageExists reports whether the daemon has an image, without pulling it.

func (*Client) ImageLabels added in v0.11.0

func (c *Client) ImageLabels(ctx context.Context, image string) (Labels, bool, error)

ImageLabels returns the labels of a local image, and whether the image is there: false, with no error, when it has not been pulled or built.

func (*Client) Info added in v0.11.0

func (c *Client) Info(ctx context.Context) (*DaemonInfo, error)

Info runs `docker info` and returns what it says about the daemon.

With --format the docker CLI reports a daemon it cannot reach in the output's ServerErrors, and may still exit 0; Info returns the first of them as its error.

func (*Client) InspectContainer

func (c *Client) InspectContainer(ctx context.Context, name ContainerName) (*ContainerInfo, error)

InspectContainer returns detailed information about a container.

func (*Client) InspectContainers added in v0.9.0

func (c *Client) InspectContainers(ctx context.Context, names ...ContainerName) ([]*ContainerInfo, error)

InspectContainers returns details for the given containers in a single docker inspect invocation. The returned slice preserves argument order. Returns nil when names is empty.

func (*Client) InspectNetwork

func (c *Client) InspectNetwork(ctx context.Context, name NetworkName) (*NetworkInfo, error)

InspectNetwork returns detailed information about a network.

func (*Client) InspectNetworkMeta added in v0.11.0

func (c *Client) InspectNetworkMeta(ctx context.Context, name NetworkName) (*NetworkMeta, error)

InspectNetworkMeta returns the ID, creation time and labels of a network. The error for a missing network satisfies IsNotFound.

func (*Client) InspectNetworks added in v0.11.0

func (c *Client) InspectNetworks(ctx context.Context, names ...NetworkName) ([]*NetworkInfo, error)

InspectNetworks returns details for the given networks in a single docker network inspect invocation. Returns nil when names is empty.

When some of the networks cannot be inspected, e.g. one was removed after it was listed, docker exits non-zero but still prints the others. InspectNetworks then returns those together with the error, so callers that can do without the missing ones may use them.

func (*Client) KillContainer

func (c *Client) KillContainer(ctx context.Context, name ContainerName) error

KillContainer sends SIGKILL to a running container (docker kill).

func (*Client) ListContainers

func (c *Client) ListContainers(ctx context.Context, filters ...string) ([]ContainerListEntry, error)

ListContainers returns containers matching the given filters, running or not. Each filter is passed as a --filter flag to docker ps (e.g. "label=sind.cluster"); docker ps keeps a container that matches every filter key, and any of the values a key is given more than once with ("network=a", "network=b").

func (*Client) ListNetworks

func (c *Client) ListNetworks(ctx context.Context, filters ...string) ([]NetworkListEntry, error)

ListNetworks returns networks matching the given filters. Each filter is passed as a --filter flag (e.g. "name=sind").

func (*Client) ListVolumes

func (c *Client) ListVolumes(ctx context.Context, filters ...string) ([]VolumeListEntry, error)

ListVolumes returns volumes matching the given filters. Each filter is passed as a --filter flag (e.g. "name=sind-dev").

func (*Client) Logs added in v0.7.1

func (c *Client) Logs(ctx context.Context, name ContainerName, n int) (string, error)

Logs returns the last n lines of a container's log output.

func (*Client) NetworkExists

func (c *Client) NetworkExists(ctx context.Context, name NetworkName) (bool, error)

NetworkExists returns true if the given network exists.

func (*Client) NetworkLabels added in v0.10.0

func (c *Client) NetworkLabels(ctx context.Context, name NetworkName) (Labels, bool, error)

NetworkLabels returns the labels of the given network, and whether it exists.

func (*Client) PauseContainer

func (c *Client) PauseContainer(ctx context.Context, name ContainerName) error

PauseContainer suspends all processes in a container (docker pause).

func (*Client) PullImage added in v0.11.0

func (c *Client) PullImage(ctx context.Context, image string) error

PullImage pulls an image from its registry, also when a copy of it is present.

func (*Client) ReadFile

func (c *Client) ReadFile(ctx context.Context, container ContainerName, path string) (string, error)

ReadFile reads a file from a running container via docker exec.

func (*Client) RemoveContainer

func (c *Client) RemoveContainer(ctx context.Context, name ContainerName) error

RemoveContainer force-removes a container and its anonymous volumes. If the container is running it is killed first. This is equivalent to docker rm -f -v: the sind-node image declares /etc/slurm, /etc/munge and /data as volumes, so a container that mounts no named volume there, such as a config helper or the SSH relay, gets anonymous ones. Named volumes are left alone.

func (*Client) RemoveNetwork

func (c *Client) RemoveNetwork(ctx context.Context, name NetworkName) error

RemoveNetwork removes a Docker network.

func (*Client) RemoveNetworkByID added in v0.11.0

func (c *Client) RemoveNetworkByID(ctx context.Context, id NetworkID) error

RemoveNetworkByID removes the network with the given ID. Unlike a name, an ID never comes to stand for another network, so a caller that inspected a network removes that one and no other.

func (*Client) RemoveVolume

func (c *Client) RemoveVolume(ctx context.Context, name VolumeName) error

RemoveVolume removes a Docker volume.

func (*Client) ReplaceFile added in v0.11.0

func (c *Client) ReplaceFile(ctx context.Context, container ContainerName, path, content string) error

ReplaceFile replaces a file in a running container via docker exec in one step, unlike WriteFile, whose `cat >` truncates it first: the content goes to a temporary file next to path, which takes path's place (rename(2)) only once it holds all of content. A reader sees the old or the new content, never a part of it, even when the docker CLI dies mid-write and the shell in the container reads an early end of input. The file is a new one, owned by the exec user, with its umask's mode.

func (*Client) RunContainer

func (c *Client) RunContainer(ctx context.Context, args ...string) (ContainerID, error)

RunContainer creates and starts a container in detached mode (docker run -d). The args are passed directly and should include the image name as the last element. Returns the container ID.

func (*Client) RunEphemeral

func (c *Client) RunEphemeral(ctx context.Context, image string, command ...string) (string, error)

RunEphemeral runs a command in a temporary container and returns its stdout. The container is removed after the command completes (docker run --rm).

func (*Client) RunEphemeralWith added in v0.11.0

func (c *Client) RunEphemeralWith(ctx context.Context, flags []string, image string, command ...string) (string, error)

RunEphemeralWith is RunEphemeral with extra docker run flags, such as mounts, placed before the image.

func (*Client) ServerVersion added in v0.2.0

func (c *Client) ServerVersion(ctx context.Context) (string, error)

ServerVersion returns the Docker Engine server version string.

func (*Client) SignalContainer

func (c *Client) SignalContainer(ctx context.Context, name ContainerName, signal string) error

SignalContainer sends a signal to a running container (docker kill -s).

func (*Client) StartContainer

func (c *Client) StartContainer(ctx context.Context, name ContainerName) error

StartContainer starts a stopped container.

func (*Client) StopContainer

func (c *Client) StopContainer(ctx context.Context, name ContainerName) error

StopContainer gracefully stops a running container.

func (*Client) UnpauseContainer

func (c *Client) UnpauseContainer(ctx context.Context, name ContainerName) error

UnpauseContainer resumes a paused container (docker unpause).

func (*Client) VolumeExists

func (c *Client) VolumeExists(ctx context.Context, name VolumeName) (bool, error)

VolumeExists returns true if the given volume exists.

func (*Client) VolumeLabels added in v0.10.0

func (c *Client) VolumeLabels(ctx context.Context, name VolumeName) (Labels, bool, error)

VolumeLabels returns the labels of the given volume, and whether it exists.

func (*Client) VolumePlugins added in v0.11.0

func (c *Client) VolumePlugins(ctx context.Context) ([]string, error)

VolumePlugins returns the names of the enabled managed plugins that provide a volume driver, as docker plugin ls prints them: with their tag, e.g. "cvmfs:latest".

func (*Client) WriteFile

func (c *Client) WriteFile(ctx context.Context, container ContainerName, path, content string) error

WriteFile overwrites a file in a running container via docker exec.

type ContainerID

type ContainerID string

ContainerID is a Docker container identifier (64 hex characters).

type ContainerInfo

type ContainerInfo struct {
	ID        ContainerID
	Name      ContainerName
	ImageRef  string // image reference the container was created from
	Status    ContainerState
	ExitCode  int
	OOMKilled bool
	Labels    Labels
	IPs       map[NetworkName]string
	Mounts    []Mount  // bind mounts and volumes; tmpfs mounts are not listed
	DNS       []string // DNS servers set with --dns
	// Image is the ID of the image the container runs (sha256:...), which
	// stays valid when the reference it was created from moves.
	Image      string
	HostConfig HostConfig
}

ContainerInfo holds inspected container details.

type ContainerListEntry

type ContainerListEntry struct {
	ID       ContainerID
	Name     ContainerName
	State    ContainerState
	Image    string
	Labels   Labels
	Networks []NetworkName
}

ContainerListEntry holds summary information from docker ps. Networks are the networks the container is connected to, also while it is stopped.

type ContainerName

type ContainerName string

ContainerName is a human-readable Docker container name.

type ContainerState added in v0.7.0

type ContainerState string

ContainerState represents the state of a Docker container.

const (
	StateRunning ContainerState = "running"
	StatePaused  ContainerState = "paused"
	StateExited  ContainerState = "exited"
	StateDead    ContainerState = "dead"
	StateCreated ContainerState = "created"
)

Known container states returned by Docker.

type DaemonInfo added in v0.11.0

type DaemonInfo struct {
	// ServerVersion is the Docker Engine version, e.g. "28.1.1".
	ServerVersion string `json:"ServerVersion"`
	// CgroupVersion is the cgroup version containers run on, "1" or "2".
	CgroupVersion string `json:"CgroupVersion"`
	// SecurityOptions lists the daemon's security features, one entry per
	// feature, e.g. "name=seccomp,profile=builtin", "name=rootless" or
	// "name=userns".
	SecurityOptions []string `json:"SecurityOptions"`
	// OperatingSystem is the daemon host's operating system, e.g.
	// "Ubuntu 24.04.3 LTS", or "Docker Desktop" in Docker Desktop's VM.
	OperatingSystem string `json:"OperatingSystem"`
	// Name is the daemon host's hostname, "docker-desktop" in Docker
	// Desktop's VM.
	Name string `json:"Name"`
	// KernelVersion is the release of the kernel the daemon runs on, as
	// uname -r prints it, e.g. "6.8.0-1017-azure".
	KernelVersion string `json:"KernelVersion"`
}

DaemonInfo is the part of `docker info` that sind checks: facts about the daemon, which need not run on the machine sind runs on.

func (*DaemonInfo) DockerDesktop added in v0.11.0

func (i *DaemonInfo) DockerDesktop() bool

DockerDesktop reports whether the daemon is Docker Desktop's, which runs in a VM with a kernel of its own, not on the machine of the docker CLI.

func (*DaemonInfo) HasSecurityOption added in v0.11.0

func (i *DaemonInfo) HasSecurityOption(name string) bool

HasSecurityOption reports whether the daemon lists the security feature name among its SecurityOptions, e.g. "rootless" or "userns".

type DeviceMapping added in v0.11.0

type DeviceMapping struct {
	PathOnHost        string `json:"PathOnHost"`
	PathInContainer   string `json:"PathInContainer"`
	CgroupPermissions string `json:"CgroupPermissions"`
}

DeviceMapping is a host device exposed to a container (--device).

type Endpoint added in v0.11.0

type Endpoint struct {
	// Host is the daemon's address, e.g. "unix:///var/run/docker.sock",
	// "tcp://build-host:2376" or "ssh://ci@build-host".
	Host string
	// Context is the docker context that Host comes from, empty when
	// DOCKER_HOST sets it.
	Context string
}

Endpoint is the address at which the docker CLI reaches the daemon.

func (Endpoint) UnixSocket added in v0.11.0

func (e Endpoint) UnixSocket() bool

UnixSocket reports whether the CLI reaches the daemon through a unix socket, as it does a daemon on its own machine.

type File

type File struct {
	Content []byte
	Mode    int64 // e.g. 0644, 0600
}

File represents a file to copy into a container with explicit permissions.

type FileContents added in v0.7.0

type FileContents map[string][]byte

FileContents maps file paths to their raw content for copying into containers.

type HostConfig added in v0.11.0

type HostConfig struct {
	NanoCPUs    int64             `json:"NanoCpus"` // --cpus, in billionths of a CPU
	Memory      int64             `json:"Memory"`   // --memory, in bytes
	Tmpfs       map[string]string `json:"Tmpfs"`    // mount point → --tmpfs options
	CapAdd      []string          `json:"CapAdd"`   // as the docker CLI normalizes them, e.g. CAP_SYS_ADMIN
	CapDrop     []string          `json:"CapDrop"`
	Devices     []DeviceMapping   `json:"Devices"`
	SecurityOpt []string          `json:"SecurityOpt"`
	DNS         []string          `json:"Dns"` // --dns
}

HostConfig is the part of a container's host configuration that sind reads back: its resource limits and privileges.

type Labels added in v0.7.0

type Labels map[string]string

Labels is a set of key-value metadata pairs applied to Docker resources.

func ComposeLabels added in v0.7.0

func ComposeLabels(project, service string, containerNumber int) Labels

ComposeLabels returns the standard Docker Compose compatibility labels for a container. These labels make sind containers appear as part of a compose project.

type Mount added in v0.11.0

type Mount struct {
	Type        MountType  `json:"Type"`
	Name        VolumeName `json:"Name"`        // the volume, for MountVolume
	Source      string     `json:"Source"`      // the host path
	Destination string     `json:"Destination"` // the mount point in the container
}

Mount is a bind mount or volume of a container, as docker inspect reports it.

type MountType added in v0.11.0

type MountType string

MountType is the kind of a container mount.

const (
	MountBind   MountType = "bind"
	MountVolume MountType = "volume"
)

Mount types docker inspect reports.

type NetworkID

type NetworkID string

NetworkID is a Docker network identifier.

type NetworkIPAM added in v0.11.0

type NetworkIPAM struct {
	Subnet  string // CIDR, e.g. 172.18.0.0/16
	Gateway string // address in Subnet; empty lets Docker choose
	// IPRange is the CIDR within Subnet that Docker takes the addresses of
	// containers from that ask for none; empty for all of Subnet. A
	// container's --ip may lie outside it.
	IPRange string
}

NetworkIPAM is a network's IPv4 subnet as the user configures it, rather than one Docker takes from its default address pools.

type NetworkInfo

type NetworkInfo struct {
	ID      string
	Name    NetworkName
	Driver  string
	Subnet  string
	Gateway string
	IPRange string
	Labels  Labels
}

NetworkInfo holds detailed information about a Docker network. Subnet, Gateway and IPRange are those of its first IPAM configuration; IPRange is empty unless the user configured one.

type NetworkListEntry

type NetworkListEntry struct {
	Name   NetworkName
	Driver string
	Labels Labels
}

NetworkListEntry holds summary information from docker network ls.

type NetworkMeta added in v0.11.0

type NetworkMeta struct {
	ID         NetworkID
	Name       NetworkName
	Created    time.Time // by the daemon's clock
	ConfigOnly bool
	Labels     Labels
}

NetworkMeta is a network's ID, name, creation time and labels.

type NetworkName

type NetworkName string

NetworkName is a human-readable Docker network name.

type VolumeListEntry

type VolumeListEntry struct {
	Name   VolumeName
	Driver string
	Labels Labels
}

VolumeListEntry holds summary information from docker volume ls.

type VolumeName

type VolumeName string

VolumeName is a human-readable Docker volume name.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL