docker

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: MIT Imports: 32 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package docker talks to a container engine through the Docker Engine API. It works with any engine that serves that API on the active Docker context: Docker Desktop, OrbStack, Colima, Rancher Desktop (dockerd), Podman or a plain Linux daemon, rootful or rootless, on a socket, over TCP with or without TLS, or over SSH.

Index

Constants

View Source
const (
	JobRecreate = "recreate"
	JobRebuild  = "rebuild"
	JobPull     = "pull"
)

Service job kinds, with optional image builds or pulls.

View Source
const (
	Connecting  = "connecting"
	Ready       = "ready"
	Unavailable = "unavailable"
)

Engine states.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Status  int
	Message string
}

APIError is an error answer from the engine.

func (*APIError) Error

func (e *APIError) Error() string

type Client

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

Client is a minimal Engine API client. Paths are unversioned, so the engine answers with its own current API version.

func NewClient

func NewClient(ep Endpoint, env []string) *Client

NewClient returns a client for ep. env is the environment of helper processes, such as ssh for an ssh:// endpoint.

func (*Client) Close

func (c *Client) Close()

Close drops idle connections.

func (*Client) ExecAttach

func (c *Client) ExecAttach(ctx context.Context, execID string) (net.Conn, io.Reader, error)

ExecAttach starts an exec instance and returns the raw, bidirectional stream of its TTY. Closing the connection does not end the command; the engine keeps it running until it exits.

func (*Client) ExecCreate

func (c *Client) ExecCreate(ctx context.Context, id string, cmd []string, env []string) (string, error)

ExecCreate prepares an interactive command with a TTY in a running container.

func (*Client) ExecDetached

func (c *Client) ExecDetached(ctx context.Context, id string, cmd []string) error

ExecDetached runs a command in a running container without waiting for it or reading its output.

func (*Client) ExecResize

func (c *Client) ExecResize(ctx context.Context, execID string, cols, rows uint16) error

ExecResize changes the TTY size of an exec instance.

func (*Client) ExecRunning

func (c *Client) ExecRunning(ctx context.Context, execID string) (bool, error)

ExecRunning reports whether an exec instance's command is still running.

func (*Client) Inspect

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

Inspect returns the full description of one container.

func (*Client) Logs

func (c *Client) Logs(ctx context.Context, id string, tty bool, tail string, since time.Time, follow, stamped bool) (io.ReadCloser, error)

Logs streams a container's output. tail limits the backlog ("all" or a number); since, when set, starts after that time; stamped prefixes each line with its RFC 3339 time and a space. Output of containers without a TTY is demultiplexed into one stream.

func (*Client) Ping

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

Ping checks that the engine answers and returns its version.

func (*Client) Restart

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

func (*Client) Start

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

Start, Stop and Restart change a container's state.

func (*Client) Stop

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

type Container

type Container struct {
	ID           string     `json:"id"`
	Name         string     `json:"name"`
	Image        string     `json:"image"`
	Project      string     `json:"project,omitempty"`
	LocalProject string     `json:"localProject,omitempty"`
	Buildable    bool       `json:"buildable,omitempty"`
	Service      string     `json:"service,omitempty"`
	OneOff       bool       `json:"oneOff,omitempty"`
	WorkingDir   string     `json:"workingDir,omitempty"`
	State        string     `json:"state"` // created, running, paused, restarting, removing, exited, dead
	Health       string     `json:"health,omitempty"`
	Status       string     `json:"status"` // the engine's own summary, e.g. "Up 3 hours (healthy)"
	StartedAt    *time.Time `json:"startedAt,omitempty"`
	FinishedAt   *time.Time `json:"finishedAt,omitempty"`
	ExitCode     *int       `json:"exitCode,omitempty"`
	OOMKilled    bool       `json:"oomKilled,omitempty"`
	// Failed marks an exited container that failed rather than finished or
	// was stopped on request (including a signal that stop sent while this
	// monitor watched), and a dead one.
	Failed     bool      `json:"failed,omitempty"`
	Restarts   int       `json:"restarts,omitempty"`
	Ports      []Port    `json:"ports,omitempty"`
	CPU        float64   `json:"cpu"`
	Mem        int64     `json:"mem"`
	MemLimit   int64     `json:"memLimit,omitempty"`
	CPUHistory []float64 `json:"cpuHistory,omitempty"`
	MemHistory []int64   `json:"memHistory,omitempty"`
	TTY        bool      `json:"-"`
	// Server is the configured server this container belongs to; the HTTP
	// layer fills it in.
	Server string `json:"server,omitempty"`
	// SharedWith are the other servers that use this container.
	SharedWith []string `json:"sharedWith,omitempty"`
	// IssueFor are the servers this container needs attention for; the
	// HTTP layer decides.
	IssueFor []string `json:"issueFor,omitempty"`
	Job      *JobView `json:"job,omitempty"`
	// contains filtered or unexported fields
}

