docker

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2026 License: MIT Imports: 16 Imported by: 0

README

Documentation

Overview

Package docker is a dependency-light client for the Docker Engine REST API: containers, images, volumes, exec, and the Engine's two stream formats (stdcopy multiplexing and JSON progress streams). It speaks HTTP directly over the daemon socket — honoring DOCKER_HOST — so consumers inherit no Docker SDK module graph, and every part of it is testable against httptest fakes: the transport (Doer), host, environment, and API version are all injectable options.

Index

Constants

View Source
const (
	ErrBadParameter     errs.Const = "daemon rejected the request"
	ErrCanceled         errs.Const = "operation canceled"
	ErrConflict         errs.Const = "conflicting resource state"
	ErrConnect          errs.Const = "connecting to the docker daemon"
	ErrDecodeResponse   errs.Const = "decoding daemon response"
	ErrEncodeRequest    errs.Const = "encoding request body"
	ErrFrameTooLarge    errs.Const = "stream frame exceeds the size limit"
	ErrHost             errs.Const = "unsupported docker host"
	ErrNotFound         errs.Const = "no such resource"
	ErrPing             errs.Const = "pinging the docker daemon"
	ErrPull             errs.Const = "pulling image"
	ErrServer           errs.Const = "daemon internal error"
	ErrStream           errs.Const = "malformed multiplexed stream"
	ErrStreamError      errs.Const = "daemon reported a stream error"
	ErrUnexpectedStatus errs.Const = "unexpected daemon status"
)

Sentinel errors this package emits, matchable with errors.Is. The Const mechanism is owned by gomatic/go-error. Keep sorted alphabetically.

Daemon failures carry the Engine's error envelope message via With, so a wrapped sentinel still matches while preserving the daemon's diagnostic.

Variables

This section is empty.

Functions

func DemuxStream

func DemuxStream(source io.Reader, stdout, stderr io.Writer) error

