dockermanage

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 23 Imported by: 1 module, 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.

README

dockermanage

CI Go Reference

Start, wait for, and clean up Docker containers from Go.

dockermanage is a thin, opinionated layer over the official Docker client. It does not depend on the testing package, so you can use it in tools, local development setups, and services, as well as in tests.

  • Sensible defaults, so the common case takes a few lines.
  • Clear errors when a container fails to start.
  • Cleanup that touches only the containers it started.
  • Built-in support for PostgreSQL.

Install

go get github.com/pressly/dockermanage

Requires Go 1.26 or newer.

Use

m, err := dockermanage.New()
if err != nil {
	return err
}
defer m.Close()

c, err := m.Start(ctx, "redis:8-alpine", dockermanage.WithPort(6379))
if err != nil {
	return err
}
defer c.Remove(context.WithoutCancel(ctx))

addr, err := c.Addr(6379) // for example, "127.0.0.1:54321"

Docs

License

MIT. See LICENSE.

Documentation

Overview

Package dockermanage starts, waits for, and cleans up Docker containers from Go. It is a thin, opinionated layer over the official Docker client (github.com/moby/moby/client).

It does not depend on the testing package, so you can use it in tools, local development setups, and services, as well as in tests.

Create a Manager with New, then call Manager.Start with an image and functional StartOption values such as WithPort and WithEnv. Start returns a Container handle. Use Container.WaitReady with a custom ReadinessFunc to block until the service inside the container accepts connections, and Container.Addr to get an address to connect to.

Every container gets the ManagedLabelKey label and a label that identifies the Manager that started it. Manager.ListAll, Manager.StopAll, and Manager.RemoveAll only affect containers that the same Manager started, so two programs that use this package do not remove each other's containers.

Database-specific sub-packages (for example, postgres) provide defaults for common databases.

Index

Constants

View Source
const (
	// DefaultHostIP is the default host IP that container ports are bound to.
	DefaultHostIP = "127.0.0.1"

	// ManagedLabelKey marks containers created by this package. The value indicates the container
	// type (for example, "postgres"). Presence of the key means the container is managed.
	ManagedLabelKey = dockerops.ManagedLabelKey
)

Variables

This section is empty.

Functions

func Healthy added in v0.2.0

func Healthy(ctx context.Context, c *Container) error

Healthy is a ReadinessFunc that waits until Docker reports the container as healthy. Use it with images that define a HEALTHCHECK. If the container has no health check, Container.WaitReady returns an error at once.

Types

type Container

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

Container is a container that a Manager started.

func (*Container) Addr

func (c *Container) Addr(containerPort int) (string, error)

Addr returns a "host:port" address to connect to a published TCP container port, for example "127.0.0.1:54321". The host is the bind address from WithHostIP. If the bind address is unspecified (0.0.0.0 or ::), the host is the remote Docker host name, or a loopback address for a local Docker daemon.

func (*Container) Exec

func (c *Container) Exec(ctx context.Context, cmd []string, options ...ExecOption) (*ExecResult, error)

Exec runs a command with its arguments inside the running container. Use WithStdout and WithStderr to read its output, and WithEnv to set environment variables. A non-zero exit code is not an error; check ExecResult.ExitCode.

If ctx is done before the command exits, Exec returns the context error. Docker cannot stop an exec process, so the command can continue to run inside the container.

func (*Container) ID

func (c *Container) ID() string

ID returns the Docker container ID.

func (*Container) Image

func (c *Container) Image() string

Image returns the image the container was started from.

func (*Container) Labels

func (c *Container) Labels() map[string]string

Labels returns a copy of the labels that this package set on the container, including the labels from WithLabel. It does not include labels from the image.

func (*Container) Remove

func (c *Container) Remove(ctx context.Context) error

Remove force removes the container and its anonymous volumes. It returns nil if the container no longer exists, so it is safe to call more than once.

func (*Container) Stop

func (c *Container) Stop(ctx context.Context) error

Stop asks the container to exit, and kills it if it does not exit within the stop timeout. See WithStopTimeout.

func (*Container) WaitReady

func (c *Container) WaitReady(ctx context.Context, readiness ReadinessFunc, options ...WaitOption) error

WaitReady calls readiness until it returns nil or ctx is done. If ctx has no deadline, WaitReady gives up after 30s. For an image that defines a HEALTHCHECK, use Healthy as readiness.

If the container exits while WaitReady waits, WaitReady cancels the running check and returns at once. The error has the exit code and the last lines of the container log. A timeout error also has the last lines of the log.

type EnvOption

type EnvOption interface {
	StartOption
	ExecOption
}

EnvOption is an option for both Manager.Start and Container.Exec.

func WithEnv

func WithEnv(key, value string) EnvOption

WithEnv adds one environment variable to a container (Manager.Start) or to a command (Container.Exec). Use it once for each variable.

type ExecOption

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

ExecOption configures Container.Exec. WithEnv is also an ExecOption.

func WithStderr

func WithStderr(writer io.Writer) ExecOption

WithStderr sets where Container.Exec writes the standard error of the command. By default, it is discarded.

func WithStdout

func WithStdout(writer io.Writer) ExecOption

WithStdout sets where Container.Exec writes the standard output of the command. By default, it is discarded.