Container is the JSON view of one container.

func (*Container) Compose

func (c *Container) Compose() bool

Compose reports whether the container belongs to a compose service, which can be recreated. Buildable identifies services with known image builds.

func (*Container) Servers

func (c *Container) Servers() []string

Servers are the servers that use the container: its owner first.

type Endpoint

type Endpoint struct {
	// Network is "unix", "tcp" or "ssh"; Address is the socket path, the
	// host:port, or for SSH the host name.
	Network string `json:"-"`
	Address string `json:"-"`
	// Host is the endpoint as written in the context, e.g. unix:///var/run/docker.sock.
	Host string `json:"host"`
	// Context is the Docker context it came from, "" for DOCKER_HOST or a guess.
	Context string `json:"context,omitempty"`
	// Target is where a socket symlink finally points, which names the
	// engine behind /var/run/docker.sock.
	Target string `json:"-"`

	// TLS settings for tcp://: certificates in CertDir (ca.pem, cert.pem,
	// key.pem, each optional), and whether the server certificate is checked.
	TLS       bool   `json:"-"`
	TLSVerify bool   `json:"-"`
	CertDir   string `json:"-"`

	// SSH settings for ssh://user@host:port.
	SSHUser string `json:"-"`
	SSHPort string `json:"-"`
	// contains filtered or unexported fields
}

Endpoint is where the engine API is served.

func Resolve

func Resolve(getenv func(string) string) (Endpoint, error)

Resolve finds the active engine endpoint the way the docker CLI does: DOCKER_HOST, then DOCKER_CONTEXT, then the current context in the CLI config, then the first engine socket found. getenv reads the user's environment.

type Host

type Host interface {
	Environ() []string
	LookPath(name string) string
}

Host gives the monitor what it needs from the rest of the daemon: the user's login-shell environment and executable lookup on its PATH.

type Inspect

type Inspect struct {
	ID      string    `json:"Id"`
	ImageID string    `json:"Image"`
	Name    string    `json:"Name"`
	Created time.Time `json:"Created"`
	Path    string    `json:"Path"`
	Args    []string  `json:"Args"`
	State   struct {
		Status     string    `json:"Status"`
		Running    bool      `json:"Running"`
		Restarting bool      `json:"Restarting"`
		OOMKilled  bool      `json:"OOMKilled"`
		ExitCode   int       `json:"ExitCode"`
		Error      string    `json:"Error"`
		StartedAt  time.Time `json:"StartedAt"`
		FinishedAt time.Time `json:"FinishedAt"`
		Health     *struct {
			Status        string `json:"Status"`
			FailingStreak int    `json:"FailingStreak"`
			Log           []struct {
				Start    time.Time `json:"Start"`
				ExitCode int       `json:"ExitCode"`
				Output   string    `json:"Output"`
			} `json:"Log"`
		} `json:"Health"`
	} `json:"State"`
	RestartCount int `json:"RestartCount"`
	Config       struct {
		Image      string            `json:"Image"`
		Env        []string          `json:"Env"`
		Cmd        []string          `json:"Cmd"`
		Entrypoint []string          `json:"Entrypoint"`
		WorkingDir string            `json:"WorkingDir"`
		Labels     map[string]string `json:"Labels"`
		Tty        bool              `json:"Tty"`
	} `json:"Config"`
	HostConfig struct {
		RestartPolicy struct {
			Name string `json:"Name"`
		} `json:"RestartPolicy"`
	} `json:"HostConfig"`
	Mounts []struct {
		Type        string `json:"Type"`
		Name        string `json:"Name"`
		Source      string `json:"Source"`
		Destination string `json:"Destination"`
		RW          bool   `json:"RW"`
	} `json:"Mounts"`
	NetworkSettings struct {
		Ports    map[string][]struct{ HostIP, HostPort string } `json:"Ports"`
		Networks map[string]struct {
			IPAddress string   `json:"IPAddress"`
			Aliases   []string `json:"Aliases"`
		} `json:"Networks"`
	} `json:"NetworkSettings"`
}

Inspect is the part of GET /containers/{id}/json that is shown or used.

type Job

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