DemuxStream copies a multiplexed Engine stream onto stdout and stderr until EOF. A system frame (the daemon's in-band error channel) surfaces as ErrStreamError carrying the frame payload; a malformed frame surfaces as ErrStream; an oversize frame as ErrFrameTooLarge.

func ScanStream

func ScanStream(source io.Reader, handle StreamHandler) error

ScanStream decodes an Engine JSON stream, invoking handle per message, and converts an in-band error document into ErrStreamError. A nil handler just watches for failure.

Types

type APIVersion

type APIVersion string

APIVersion is a Docker Engine API version like "1.43". Supplying it as an option pins the client and skips negotiation; otherwise the daemon's reported version is adopted at construction.

type Capability added in v0.4.0

type Capability string

Capability names one Linux capability in the Engine's vocabulary, like "ALL" or "NET_BIND_SERVICE".

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client speaks the Engine API for one daemon. The zero value is not usable; construct with New. Client is a value: it holds only immutable configuration plus the injected transport, so it is safe to copy and share.

func New

func New(ctx context.Context, options ...Option) (Client, error)

New resolves the daemon endpoint, builds the transport, and negotiates the API version (unless one was pinned). The returned Client is ready for use and safe to copy.

func (Client) ContainerLogs

func (c Client) ContainerLogs(
	ctx context.Context,
	id ContainerID,
	options LogOptions,
	stdout, stderr io.Writer,
) error

ContainerLogs copies a container's stdout and stderr onto the two writers, demultiplexing the Engine's framed stream. It returns when the backlog is exhausted — or, when following, when the container stops or the context is canceled.

func (Client) Containers

func (c Client) Containers(ctx context.Context, query ContainerQuery) ([]ContainerSummary, error)

Containers lists containers matching the query.

func (Client) CreateContainer

func (c Client) CreateContainer(ctx context.Context, spec ContainerSpec) (ContainerID, error)

CreateContainer creates a container from spec and returns its identifier.

func (Client) CreateVolume

func (c Client) CreateVolume(ctx context.Context, spec VolumeSpec) (VolumeDetails, error)

CreateVolume creates a named volume; creating an existing name returns the existing volume unchanged (Engine semantics).

func (Client) Exec

func (c Client) Exec(
	ctx context.Context,
	id ContainerID,
	command Command,
	options ExecOptions,
) (ExitCode, error)

Exec runs command inside the container and returns its exit code, polling until the command finishes or the context is canceled.

func (Client) ImageExists

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

ImageExists reports whether the daemon holds the image locally.

func (Client) InspectContainer

func (c Client) InspectContainer(ctx context.Context, id ContainerID) (ContainerDetails, error)

InspectContainer returns the current state of one container.

func (Client) InspectVolume

func (c Client) InspectVolume(ctx context.Context, name VolumeName) (VolumeDetails, error)

InspectVolume returns one volume's state.

func (Client) Ping

func (c Client) Ping(ctx context.Context) (APIVersion, error)

Ping verifies daemon connectivity and returns the API version the daemon reports (empty when the daemon predates the header).

func (Client) PullImage

func (c Client) PullImage(ctx context.Context, image ImageRef, options PullOptions) error

PullImage pulls an image, scanning the Engine's progress stream so a pull that fails mid-stream — auth failure, missing manifest, platform mismatch — returns an error instead of a silent HTTP 200 success.

func (Client) RemoveContainer

func (c Client) RemoveContainer(ctx context.Context, id ContainerID, options RemovalOptions) error

RemoveContainer removes a container. Force removal stops a running container first; volume removal also deletes its anonymous volumes.

func (Client) RemoveVolume

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

RemoveVolume deletes a named volume.

func (Client) StartContainer

func (c Client) StartContainer(ctx context.Context, id ContainerID) error

StartContainer starts a created container.

func (Client) StopContainer

func (c Client) StopContainer(ctx context.Context, id ContainerID, grace StopSeconds) error

StopContainer stops a running container, allowing it grace seconds to exit. Stopping an already-stopped container succeeds.

func (Client) Volumes

func (c Client) Volumes(ctx context.Context, query VolumeQuery) ([]VolumeDetails, error)

Volumes lists volumes matching the query.

func (Client) WaitContainer

func (c Client) WaitContainer(
	ctx context.Context,
	id ContainerID,
	condition WaitCondition,
) (ExitCode, error)

WaitContainer blocks until the container reaches the condition and returns its exit code. Cancellation is the caller's context; there is no internal polling or recursion.

type Command

type Command []string

Command is an argv vector (entrypoint or command override).

type Connection

type Connection struct {
	Doer Doer
}

Connection injects the HTTP transport used to reach the daemon; tests pass an httptest client or a hand-rolled fake.

type ContainerDetails

type ContainerDetails struct {
	Labels    Labels
	ID        ContainerID
	Name      ContainerName
	Image     ImageRef
	Status    ContainerStatus
	Mounts    []MountDetails
	ExitCode  ExitCode
	IsRunning bool
}

ContainerDetails is the inspected state of one container.

type ContainerID

type ContainerID string

ContainerID is the Engine-assigned container identifier.

type ContainerName

type ContainerName string

ContainerName is the caller-chosen container name.

type ContainerQuery

type ContainerQuery struct {
	Labels     Labels
	Name       ContainerName
	AllEnabled bool
}

ContainerQuery filters container listings. Zero-value fields do not filter; AllEnabled includes stopped containers.

type ContainerSpec

type ContainerSpec struct {
	Name                  ContainerName
	Image                 ImageRef
	Command               Command
	Entrypoint            Command
	Env                   Env
	Labels                Labels
	WorkingDir            WorkDir
	User                  ContainerUser
	Network               NetworkMode
	Platform              Platform
	Mounts                []Mount
	Ports                 []PortBinding
	Tmpfs                 Tmpfs
	CapDrop               []Capability
	SecurityOptions       []SecurityOption
	AutoRemoveEnabled     bool
	ReadOnlyRootfsEnabled bool
}

ContainerSpec describes a container to create. Zero fields defer to image or daemon defaults.

type ContainerStatus

type ContainerStatus string

ContainerStatus is the Engine's lifecycle state word ("created", "running", "exited", ...).

type ContainerSummary

type ContainerSummary struct {
	Labels Labels
	ID     ContainerID
	Name   ContainerName
	Image  ImageRef
	Status ContainerStatus
}

ContainerSummary is one row of a container listing.

type ContainerUser added in v0.4.0

type ContainerUser string

ContainerUser is the run-as user for a container or exec — "name", "uid", "name:group", or "uid:gid"; empty defers to the image default.

type Doer

type Doer interface {
	Do(request *http.Request) (*http.Response, error)
}

Doer issues one HTTP request. It matches (*http.Client).Do so production wraps a real client while tests substitute a fake or an httptest client.

type Env

type Env []EnvVar

Env is the container environment.

type EnvVar

type EnvVar string

EnvVar is one KEY=value environment entry.

type Environment

type Environment EnvironmentLookup

Environment injects the environment lookup consulted for DOCKER_HOST; production defaults to os.LookupEnv.

type EnvironmentLookup

type EnvironmentLookup func(key string) (string, bool)

EnvironmentLookup reads one environment variable, reporting whether it is set. It matches os.LookupEnv so production passes that function directly while tests substitute a fake.

type ExecOptions

type ExecOptions struct {
	// User runs the command as this user; empty inherits the container's
	// configured user.
	User ContainerUser
	// Env adds environment entries visible to the command.
	Env Env
	// PollInterval is the delay between exit-code polls; zero uses
	// defaultExecPollInterval.
	PollInterval time.Duration
}

ExecOptions adjusts an in-container command run.

type ExitCode

type ExitCode int64

ExitCode is a container or exec process exit status.

type HTTPMethod

type HTTPMethod string

HTTPMethod is an HTTP request method.

type HTTPStatus

type HTTPStatus int

HTTPStatus is an HTTP response status code.

type HostAddress

type HostAddress string

HostAddress locates a Docker daemon: a unix://, tcp://, http://, or https:// URL. The zero value defers to the DOCKER_HOST environment variable, falling back to the platform default socket.

type HostIP

type HostIP string

HostIP is the host interface address a port binding listens on.

type ImageRef

type ImageRef string

ImageRef names an image, like "postgres:17-alpine".

type LabelKey

type LabelKey string

LabelKey is a label's key.

type LabelValue

type LabelValue string

LabelValue is a label's value.

type Labels

type Labels map[string]string

Labels is a label map applied to containers and volumes.

type LogOptions

type LogOptions struct {
	// Since limits logs to entries after this time; zero means from the
	// container's start.
	Since time.Time
	// FollowEnabled streams logs until the container stops instead of
	// returning the current backlog.
	FollowEnabled bool
}

LogOptions adjusts container log retrieval.

type Mount

type Mount struct {
	Kind            MountKind
	Source          MountSource
	Target          MountTarget
	ReadOnlyEnabled bool
}

Mount attaches a volume or host path into a container.

type MountDetails

type MountDetails struct {
	Kind   MountKind
	Volume VolumeName
	Source MountSource
	Target MountTarget
}

MountDetails describes one mount attached to an inspected container.

type MountKind

type MountKind string

MountKind is the mount flavor: MountVolume or MountBind.

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

Sanctioned mount kinds.

type MountSource

type MountSource string

MountSource is the volume name or absolute host path being mounted.

type MountTarget

type MountTarget string

MountTarget is the absolute path inside the container.

type NetworkMode

type NetworkMode string

NetworkMode selects the container network ("", "host", or "container:<id>" to share another container's network namespace).

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option adjusts client construction. Options are concrete types — HostAddress, APIVersion, Connection, Environment — applied in order.

type Platform

type Platform string

Platform is an OS/architecture selector like "linux/arm64"; empty defers to the daemon default.

type Port

type Port uint16

Port is a TCP port number.

type PortBinding

type PortBinding struct {
	HostAddress HostIP
	Host        Port
	Container   Port
}

PortBinding publishes one container TCP port on the host.

type PullOptions

type PullOptions struct {
	Progress StreamHandler
	Platform Platform
	Auth     RegistryAuth
}

PullOptions adjusts an image pull.

type RegistryAuth

type RegistryAuth string

RegistryAuth is a pre-encoded X-Registry-Auth header value (the Engine's base64url auth document). Empty means anonymous.

type RemovalOptions

type RemovalOptions struct {
	ForceEnabled         bool
	RemoveVolumesEnabled bool
}

RemovalOptions adjusts container removal.

type SecurityOption added in v0.4.0

type SecurityOption string

SecurityOption is one HostConfig security option, like "no-new-privileges".

type StopSeconds

type StopSeconds int

StopSeconds is the grace period the daemon allows a container before killing it on stop.

type StreamErrorDetail

type StreamErrorDetail struct {
	Message string `json:"message"`
}

StreamErrorDetail is the structured error a failed stream operation reports.

type StreamHandler

type StreamHandler func(message StreamMessage) error

StreamHandler observes each stream message in order. Returning an error stops the scan and surfaces that error.

type StreamMessage

type StreamMessage struct {
	Status  string            `json:"status"`
	Failure string            `json:"error"`
	Detail  StreamErrorDetail `json:"errorDetail"`
}

StreamMessage is one progress document from an Engine JSON stream.

type Tmpfs added in v0.4.0

type Tmpfs map[MountTarget]TmpfsOptions

Tmpfs maps container paths to tmpfs mounts by their options.

type TmpfsOptions added in v0.4.0

type TmpfsOptions string

TmpfsOptions is the mount-option string for one tmpfs target, like "rw,nosuid,noexec,mode=1777"; empty applies the daemon defaults.

type VolumeCreatedAt

type VolumeCreatedAt string

VolumeCreatedAt is the Engine's volume creation timestamp, as reported (RFC 3339 text).

type VolumeDetails

type VolumeDetails struct {
	Labels     Labels
	Name       VolumeName
	Mountpoint MountSource
	CreatedAt  VolumeCreatedAt
}

VolumeDetails is one volume's state.

type VolumeName

type VolumeName string

VolumeName identifies a named Docker volume.

type VolumeQuery

type VolumeQuery struct {
	Labels Labels
}

VolumeQuery filters volume listings by label terms; zero value lists all.

type VolumeRemoval

type VolumeRemoval struct {
	// ForceEnabled removes the volume even when the daemon believes it is
	// in use.
	ForceEnabled bool
}

VolumeRemoval adjusts volume removal.

type VolumeSpec

type VolumeSpec struct {
	Labels Labels
	Name   VolumeName
}

VolumeSpec describes a volume to create.

type WaitCondition

type WaitCondition string

WaitCondition names the container state transition WaitContainer blocks on.

const (
	WaitNotRunning WaitCondition = "not-running"
	WaitNextExit   WaitCondition = "next-exit"
	WaitRemoved    WaitCondition = "removed"
)

Wait conditions the Engine accepts.

type WorkDir

type WorkDir string

WorkDir is the container working directory.

Jump to

Keyboard shortcuts

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