containers

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: BSD-3-Clause Imports: 13 Imported by: ? 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.

README

containers

License GoDoc Discord

Runs containers from Go, over docker or containerd.

Layout

Package What it is
containers The client: images, containers, run, logs. What callers use.
core The Backend and Image interfaces, the config types, the backend registry.
backends/docker Docker backend. Builds natively.
backends/containerd containerd backend, Linux only. Builds by running BuildKit.
backends/conformance The behaviour both backends are held to.
gc Periodic image cleanup.

New() picks a backend at construction: docker if its daemon answers, otherwise containerd. Callers do not choose.

Usage

client, err := containers.New()
if err != nil {
    return err
}

image, err := client.Image(ctx, "alpine:latest")
if err != nil {
    return err
}

container, err := image.Instantiate(ctx,
    containers.Command([]string{"echo", "Hello World!"}),
    containers.Volume("/host/path", "/container/path"),
    containers.Variable("KEY", "value"),
)
if err != nil {
    return err
}

logs, err := container.Run(ctx)
// logs are readable even when err wraps ErrorExitCode: that is where a failed
// build's compiler output lives.
if logs != nil {
    io.Copy(os.Stdout, logs.Combined())
}

Run starts the container, waits for it, collects its output and removes it. A non-zero exit comes back as an error wrapping ErrorExitCode; a runtime that broke comes back as one of the other sentinels in errors.go. Both match with errors.Is.

Building an image from a Dockerfile

The Dockerfile and anything it needs go in a tarball, which becomes an ImageOption:

tar cvf image.tar -C <dir>/ .
client.Image(ctx, "org/name:version", containers.Build(tarball))

Image names must be lowercase. Both backends build: docker hands the context to its daemon, and containerd runs BuildKit as a one-shot container and imports what it produces, so nothing extra has to be installed or kept running. Check Capabilities().SupportsBuild before building anyway — it is what routes a build, and a backend added later may not.

Backend differences

Docker and containerd are interchangeable for running containers: same exit codes, same log framing, same environment, working directory and bind mounts, all enforced by the conformance suite. They still differ where the runtimes do:

  • Networking. Docker bridges by default. containerd runs without CNI, so it shares the host's network instead; none isolates, and a bridged mode is refused rather than silently downgraded. containerd containers use the host's resolver, so custom DNS servers are refused there.

  • Port mappings and named volumes. Docker only. containerd refuses both.

  • What a build needs. containerd's BuildKit container needs the host's cgroup hierarchy either way, because BuildKit runs a runc of its own per step. Beyond that it differs by mode, and the difference is not cosmetic — asking for the wrong one stops buildkitd from starting at all:

    rootless containerd rootful containerd
    buildkitd flags no-process-sandbox, rootless worker, native snapshotter none: its defaults are right
    privileges CAP_SYS_ADMIN + /dev/fuse privileged

    Privileged is asked for only where the runtime is already real root, so it relaxes the container and grants nothing the process did not have. Under a rootless runtime the user namespace is the boundary and the narrow set stays inside it. Docker builds need none of this — its daemon builds natively.

  • Resource limits. Not available on rootless containerd, which cannot create the cgroup that would enforce them; asking for them there is an error rather than a limit that quietly does nothing.

  • The image's USER. Not applied by containerd — resolving a user name needs a mount of the image's snapshot that rootless is not permitted to make, so containers run as root. Its ENV, WORKDIR and ENTRYPOINT are applied.

  • What Clean considers an image's age. Docker reports only the image's build date, so the sweep measures how old the image is; containerd records when the image arrived locally, so it measures how long it has been here. Same call, different cutoff.

Tests

go test ./pkg/containers/...   # unit tests: no daemon, no network
make test-docker               # needs a docker daemon
make test-containerd           # needs containerd, or containerd+rootlesskit

Both integration suites run backends/conformance, which is what keeps the two backends honest. Anything a backend must do belongs there rather than in a per-backend test.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrorImageOptions         = errors.New("image options failed")
	ErrorImageBuild           = errors.New("building image failed")
	ErrorImagePull            = errors.New("pulling image failed")
	ErrorClientPull           = errors.New("client pull failed")
	ErrorImageBuildDockerFile = errors.New("building Dockerfile failed")
	ErrorContainerOptions     = errors.New("container options failed")
	ErrorContainerCreate      = errors.New("creating container failed")
	ErrorContainerStart       = errors.New("start container failed")
	ErrorContainerWait        = errors.New("container wait failed")
	ErrorContainerInspect     = errors.New("inspecting container failed")
	ErrorExitCode             = errors.New("exit-code")
	ErrorContainerLogs        = errors.New("getting container logs failed")
	ErrBackendNotAvailable    = errors.New("backend not available on this platform")
)
View Source
var (
	ForceRebuild = false
)

Functions

func AvailableBackends added in v1.1.10

func AvailableBackends() []core.BackendType

AvailableBackends returns all registered backends

func NewBackend added in v1.1.10

func NewBackend(config core.BackendConfig) (core.Backend, error)

NewBackend creates a backend instance using the registered factory from core

Types

type BuildStatus

type BuildStatus struct {
	Stream      string `json:"stream"`
	Error       string `json:"error"`
	ErrorDetail struct {
		Message string `json:"message"`
	} `json:"errorDetail"`
}

type Client

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