type ExecResult

type ExecResult struct {
	ExitCode int
}

ExecResult holds the outcome of a command run with Container.Exec.

type Manager

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

Manager starts Docker containers and tracks the containers it started. It is safe for concurrent use.

func New

func New(options ...ManagerOption) (*Manager, error)

New creates a new Manager.

By default, it uses a Docker client configured from the environment (DOCKER_HOST and related variables). Use WithClient to provide your own client. For a remote Docker daemon, see WithHostIP.

func (*Manager) Close

func (m *Manager) Close() error

Close closes the Docker client if the Manager created it. It does not stop or remove containers; call Manager.RemoveAll first for that. A client passed with WithClient is not closed.

func (*Manager) ListAll

func (m *Manager) ListAll(ctx context.Context) ([]string, error)

ListAll returns the IDs of all containers that this Manager started, including stopped ones.

func (*Manager) RemoveAll

func (m *Manager) RemoveAll(ctx context.Context) error

RemoveAll removes all containers that this Manager started, with their anonymous volumes. Running containers are force removed.

func (*Manager) Start

func (m *Manager) Start(ctx context.Context, image string, options ...StartOption) (_ *Container, retErr error)

Start pulls the image if it is not present, then creates and starts a container. If Start fails after it creates the container, it removes the container.

Start pulls without registry credentials. For a private image, pull it first (for example, with docker pull).

func (*Manager) StopAll

func (m *Manager) StopAll(ctx context.Context) error

StopAll stops all containers that this Manager started.

type ManagerOption

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

ManagerOption configures New.

func WithClient

func WithClient(dockerClient *client.Client) ManagerOption

WithClient sets the Docker client, for example to set a custom transport or API version. The caller owns the client: Manager.Close does not close it.

For a remote Docker daemon, see WithHostIP.

func WithLogger

func WithLogger(logger *slog.Logger) ManagerOption

WithLogger sets the logger. The Manager logs at debug level. By default, it does not log.

type ReadinessFunc

type ReadinessFunc func(ctx context.Context, container *Container) error

ReadinessFunc reports whether a container is ready. Return a non-nil error to check again.

type StartOption

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

StartOption configures Manager.Start. Options do not change after they are created, so you can share them between goroutines. WithEnv is also a StartOption.

func WithAutoRemove

func WithAutoRemove() StartOption

WithAutoRemove makes Docker remove the container when it stops.

func WithCmd

func WithCmd(cmd ...string) StartOption

WithCmd sets the command and arguments that the container runs, in place of the image default (CMD).

func WithEntrypoint

func WithEntrypoint(entrypoint ...string) StartOption

WithEntrypoint sets the program that the container runs, in place of the image default (ENTRYPOINT), like docker run --entrypoint. Docker does not pass the image default CMD to a replaced entrypoint; use WithCmd to pass arguments.

func WithHostIP

func WithHostIP(hostIP string) StartOption

WithHostIP sets the host IP address that container ports are bound to. Defaults to DefaultHostIP.

For a remote Docker daemon (DOCKER_HOST=tcp://host:port, for example Docker-in-Docker in CI), ports bound to 127.0.0.1 are not reachable. Use "0.0.0.0"; Container.Addr then returns the daemon host name. For a client with a custom connection, such as SSH through WithClient, bind a specific IP address that you can reach; Addr returns that address.

func WithLabel

func WithLabel(key, value string) StartOption

WithLabel sets one container label. Use it once for each label.

func WithName

func WithName(name string) StartOption

WithName sets the container name.

func WithPort

func WithPort(containerPort int) StartOption

WithPort publishes a TCP container port on a host port that Docker picks. Use Container.Addr to get the address. Use it once for each port to publish.

func WithPortBinding

func WithPortBinding(containerPort, hostPort int) StartOption

WithPortBinding publishes a TCP container port on a fixed host port.

func WithPullProgress

func WithPullProgress(writer io.Writer) StartOption

WithPullProgress sets where image pull status is written, as one text line for each status message (for example, "Pull complete"). By default, it is discarded.

func WithStopTimeout

func WithStopTimeout(timeout time.Duration) StartOption

WithStopTimeout sets how long Docker waits for the container to exit after a stop request before it kills the container. It applies to Container.Stop, Manager.StopAll, and docker stop. Docker uses whole seconds, so the value is rounded up. Zero kills the container at once. The Docker default is 10s.

type WaitOption

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

WaitOption configures Container.WaitReady.

func WithPollInterval

func WithPollInterval(interval time.Duration) WaitOption

WithPollInterval sets the time between readiness checks in Container.WaitReady. Defaults to 500ms.

Directories

Path Synopsis
cmd
dockermanage module
internal
dockerops
Package dockerops holds the label keys and Docker operations that the dockermanage package and the dockermanage command share.
Package dockerops holds the label keys and Docker operations that the dockermanage package and the dockermanage command share.
dockertesting
Package dockertesting skips tests that need Docker when Docker is not reachable.
Package dockertesting skips tests that need Docker when Docker is not reachable.
Package postgres starts PostgreSQL containers with dockermanage.
Package postgres starts PostgreSQL containers with dockermanage.

Jump to

Keyboard shortcuts

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