Job runs one compose operation and retains its terminal output.

func (*Job) Wait

func (j *Job) Wait(ctx context.Context) (JobResult, error)

Wait returns a bounded output tail for this exact job, even if a later job replaces it in the dashboard before the client receives the response.

type JobResult

type JobResult struct {
	JobView
	Output string `json:"output"`
}

JobResult includes a bounded plain-text tail of a completed compose job.

type JobView

type JobView struct {
	Kind      string     `json:"kind"`
	Running   bool       `json:"running"`
	Error     string     `json:"error,omitempty"`
	StartedAt time.Time  `json:"startedAt"`
	EndedAt   *time.Time `json:"endedAt,omitempty"`
}

JobView is the JSON view of the last compose job run for a container.

type Monitor

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

Monitor keeps a live picture of the engine: whether it is reachable, its containers, and their resource usage. Changes are pushed by the engine's event stream; a periodic resync covers anything missed.

func NewMonitor

func NewMonitor(host Host, interval time.Duration, custom func() string) *Monitor

NewMonitor returns a monitor; call Run to connect. custom returns the configured engine start command, "" for automatic detection.

func (*Monitor) Client

func (m *Monitor) Client() (*Client, error)

Client returns the connected client, or an error while the engine is unavailable.

func (*Monitor) DismissJob

func (m *Monitor) DismissJob(name string)

DismissJob forgets a finished job.

func (*Monitor) Find

func (m *Monitor) Find(ref string) (Container, bool)

Find returns a container by name or ID.

func (*Monitor) JobLog

func (m *Monitor) JobLog(name string) (*supervisor.LogBuffer, bool)

JobLog returns the output of the last job for a container.

func (*Monitor) Kick

func (m *Monitor) Kick()

Kick asks the monitor to reconnect or resync now.

func (*Monitor) ProjectAction

func (m *Monitor) ProjectAction(ref, action string) (*Job, error)

ProjectAction starts, stops or removes an existing compose project's containers. Removal never asks compose to remove volumes.

func (*Monitor) Publishing

func (m *Monitor) Publishing(port int) []Container

Publishing lists the running containers of a local engine that publish TCP port on the host.

func (*Monitor) RecordStop

func (m *Monitor) RecordStop(id string)

RecordStop remembers an explicit request even if the events stream misses it.

func (*Monitor) Recreate

func (m *Monitor) Recreate(name string, rebuild, pull bool) (*Job, error)

Recreate runs a compose service job, optionally building or pulling its image.

func (*Monitor) Run

func (m *Monitor) Run(ctx context.Context)

Run connects to the engine and follows it until ctx ends.

func (*Monitor) RunningJobs

func (m *Monitor) RunningJobs() []string

RunningJobs names the containers whose compose job is still running.

func (*Monitor) Snapshot

func (m *Monitor) Snapshot() State

Snapshot returns the current state with containers sorted by project, service and name.

func (*Monitor) StartEngine

func (m *Monitor) StartEngine() error

StartEngine launches the container engine behind the active context, or the configured start command. It returns once the launch has begun; the monitor reports when the engine answers.

func (*Monitor) Subscribe

func (m *Monitor) Subscribe() chan struct{}

Subscribe returns a channel signalled on every change.

func (*Monitor) Unsubscribe

func (m *Monitor) Unsubscribe(ch chan struct{})

Unsubscribe stops signals to ch.

func (*Monitor) UseStateDir

func (m *Monitor) UseStateDir(dir string)

UseStateDir restores deliberate stops before the monitor starts following events. A file that cannot be read is logged and replaced by the next stop; the monitor then starts without remembered stops.

type Port

type Port struct {
	Private int    `json:"private"`
	Public  int    `json:"public"`
	Proto   string `json:"proto"`
	IP      string `json:"ip,omitempty"`
}

Port is a published container port.

type SSHError

type SSHError struct{ Message string }

SSHError is why ssh ended a connection, from its own output.

func (*SSHError) Error

func (e *SSHError) Error() string

Error names ssh once: its own messages often start with "ssh: ".

type State

type State struct {
	Status     string      `json:"status"`
	Error      string      `json:"error,omitempty"`
	Host       string      `json:"host,omitempty"`
	Context    string      `json:"context,omitempty"`
	Engine     string      `json:"engine"`
	Version    string      `json:"version,omitempty"`
	Starting   bool        `json:"starting,omitempty"`
	Containers []Container `json:"containers"`
}

State is the JSON view of the engine connection and its containers.

Jump to

Keyboard shortcuts

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