Client wraps the methods of the docker Client. It now uses a Backend internally for container operations.

func New

func New(options ...Option) (dockerClient *Client, err error)

New creates a new dockerClient with default Options. Backend is initialized immediately (Docker first, fallback to containerd).

func (*Client) Clean

func (c *Client) Clean(ctx context.Context, age time.Duration, reference string) error

Clean removes images older than age, optionally scoped to one reference.

func (*Client) Close added in v1.1.10

func (c *Client) Close() error

Close is a no-op for backward compatibility. The backend handles its own lifecycle and doesn't need explicit closing.

func (*Client) Image

func (c *Client) Image(ctx context.Context, name string, options ...ImageOption) (image *DockerImage, err error)

Image initializes the given image. It tries to pull from the registry first to get the latest; if pull fails and the image exists locally, that image is used. If the Build() Option is provided then the given DockerFile tarball is built and returned.

type Container

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

Container wraps the methods of the docker container. It now uses a Backend internally for container operations.

func (*Container) Cleanup

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

Cleanup removes the container from the docker host client.

func (*Container) Run

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

Run starts the container and waits for the container to exit before returning the container logs. Logs are returned even when the container exits with a non-zero status so callers can inspect build output (e.g. compiler errors); that status comes back as an error wrapping ErrorExitCode.

func (*Container) Wait

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

Wait calls the ContainerWait method for the container, and returns once a response has been received. If there is an error response then wait will return the error

type ContainerOption

type ContainerOption func(*Container) error

ContainerOption is a function to set configuration to the Container object.

func Command

func Command(cmd []string) ContainerOption

Command sets the commands to be run by the container after being built.

func RestrictedEgress added in v1.2.0

func RestrictedEgress() ContainerOption

RestrictedEgress makes the backend confine the container's network egress to the public internet — blocking node-local services, the cloud metadata endpoint, and private/link-local ranges. Set for any workload the node did not author — a build running a repository's own build.sh, a tenant's container. Enforcement is fail-closed: if the firewall cannot be installed the container is not started.

func Variable

func Variable(key, value string) ContainerOption

Variable sets an environment variable in the container.

func Variables

func Variables(vars map[string]string) ContainerOption

Variables sets multiple environment variables in the container.

func Volume

func Volume(sourcePath, containerPath string) ContainerOption

Volume sets local directories to be volumed in the container.

func WorkDir

func WorkDir(workDir string) ContainerOption

WorkDir sets the working directory of the container, where calls will be made.

type DockerImage added in v1.1.10

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

DockerImage wraps the methods of the docker image. It now uses a Backend internally for image operations.

func (*DockerImage) Exists added in v1.1.10

func (i *DockerImage) Exists(ctx context.Context) bool

Exists checks if the image exists locally without pulling

func (*DockerImage) Instantiate added in v1.1.10

func (i *DockerImage) Instantiate(ctx context.Context, options ...ContainerOption) (*Container, error)

Instantiate sets given options and creates the container from the docker image.

func (*DockerImage) Name added in v1.1.10

func (i *DockerImage) Name() string

Name returns the name of the image

func (*DockerImage) Pull added in v1.1.10

func (i *DockerImage) Pull(ctx context.Context, statusChan chan<- PullStatus) (*DockerImage, error)

Pull retrieves latest changes to the image from docker hub.

type ImageOption

type ImageOption func(*DockerImage) error

ImageOption is a function to set configuration to the Image object.

func Build

func Build(tarball io.Reader) ImageOption

Build returns an ImageOption to build a tarball of a Dockerfile

func Dockerfile

func Dockerfile(dockerfile string) ImageOption

func Output

func Output(output io.Writer) ImageOption

func RestrictedBuildEgress added in v1.2.0

func RestrictedBuildEgress() ImageOption

RestrictedBuildEgress confines a Dockerfile build's egress, the way RestrictedEgress does for a container it is the image of.

type MuxedReadCloser

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

MuxedReadCloser wraps the Read/Close methods for muxed logs.

func (*MuxedReadCloser) Close

func (mx *MuxedReadCloser) Close() error

func (*MuxedReadCloser) Combined

func (mx *MuxedReadCloser) Combined() io.ReadCloser

Combined returns the Stderr, and Stdout combined container logs.

type Option

type Option func(*Client) error

func Verbose

func Verbose() Option

do not show progress output

type PullStatus

type PullStatus struct {
	Status         string `json:"status"`
	ProgressDetail struct {
		Current int `json:"current"`
		Total   int `json:"total"`
	} `json:"progressDetail"`
	Id          string `json:"id"`
	Error       string `json:"error"`
	ErrorDetail struct {
		Message string `json:"message"`
	} `json:"errorDetail"`
}

Directories

Path Synopsis
backends
conformance
Package conformance holds the behaviour every container backend must exhibit.
Package conformance holds the behaviour every container backend must exhibit.
containerd
Package containerd provides a containerd backend implementation for container operations.
Package containerd provides a containerd backend implementation for container operations.
docker
Package docker provides a Docker backend implementation for container operations.
Package docker provides a Docker backend implementation for container operations.
Package core provides core interfaces and types for container backends This package is separate from the main containers package to avoid import cycles
Package core provides core interfaces and types for container backends This package is separate from the main containers package to avoid import cycles

Jump to

Keyboard shortcuts

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