Help us shape the future of Go! Take the 2026 Go Developer Survey

kit

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 44 Imported by: 0

Documentation

Overview

Package kit defines Compose projects and runs them through the Docker Compose SDK.

Package kit provides the container config for the wrapped client. it is built to be created in a declarative way.

Index

Constants

View Source
const (
	SELinuxShared  = "z"
	SELinuxPrivate = "Z"
)

SELinux relabel modes for a bind mount.

Variables

This section is empty.

Functions

This section is empty.

Types

type AddOpts

type AddOpts struct {
	Chown      string
	Chmod      string
	Checksum   string
	KeepGitDir bool
	Link       bool
	Exclude    []string
}

AddOpts are optional flags on an ADD instruction.

type Attach

type Attach struct {
	DetachKeys string
	Index      *int
	NoStdin    bool
	NoSigProxy bool // --sig-proxy=false; Compose defaults to true

	Writer   io.Writer
	Stdin    io.Reader
	Profiles []string
	Service  string // required
}

Attach is the options for the compose attach command. Service is required.

type BindOptions

type BindOptions struct {
	Propagation            types.MountPropagation
	SELinux                string // z or Z
	NonRecursive           bool
	CreateHostPath         *bool
	ReadOnlyNonRecursive   bool
	ReadOnlyForceRecursive bool
}

BindOptions are options for a bind mount.

type BridgeConvert

type BridgeConvert struct {
	Output          string // default out
	Templates       string
	Transformations []string
	Yes             bool

	Writer   io.Writer
	Profiles []string
}

BridgeConvert is the options for compose bridge convert.

type BridgeTransformationsCreate

type BridgeTransformationsCreate struct {
	From string
	Dest string

	Writer io.Writer
}

BridgeTransformationsCreate is the options for compose bridge transformations create.

type BridgeTransformationsList

type BridgeTransformationsList struct {
	Format string // table or json; default table
	Quiet  bool

	Writer io.Writer
}

BridgeTransformationsList is the options for compose bridge transformations list.

type Build

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

Build is a fluent Compose service build spec. Pass it to Service.Build. A later Build call is applied after earlier ones.

func NewBuild

func NewBuild() Build

NewBuild starts an empty build spec.

func NewBuildFrom

func NewBuildFrom(spec BuildSpec) Build

NewBuildFrom starts a build spec from an existing BuildSpec value.

func (Build) AdditionalContext

func (b Build) AdditionalContext(name, value string) Build

AdditionalContext sets one named additional build context.

func (Build) AdditionalContexts

func (b Build) AdditionalContexts(contexts map[string]string) Build

AdditionalContexts merges named additional build contexts.

func (Build) Apply

func (b Build) Apply(cfg *types.ServiceConfig) error

Apply writes the build spec onto a Compose service.

func (Build) Arg

func (b Build) Arg(key, value string) Build

Arg sets one build arg.

func (Build) Args

func (b Build) Args(args map[string]string) Build

Args merges build args into the spec.

func (Build) CacheFrom

func (b Build) CacheFrom(sources ...string) Build

CacheFrom appends cache import sources.

func (Build) CacheTo

func (b Build) CacheTo(destinations ...string) Build

CacheTo appends cache export destinations.

func (Build) Context

func (b Build) Context(path string) Build

Context sets the build context directory.

func (Build) Dockerfile

func (b Build) Dockerfile(file DockerFile) Build

Dockerfile sets the Dockerfile text from a DockerFile builder. A nil file is ignored. When validation fails, WithService reports the error and does not apply the spec.

func (Build) DockerfilePath

func (b Build) DockerfilePath(path string) Build

DockerfilePath sets the Dockerfile path inside the context.

func (Build) Entitlement

func (b Build) Entitlement(names ...string) Build

Entitlement appends build entitlements.

func (Build) ExtraHost

func (b Build) ExtraHost(host string) Build

ExtraHost appends an extra host entry in "name:ip" form.

func (Build) Isolation

func (b Build) Isolation(mode string) Build

Isolation sets the build isolation mode.

func (Build) Label

func (b Build) Label(key, value string) Build

Label sets one build label.

func (Build) Labels

func (b Build) Labels(labels map[string]string) Build

Labels merges build labels into the spec.

func (Build) Network

func (b Build) Network(name string) Build

Network sets the network mode used during the build.

func (Build) NoCache

func (b Build) NoCache() Build

NoCache disables the build cache.

func (Build) NoCacheFilter

func (b Build) NoCacheFilter(filters ...string) Build

NoCacheFilter appends cache filters that skip the cache.

func (Build) Platform

func (b Build) Platform(platforms ...string) Build

Platform appends target platforms.

func (Build) Privileged

func (b Build) Privileged() Build

Privileged enables privileged mode for the build.

func (Build) Provenance

func (b Build) Provenance(mode string) Build

Provenance sets the provenance attestation mode.

func (Build) Pull

func (b Build) Pull() Build

Pull pulls newer versions of the base image.

func (Build) Reader

func (b Build) Reader() (io.Reader, error)

Reader returns the tar build context client.ImageBuild reads. Context is the directory to pack. A Dockerfile passed to Build.Dockerfile is written as Dockerfile over any Dockerfile already in that directory. When only Context or DockerfilePath is set, the file is read from disk (default "Dockerfile"). A .dockerignore in Context is honored. An empty Context packs only the Dockerfile.

func (Build) SBOM

func (b Build) SBOM(mode string) Build

SBOM sets the SBOM attestation mode.

func (Build) SSH

func (b Build) SSH(id, path string) Build

SSH appends an SSH agent socket or key available to the build.

func (Build) Secret

func (b Build) Secret(secret BuildSecret) Build

Secret appends a build-time secret reference.

func (Build) ShmSize

func (b Build) ShmSize(size int64) Build

ShmSize sets /dev/shm size in bytes.

func (Build) Tag

func (b Build) Tag(tags ...string) Build

Tag appends image tags applied to the built image.

func (Build) Target

func (b Build) Target(name string) Build

Target sets the Dockerfile target stage.

func (Build) Ulimit

func (b Build) Ulimit(name string, soft, hard int) Build

Ulimit sets one build ulimit.

type BuildSSH

type BuildSSH struct {
	ID   string
	Path string
}

BuildSSH is one SSH agent socket or key for a service build.

type BuildSecret

type BuildSecret struct {
	Source string
	Target string
	UID    string
	GID    string
	Mode   *int64
}

BuildSecret is a build-time secret reference.

type BuildSpec

type BuildSpec struct {
	Context            string
	Dockerfile         string
	DockerfileInline   string
	Args               map[string]string
	Labels             map[string]string
	Tags               []string
	Target             string
	Network            string
	NoCache            bool
	Pull               bool
	Privileged         bool
	Platforms          []string
	CacheFrom          []string
	CacheTo            []string
	SSH                []BuildSSH
	AdditionalContexts map[string]string
	ExtraHosts         []string
	Isolation          string
	ShmSize            int64
	Entitlements       []string
	Ulimits            map[string]BuildUlimit
	Secrets            []BuildSecret
	Provenance         string
	SBOM               string
	NoCacheFilter      []string
	// contains filtered or unexported fields
}

BuildSpec is Compose service build configuration.

func (BuildSpec) Apply

func (b BuildSpec) Apply(cfg *composetypes.ServiceConfig) error

type BuildUlimit

type BuildUlimit struct {
	Soft int
	Hard int
}

BuildUlimit is a soft/hard ulimit for a service build.

type Commit

type Commit struct {
	Author  string
	Change  []string // Dockerfile instructions applied to the image
	Index   *int
	Message string
	NoPause bool // --pause=false; Compose defaults to true

	Writer     io.Writer
	Profiles   []string
	Service    string // required
	Repository string // optional REPOSITORY[:TAG]
}

Commit is the options for the compose commit command. Service is required.

type Compose

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

Compose runs a Project through the Docker Compose SDK.

func NewCompose

func NewCompose(project *Project) *Compose

NewCompose returns a Compose runner for the given project.

func (*Compose) Attach

func (c *Compose) Attach(ctx context.Context, opt *Attach) error

Attach attaches to a running service container. Service is required.

func (*Compose) BridgeConvert

func (c *Compose) BridgeConvert(ctx context.Context, opt *BridgeConvert) error

BridgeConvert converts the project with a Compose bridge transformation.

func (*Compose) BridgeTransformationsCreate

func (c *Compose) BridgeTransformationsCreate(ctx context.Context, opt *BridgeTransformationsCreate) error

BridgeTransformationsCreate copies a transformation image into Dest.

func (*Compose) BridgeTransformationsList

func (c *Compose) BridgeTransformationsList(ctx context.Context, opt *BridgeTransformationsList) error

BridgeTransformationsList writes installed Compose bridge transformations.

func (*Compose) Build

func (c *Compose) Build(ctx context.Context, opt *ComposeBuild) error

Build builds or rebuilds services.

func (*Compose) Commit

func (c *Compose) Commit(ctx context.Context, opt *Commit) error

Commit creates an image from a service container. Service is required.

func (*Compose) Config

func (c *Compose) Config(ctx context.Context, opt *ComposeConfig) error

Config renders the project model.

func (*Compose) Cp

func (c *Compose) Cp(ctx context.Context, opt *Cp) error

Cp copies between a service container and the local filesystem. Source and Dest are required.

func (*Compose) Create

func (c *Compose) Create(ctx context.Context, opt *Create) error

Create creates containers for services without starting them.

func (*Compose) Down

func (c *Compose) Down(ctx context.Context, opt *Down) error

Down stops and removes project resources. A nil opt uses defaults (writer is os.Stdout).

func (*Compose) Events

func (c *Compose) Events(ctx context.Context, opt *EventsOpt) (<-chan Events, <-chan error, error)

Events streams compose events for the project. A nil opt watches every service and enables no profiles.

func (*Compose) Exec

func (c *Compose) Exec(ctx context.Context, opt *Exec) error

Exec runs a command in a running service container. Service and Command must be set on opt.

func (*Compose) Export

func (c *Compose) Export(ctx context.Context, opt *ComposeExport) error

Export writes a service container filesystem as a tar archive. Service is required.

func (*Compose) Generate

func (c *Compose) Generate(ctx context.Context, opt *Generate) error

Generate writes a Compose model built from existing containers.

func (*Compose) Global

func (c *Compose) Global(g Global) *Compose

Global sets parent settings used by every command on this runner.

func (*Compose) Images

func (c *Compose) Images(ctx context.Context, opt *Images) error

Images lists images used by project containers.

func (*Compose) Kill

func (c *Compose) Kill(ctx context.Context, opt *Kill) error

Kill stops service containers immediately. A nil opt uses defaults (writer is os.Stdout).

func (*Compose) LoadProject

func (c *Compose) LoadProject(ctx context.Context, opt *ProjectLoad) (*Project, error)

LoadProject loads a Compose project from files and returns it. Global compatibility, env files, working directory, all-resources, and dry-run apply.

func (*Compose) Logs

func (c *Compose) Logs(ctx context.Context, opt *Logs) error

Logs writes service logs to Writer. A nil opt uses defaults (writer is os.Stdout).

func (*Compose) Ls

func (c *Compose) Ls(ctx context.Context, opt *Ls) error

Ls lists Compose projects on the engine.

func (*Compose) Pause

func (c *Compose) Pause(ctx context.Context, opt *Pause) error

Pause pauses services.

func (*Compose) Port

func (c *Compose) Port(ctx context.Context, opt *Port) error

Port prints the public address for a private port. Service and PrivatePort are required.

func (*Compose) Project

func (c *Compose) Project() *Project

Project is the Compose project this runner was constructed with.

func (*Compose) Ps

func (c *Compose) Ps(ctx context.Context, opt *Ps) error

Ps lists project containers.

func (*Compose) Publish

func (c *Compose) Publish(ctx context.Context, opt *Publish) error

Publish publishes the application image. Repository is required.

func (*Compose) Pull

func (c *Compose) Pull(ctx context.Context, opt *Pull) error

Pull pulls service images.

func (*Compose) Push

func (c *Compose) Push(ctx context.Context, opt *Push) error

Push pushes service images.

func (*Compose) Restart

func (c *Compose) Restart(ctx context.Context, opt *Restart) error

Restart restarts project containers.

func (*Compose) Rm

func (c *Compose) Rm(ctx context.Context, opt *Rm) error

Rm removes stopped service containers.

func (*Compose) Run

func (c *Compose) Run(ctx context.Context, opt *Run) error

Run runs a one-off command on a service. Service is required.

func (*Compose) Scale

func (c *Compose) Scale(ctx context.Context, opt *Scale) error

Scale sets the number of replicas for services. Replicas is required.

func (*Compose) Start

func (c *Compose) Start(ctx context.Context, opt *Start) error

Start starts existing project containers.

func (*Compose) Stats

func (c *Compose) Stats(ctx context.Context, opt *Stats) error

Stats writes container resource usage. The Compose SDK has no stats method, so this reads one-shot or streamed stats from the engine for project containers.

func (*Compose) Stop

func (c *Compose) Stop(ctx context.Context, opt *Stop) error

Stop stops project containers.

func (*Compose) Top

func (c *Compose) Top(ctx context.Context, opt *Top) error

Top lists processes in project containers.

func (*Compose) Unpause

func (c *Compose) Unpause(ctx context.Context, opt *Unpause) error

Unpause unpauses services.

func (*Compose) Up

func (c *Compose) Up(ctx context.Context, opt *Up) error

Up creates and starts the project. A nil opt uses defaults (writer is os.Stdout).

func (*Compose) Version

func (c *Compose) Version(ctx context.Context, opt *Version) error

Version writes the linked Compose SDK module version.

func (*Compose) Viz

func (c *Compose) Viz(ctx context.Context, opt *Viz) error

Viz writes a Graphviz graph of the project.

func (*Compose) Volumes

func (c *Compose) Volumes(ctx context.Context, opt *Volumes) error

Volumes lists project volumes.

func (*Compose) Wait

func (c *Compose) Wait(ctx context.Context, opt *Wait) error

Wait blocks until a service container stops. ServiceNames is required.

func (*Compose) Watch

func (c *Compose) Watch(ctx context.Context, opt *Watch) error

Watch rebuilds services when build-context files change.

type ComposeBuild

type ComposeBuild struct {
	BuildArg         []string // key=value, appended as --build-arg each
	Builder          string
	Check            bool
	Memory           string // e.g. "2G"
	NoCache          bool
	Print            bool
	Provenance       bool
	Pull             bool
	Push             bool
	Quiet            bool
	SBOM             bool
	SSH              []string // e.g. "default" or "key=path"
	WithDependencies bool
	Writer           io.Writer
	Profiles         []string
	ServiceNames     []string
}

ComposeBuild is the options for the compose build command

type ComposeConfig

type ComposeConfig struct {
	PrintEnvironment bool
	Format           string // yaml | json
	PrintImages      bool
	PrintModels      bool
	PrintNetworks    bool
	NoConsistency    bool
	NoEnvResolution  bool
	NoInterpolate    bool
	NoNormalize      bool
	NoPathResolution bool
	Output           string
	PrintProfiles    bool
	Quiet            bool
	PrintServices    bool
	PrintVariables   bool
	PrintVolumes     bool

	Writer       io.Writer
	Profiles     []string
	ServiceNames []string
}

ComposeConfig is the options for the compose config command. Named ComposeConfig because Config is too generic (MergedConfig, container.Config).

type ComposeExport

type ComposeExport struct {
	Index  *int
	Output string

	Writer   io.Writer
	Profiles []string
	Service  string // required
}

ComposeExport is the options for the compose export command. Named ComposeExport to avoid confusion with Project.Export. Service is required.

type Container

type Container struct {
	Name   string              // the name of the container
	Config *types.MergedConfig // merged docker sdk configuration for container creation
	Errors []error             // errors encountered during configuration
	// contains filtered or unexported fields
}

func NewContainer

func NewContainer(name ...string) *Container

NewContainer creates a new container with the given name. It will return a container with empty configurations ready to be set. a container is a wrapper around the docker sdk container configuration. but it can be used as a service config in a compose project

parameters:

  • name: the name of the container

Note: 'name' is optional when using this container as a Compose service config. It is required when using the Docker SDK directly. If multiple strings are passed as the name, they will be joined with hyphens (e.g., "foo", "bar" -> "foo-bar").

func (*Container) AddedCapabilities

func (c *Container) AddedCapabilities(caps ...types.Capability) *Container

AddedCapabilities adds capabilities to the host configuration for the container. parameters:

  • caps: the capabilities to add

func (*Container) AddedDevice

func (c *Container) AddedDevice(device types.Device) *Container

AddedDevice maps a host device into the container.

func (*Container) AddedGroups

func (c *Container) AddedGroups(group ...string) *Container

AddedGroups appends supplementary groups to the host configuration for the container. parameters:

  • group: the group to add

func (*Container) Architecture

func (c *Container) Architecture(architecture string) *Container

Architecture sets the platform CPU architecture, for example amd64 or ppc64le. Parameter:

  • architecture: the architecture to be used for the platform

Architecture field specifies the CPU architecture, for example `amd64` or `ppc64le`.

func (*Container) AttachedStderr

func (c *Container) AttachedStderr() *Container

func (*Container) AttachedStdin

func (c *Container) AttachedStdin() *Container

func (*Container) AttachedStdout

func (c *Container) AttachedStdout() *Container

func (*Container) AutoRemove

func (c *Container) AutoRemove() *Container

AutoRemove sets the container to be automatically removed when it exits.

func (*Container) BindMountWithPropagation

func (c *Container) BindMountWithPropagation(source, target string, propagation types.MountPropagation) *Container

func (*Container) BlkioDeviceReadBps

func (c *Container) BlkioDeviceReadBps(devicePath string, rate types.ByteSize) *Container

BlkioDeviceReadBps limits the read rate for one device.

func (*Container) BlkioDeviceReadIOps

func (c *Container) BlkioDeviceReadIOps(devicePath string, rate uint64) *Container

BlkioDeviceReadIOps appends a block IO read operations per second (IOPS) limit for a specific device to the container's host configuration.

Parameters:

  • devicePath: the device path (e.g., "/dev/sda")
  • rate: the maximum read IOPS limit

func (*Container) BlkioDeviceWriteBps

func (c *Container) BlkioDeviceWriteBps(devicePath string, rate types.ByteSize) *Container

BlkioDeviceWriteBps limits the write rate for one device.

func (*Container) BlkioDeviceWriteIOps

func (c *Container) BlkioDeviceWriteIOps(devicePath string, rate uint64) *Container

BlkioDeviceWriteIOps appends a block IO write operations per second (IOPS) limit for a specific device to the container's host configuration.

Parameters:

  • devicePath: the device path (e.g., "/dev/sda")
  • rate: the maximum write IOPS limit

func (*Container) BlkioWeight

func (c *Container) BlkioWeight(weight uint16) *Container

BlkioWeight sets the block IO weight (relative weight) for the container. Weight is a value between 10 and 1000. parameters:

  • weight: the block IO weight

func (*Container) CPUCount

func (c *Container) CPUCount(count int64) *Container

CPUCount sets the number of CPUs allocated to the container in the host configuration.

Parameters:

  • count: the number of CPUs to allocate to the container.

Returns an error if count is less than 1.

func (*Container) CPUPercent

func (c *Container) CPUPercent(percent int64) *Container

CPUPercent sets the CPU percentage limit for the container.

This option specifies the maximum amount of CPU the container can use as a percentage (e.g., 50 means the container can use up to 50% of one CPU core).

Parameters:

  • percent: the desired CPU limit as a percentage (0–100, or more for multi-core allocation).

Returns an error if the percent is negative.

func (*Container) CPUPeriod

func (c *Container) CPUPeriod(period time.Duration) *Container

CPUPeriod sets the CFS period. Zero leaves it unset. A positive period must be from 1ms through 1s.

func (*Container) CPUQuota

func (c *Container) CPUQuota(quota time.Duration) *Container

CPUQuota sets the CFS quota. Zero means no quota.

func (*Container) CPURealtimePeriod

func (c *Container) CPURealtimePeriod(period time.Duration) *Container

CPURealtimePeriod sets the real-time scheduling period. Zero leaves it unset. A positive period must be from 1ms through 1s.

func (*Container) CPURealtimeRuntime

func (c *Container) CPURealtimeRuntime(runtime int64) *Container

CPURealtimeRuntime sets the CPU real-time runtime in microseconds. A value of -1 disables the limit (default). parameters:

  • runtime: the CPU real-time runtime in microseconds

func (*Container) CPUShares

func (c *Container) CPUShares(shares int64) *Container

CPUShares sets the CPU shares (relative weight) for the container.

CPU shares define the relative CPU time available to the container compared to others. For example, 1024 is the default (normal priority), 512 is half the CPU weight, 2048 is double.

Parameters:

  • shares: the number of CPU shares (must be a positive integer).

Returns an error if the value is less than or equal to zero.

func (*Container) Cgroup

func (c *Container) Cgroup(mode types.CgroupMode) *Container

Cgroup sets the container cgroup namespace.

func (*Container) CgroupParent

func (c *Container) CgroupParent(parent string) *Container

func (*Container) Command

func (c *Container) Command(cmd ...string) *Container

Command appends the command to be run in the container Parameters:

  • cmd: command and its arguments

func (*Container) ConsoleSize

func (c *Container) ConsoleSize(size types.ConsoleSize) *Container

ConsoleSize sets the container console height and width.

func (*Container) ContainerIDFile

func (c *Container) ContainerIDFile(path string) *Container

ContainerIDFile sets the path to a file where the container ID will be written after creation.

After `client.ContainerCreate`, Docker will write the container's ID to this file. This is useful for external tooling or scripts that need to reference the container after it starts.

Parameters:

  • path: absolute or relative path to the container ID file.

Returns an error if the path is empty or only whitespace.

func (*Container) CpusetCpus

func (c *Container) CpusetCpus(cpus types.Cpuset) *Container

CpusetCpus sets the CPUs in which execution is allowed.

func (*Container) CpusetMems

func (c *Container) CpusetMems(mems types.Cpuset) *Container

CpusetMems sets the memory nodes in which execution is allowed. Only effective on NUMA systems.

func (*Container) DNSLookups

func (c *Container) DNSLookups(dns ...string) *Container

DNSLookups appends a DNS server to the host configuration for the container. parameters:

  • dns: the DNS server to add

func (*Container) DNSOptions

func (c *Container) DNSOptions(dnsOption ...string) *Container

DNSOptions appends a DNS option to the host configuration for the container. parameters:

  • dnsOption: the DNS option to add

func (*Container) DNSSearches

func (c *Container) DNSSearches(search ...string) *Container

DNSSearches appends a DNS search domain to the host configuration for the container. parameters:

  • search: the DNS search domain to add

func (*Container) DeviceCgroupRules

func (c *Container) DeviceCgroupRules(rules ...string) *Container

DeviceCgroupRules appends device cgroup rules to the container's host configuration. Device cgroup rules control access to devices inside the container.

Parameters:

  • rules: one or more device cgroup rule strings (e.g., "c 1:3 rwm").

Note: Rules must follow the device cgroup format accepted by the Linux kernel.

func (*Container) DeviceRequest

func (c *Container) DeviceRequest(req types.DeviceRequest) *Container

DeviceRequest appends a device request, such as a GPU, to the container.

func (*Container) DisabledHealthCheck

func (c *Container) DisabledHealthCheck() *Container

DisabledHealthCheck disables the healthcheck.

func (*Container) DisabledNetwork

func (c *Container) DisabledNetwork() *Container

func (*Container) DomainName

func (c *Container) DomainName(domainname string) *Container

DomainName sets the domain name of the container

func (*Container) DroppedAllCapabilities

func (c *Container) DroppedAllCapabilities() *Container

DroppedAllCapabilities drops all capabilities

func (*Container) DroppedCapabilities

func (c *Container) DroppedCapabilities(caps ...types.Capability) *Container

DroppedCapabilities drops capabilities from the host configuration for the container. parameters:

  • caps: the capabilities to drop

func (*Container) DroppedSensitiveCapabilities

func (c *Container) DroppedSensitiveCapabilities() *Container

DroppedSensitiveCapabilities drops a common set of sensitive capabilities

SYS_ADMIN, SYS_MODULE, SYS_PTRACE, SYS_TIME, SYSLOG, MAC_ADMIN, MAC_OVERRIDE, CHECKPOINT_RESTORE

func (*Container) Endpoint

func (c *Container) Endpoint(name string, opts ...EndpointOpts) *Container

Endpoint joins the named network. Optional EndpointOpts customize the endpoint.

func (*Container) Entrypoint

func (c *Container) Entrypoint(entrypoint ...string) *Container

Entrypoint sets the entrypoint to be run within the container

func (*Container) Env

func (c *Container) Env(key string, value string) *Container

Env appends an environment variable and its value to the container configuration Parameters:

  • key: environment variable name
  • value: environment variable value

func (*Container) EnvMap

func (c *Container) EnvMap(env map[string]string) *Container

EnvMap appends a map of environment variables to the container configuration Parameters:

  • env: map of environment variables

func (*Container) EscapedArgs

func (c *Container) EscapedArgs() *Container

func (*Container) ExposedPort

func (c *Container) ExposedPort(protocol types.Protocol, port string) *Container

ExposedPort appends a port to be exposed from the container Parameter:

  • port: port number or port range to be exposed in the container (e.g., "80-1000" or "80")
  • protocol: protocol to be exposed from the container

func (*Container) ExtraHost

func (c *Container) ExtraHost(hostname, ip string) *Container

ExtraHost adds a hostname and address to the container hosts file.

func (*Container) HealthCheck

func (c *Container) HealthCheck(h Health) *Container

HealthCheck sets the container healthcheck from a Health value.

func (*Container) HostBindMountRecursiveRO

func (c *Container) HostBindMountRecursiveRO(source, target string) *Container

func (*Container) HostName

func (c *Container) HostName(hostname string) *Container

HostName sets the hostname of the container

func (*Container) Image

func (c *Container) Image(image string) *Container

Image sets the image to use for the container

func (*Container) Imagef

func (c *Container) Imagef(stringFormat string, args ...any) *Container

func (*Container) Init

func (c *Container) Init() *Container

Init sets the init flag for the container parameters:

  • init: the init flag to use

Note: use to run a custom init inside the container, if null, use the daemon's configured settings

func (*Container) IpcMode

func (c *Container) IpcMode(mode types.IpcMode) *Container

IpcMode sets the container IPC namespace.

func (*Container) Isolation

func (c *Container) Isolation(mode types.Isolation) *Container

Isolation sets the container isolation mode.

func (*Container) KernelMemory

func (c *Container) KernelMemory(memory types.ByteSize) *Container

KernelMemory sets the kernel memory limit.

func (*Container) Label

func (c *Container) Label(label, value string) *Container

Label appends a label to the container Parameters:

  • label: label key
  • value: label value

func (*Container) LogDriver

func (c *Container) LogDriver(driver string, options map[string]string) *Container

func (*Container) MaskedPaths

func (c *Container) MaskedPaths(paths ...string) *Container

MaskedPaths appends a list of paths to be masked inside the container.

Masked paths are mounted as read-only and inaccessible from within the container, overriding the default masked paths (e.g., "/proc/kcore", "/proc/latency_stats").

Parameters:

  • paths: one or more absolute paths to mask

Returns an error if any path is empty or not absolute.

func (*Container) MemoryLimit

func (c *Container) MemoryLimit(memory types.ByteSize) *Container

MemoryLimit sets the container memory limit.

func (*Container) MemoryReservation

func (c *Container) MemoryReservation(memory types.ByteSize) *Container

MemoryReservation sets the memory soft limit.

func (*Container) MemorySwap

func (c *Container) MemorySwap(memorySwap types.ByteSize) *Container

MemorySwap sets the total memory limit, including swap.

func (*Container) MemorySwappiness

func (c *Container) MemorySwappiness(swappiness int64) *Container

MemorySwappiness tunes container memory swappiness (0 to 100). - A value of 0 turns off anonymous page swapping. - A value of 100 sets the host's swappiness value. - Values between 0 and 100 modify the swappiness level accordingly. parameters:

  • swappiness: the swappiness level

func (*Container) Mount

func (c *Container) Mount(m Mount) *Container

Mount adds a host mount point.

func (*Container) NetworkMode

func (c *Container) NetworkMode(mode types.NetworkMode) *Container

NetworkMode sets the container network namespace.

func (*Container) NonRecursiveBindMount

func (c *Container) NonRecursiveBindMount(source, target string, readonly bool) *Container

func (*Container) OS

func (c *Container) OS(OS string) *Container

OS sets the OS for the platform Parameter:

  • OS: the OS to be used for the platform

OS specifies the operating system, for example `linux` or `windows`.

func (*Container) OSFeatures

func (c *Container) OSFeatures(OSFeatures ...string) *Container

OSFeatures sets the OS features for the platform Parameter:

  • OSFeatures: the OS features to be used for the platform

OSFeatures is an optional field specifying an array of strings, each listing a required OS feature (for example on Windows `win32k`).

func (*Container) OSVersion

func (c *Container) OSVersion(OSVersion string) *Container

OSVersion sets the OS version for the platform Parameter:

  • OSVersion: the OS version to be used for the platform

OSVersion is an optional field specifying the operating system version, for example on Windows `10.0.14393.1066`.

func (*Container) OnBuild

func (c *Container) OnBuild(args ...string) *Container

OnBuild appends ONBUILD metadata that will trigger when the image is used as a base image

func (*Container) OomKillDisable

func (c *Container) OomKillDisable() *Container

OomKillDisable sets the OOM kill disable flag for the container in the host configuration. parameters:

  • oomKillDisable: the OOM kill disable flag to use

func (*Container) OomScoreAdj

func (c *Container) OomScoreAdj(score int) *Container

OomScoreAdj sets the Out-Of-Memory (OOM) score adjustment for the container.

The OOM score adjustment ranges from -1000 to 1000 and tells the kernel how likely it is to kill the container’s process when the system is under memory pressure. - A value closer to -1000 means the process is protected from OOM killing. - A value closer to 1000 makes the process more likely to be killed.

Parameters:

  • score: an integer between -1000 and 1000 (inclusive)

Returns an error if the score is outside the valid range.

func (*Container) PidMode

func (c *Container) PidMode(mode types.PidMode) *Container

PidMode sets the container PID namespace.

func (*Container) PidsLimit

func (c *Container) PidsLimit(limit int64) *Container

PidsLimit sets the container's PIDs limit. parameters:

  • limit: the PIDs limit

func (*Container) PortBinding

func (c *Container) PortBinding(binding types.PortBinding) *Container

PortBinding publishes one container port on the host. An empty Protocol defaults to TCP. An empty HostIP defaults to 0.0.0.0.

func (*Container) Privileged

func (c *Container) Privileged() *Container

func (*Container) PublishAllPorts

func (c *Container) PublishAllPorts() *Container

func (*Container) ROHostBindMount

func (c *Container) ROHostBindMount(source string, target string) *Container

func (*Container) RONamedVolumeMount

func (c *Container) RONamedVolumeMount(name, target string) *Container

func (*Container) RWHostBindMount

func (c *Container) RWHostBindMount(source string, target string) *Container

func (*Container) RWNamedVolumeMount

func (c *Container) RWNamedVolumeMount(name, target string) *Container

func (*Container) RWNamedVolumeMountWithLabel

func (c *Container) RWNamedVolumeMountWithLabel(name, target, labelKey, labelValue string) *Container

func (*Container) RWNamedVolumeSubPath

func (c *Container) RWNamedVolumeSubPath(name, target, subPath string) *Container

func (*Container) ReadOnlyRootfs

func (c *Container) ReadOnlyRootfs() *Container

func (*Container) ReadonlyPaths

func (c *Container) ReadonlyPaths(paths ...string) *Container

ReadonlyPaths appends a list of paths to be marked as read-only inside the container.

These paths are mounted as read-only from the host and are inaccessible for writing by any process in the container.

Parameters:

  • paths: one or more absolute paths to mark as read-only

Returns an error if any path is empty or not absolute.

func (*Container) RestartAlways

func (c *Container) RestartAlways() *Container

RestartAlways sets a restart policy that ensures the container is always restarted upon exit. This policy restarts the container indefinitely, ignoring any retry limits.

func (*Container) RestartPolicy

func (c *Container) RestartPolicy(mode types.RestartPolicy, maxRetryCount int) *Container

RestartPolicy sets the container restart policy. maxRetryCount applies to RestartPolicyOnFailure.

func (*Container) RestartPolicyAlways

func (c *Container) RestartPolicyAlways() *Container

RestartPolicyAlways restarts the container whenever it exits.

func (*Container) RestartPolicyNever

func (c *Container) RestartPolicyNever() *Container

RestartPolicyNever does not restart the container.

func (*Container) RestartPolicyOnFailure

func (c *Container) RestartPolicyOnFailure(maxRetryCount int) *Container

RestartPolicyOnFailure restarts the container when it exits with an error.

func (*Container) RestartPolicyUnlessStopped

func (c *Container) RestartPolicyUnlessStopped() *Container

RestartPolicyUnlessStopped restarts the container unless it was stopped.

func (*Container) RestartUnlessStopped

func (c *Container) RestartUnlessStopped() *Container

RestartUnlessStopped is an alias for RestartPolicyUnlessStopped.

func (*Container) Runtime

func (c *Container) Runtime(runtime string) *Container

func (*Container) SecurityOpts

func (c *Container) SecurityOpts(opts ...string) *Container

SecurityOpts appends security options to the container's host configuration.

These options customize security labels or settings used by Mandatory Access Control (MAC) systems like SELinux, AppArmor, or Seccomp. They allow fine-tuning container security contexts, such as specifying custom SELinux labels or disabling certain security profiles.

Docker itself does minimal validation on these strings, so this function simply appends them. Users should provide valid options according to their security system's documentation.

parameters:

  • opts: a variadic list of security options to append (e.g., SELinux labels or profile overrides)

func (*Container) Shell

func (c *Container) Shell(shell ...string) *Container

Shell sets the shell for shell-form of RUN, CMD, ENTRYPOINT

func (*Container) ShmSize

func (c *Container) ShmSize(size types.ByteSize) *Container

ShmSize sets the size of /dev/shm.

func (*Container) StdinOnce

func (c *Container) StdinOnce() *Container

func (*Container) StdinOpen

func (c *Container) StdinOpen() *Container

func (*Container) StopSignal

func (c *Container) StopSignal(signal string) *Container

StopSignal sets the signal that will be used to stop the container

func (*Container) StopTimeout

func (c *Container) StopTimeout(timeout int) *Container

StopTimeout sets the timeout (in seconds) to stop the container

note: is also stop_grace_period in compose

func (*Container) StorageOpt

func (c *Container) StorageOpt(key, value string) *Container

StorageOpt appends a storage driver option for the container's host configuration. Storage options are key-value pairs passed to the container storage driver to configure specific behaviors like size limits, encryption, or performance settings.

Since storage options are driver-specific and Docker itself does minimal validation, this function trims whitespace and requires a non-empty key to avoid invalid or meaningless options that might cause runtime errors or unexpected behavior.

parameters:

  • key: the storage option key (must be non-empty after trimming whitespace)
  • value: the value for the storage option

func (*Container) Sysctls

func (c *Container) Sysctls(key, value string) *Container

Sysctls adds or updates a sysctl key-value pair in the container's host configuration. Sysctls allow tuning of kernel parameters inside the container.

Parameters:

  • key: the sysctl parameter name (e.g., "net.ipv4.ip_forward")
  • value: the sysctl parameter value (e.g., "1")

Note: The effectiveness of sysctls depends on the container runtime and host kernel support.

func (*Container) Tmpfs

func (c *Container) Tmpfs(key, value string) *Container

Tmpfs appends to a map of tmpfs (mounts) used for the container parameters:

  • key: the key of the tmpfs option
  • value: the value of the tmpfs option

func (*Container) TmpfsMount

func (c *Container) TmpfsMount(target string, sizeBytes int, mode os.FileMode) *Container

func (*Container) TmpfsMountCustomOptions

func (c *Container) TmpfsMountCustomOptions(target string, sizeBytes int, flags ...[]string) *Container

func (*Container) TmpfsMountExec

func (c *Container) TmpfsMountExec(target string, sizeBytes int) *Container

func (*Container) TmpfsMountUIDGID

func (c *Container) TmpfsMountUIDGID(target string, sizeBytes int, uid, gid string) *Container

func (*Container) Tty

func (c *Container) Tty() *Container

func (*Container) UTSMode

func (c *Container) UTSMode(mode types.UTSMode) *Container

UTSMode sets the container UTS namespace.

func (*Container) Ulimits

func (c *Container) Ulimits(limit types.Ulimit) *Container

Ulimits appends one resource limit.

func (*Container) User

func (c *Container) User(user string) *Container

User sets the user that commands are run as inside the container

func (*Container) UserNSMode

func (c *Container) UserNSMode(mode types.UserNSMode) *Container

UserNSMode sets the container user namespace.

func (*Container) Validate

func (c *Container) Validate() error

Validate validates the container config. It will return an error if the container has errors.

func (*Container) Variant

func (c *Container) Variant(variant string) *Container

Variant sets the variant for the platform Parameter:

  • variant: the variant to be used for the platform

Variant is an optional field specifying a variant of the CPU, for example `v7` to specify ARMv7 when architecture is `arm`.

func (*Container) Volume

func (c *Container) Volume(volume string) *Container

Volume appends a short hand volume mount point to the container Parameter:

  • volume: path where the volume should be mounted

note: Compose maps this to an anonymous volume at the container path. Named volumes use Mount or RWNamedVolumeMount.

func (*Container) VolumeBinds

func (c *Container) VolumeBinds(binds ...string) *Container

VolumeBinds parses short mount strings into Mount values. Format is source:target[:mode]. Mode is optional and defaults to read-write. A source with no path separator is a named volume. Absolute, relative, and Windows paths are binds. Mode tokens: ro, rw, readonly, z, Z, consistent, cached, delegated, rshared, shared, rslave, slave, rprivate, private.

func (*Container) VolumeDriver

func (c *Container) VolumeDriver(driver string) *Container

VolumeDriver sets the volume driver for the container in the host configuration.

The volume driver specifies the plugin or mechanism used to manage volumes mounted into the container. This option is typically only used with the Docker API directly, not with Docker Compose.

Parameters:

  • driver: the name of the volume driver to use.

Returns an error if the driver name is empty or contains only whitespace.

func (*Container) VolumesFrom

func (c *Container) VolumesFrom(name string, readOnly bool) *Container

VolumesFrom inherits volumes from another container. readOnly maps to the :ro suffix. A writable inherit stores the container name alone.

func (*Container) WorkingDir

func (c *Container) WorkingDir(dir string) *Container

WorkingDir sets the working directory for commands to run in

type CopyOpts

type CopyOpts struct {
	From    string
	Chown   string
	Chmod   string
	Link    bool
	Exclude []string
	Parents bool
}

CopyOpts are optional flags on a COPY instruction.

type Cp

type Cp struct {
	All        bool
	Archive    bool
	FollowLink bool
	Index      *int

	Writer   io.Writer
	Stdin    io.Reader // used when Source or Dest is "-"
	Profiles []string
	Source   string // required
	Dest     string // required
}

Cp is the options for the compose cp command. Source and Dest are required (SERVICE:PATH or PATH or "-").

type Create

type Create struct {
	Build         bool
	ForceRecreate bool
	NoBuild       bool
	NoRecreate    bool
	Pull          string
	QuietPull     bool
	RemoveOrphans bool
	IgnoreOrphans bool
	Scale         []UpScale
	Yes           bool

	Writer       io.Writer
	Profiles     []string
	ServiceNames []string
}

Create is the options for the compose create command.

type Deploy

type Deploy struct {
	Mode         string
	Replicas     *int
	Labels       map[string]string
	Limits       *types.Resources
	Reservations *types.Resources
}

Deploy is Compose deploy configuration.

func (Deploy) Apply

func (d Deploy) Apply(cfg *composetypes.ServiceConfig) error

type Develop

type Develop struct {
	Action WatchAction
	Path   string
	Target string
	Ignore []string
}

Develop is one Compose develop watch rule.

type DockerFile

type DockerFile interface {
	String() string
	Validate() error
}

DockerFile is the contract consumed by Build.Dockerfile. *Dockerfile from NewDockerFile, ParseDockerfile, and ReadDockerfile implements it.

type Dockerfile

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

Dockerfile is a fluent Dockerfile builder.

Not safe for concurrent use.

func NewDockerFile

func NewDockerFile() *Dockerfile

NewDockerFile creates a fluent Dockerfile builder.

func ParseDockerfile

func ParseDockerfile(content string) *Dockerfile

ParseDockerfile wraps existing Dockerfile text. An empty string records a validation error.

func ReadDockerfile

func ReadDockerfile(path string) *Dockerfile

ReadDockerfile reads a Dockerfile from path. Read errors are returned by Validate.

func (*Dockerfile) Add

func (d *Dockerfile) Add(src string, dest string, opts ...AddOpts) *Dockerfile

Add sets an ADD instruction. At most one AddOpts value is accepted.

func (*Dockerfile) Arg

func (d *Dockerfile) Arg(name string, defaultValue ...string) *Dockerfile

Arg sets an ARG instruction, with an optional default value.

func (*Dockerfile) Check

func (d *Dockerfile) Check(value string) *Dockerfile

Check sets the # check= parser directive.

func (*Dockerfile) Command

func (d *Dockerfile) Command(executable string, args ...string) *Dockerfile

Command sets CMD in JSON exec form. A second CMD records an error and is not written.

func (*Dockerfile) CommandShell

func (d *Dockerfile) CommandShell(executable string, args ...string) *Dockerfile

CommandShell sets CMD in shell form. A second CMD records an error and is not written.

func (*Dockerfile) Comment

func (d *Dockerfile) Comment(comment string) *Dockerfile

Comment writes a dockerfile comment.

func (*Dockerfile) Copy

func (d *Dockerfile) Copy(src string, dest string, opts ...CopyOpts) *Dockerfile

Copy sets a COPY instruction. At most one CopyOpts value is accepted.

func (*Dockerfile) Entrypoint

func (d *Dockerfile) Entrypoint(executable string, args ...string) *Dockerfile

Entrypoint sets the JSON exec form of ENTRYPOINT.

func (*Dockerfile) EntrypointShell

func (d *Dockerfile) EntrypointShell(executable string, args ...string) *Dockerfile

EntrypointShell sets the shell form of ENTRYPOINT.

func (*Dockerfile) Env

func (d *Dockerfile) Env(key string, value string) *Dockerfile

Env sets an ENV instruction.

func (*Dockerfile) Escape

func (d *Dockerfile) Escape(char string) *Dockerfile

Escape sets the # escape= parser directive. char must be \ or `.

func (*Dockerfile) Export

func (d *Dockerfile) Export(path string, mode os.FileMode) error

Export writes the dockerfile to path after validation.

func (*Dockerfile) Expose

func (d *Dockerfile) Expose(port string) *Dockerfile

Expose sets an EXPOSE instruction.

func (*Dockerfile) Format

func (d *Dockerfile) Format(args ...any) *Dockerfile

Format formats the dockerfile with the given arguments and replaces its contents.

func (*Dockerfile) From

func (d *Dockerfile) From(image string, tag ...string) *Dockerfile

From sets the FROM instruction. Pass the tag in image ("alpine:latest") or as the second argument.

func (*Dockerfile) FromAs

func (d *Dockerfile) FromAs(image, alias string) *Dockerfile

FromAs sets FROM image AS alias. image may include a tag.

func (*Dockerfile) FromAsPlatform

func (d *Dockerfile) FromAsPlatform(platform, image, alias string) *Dockerfile

FromAsPlatform sets FROM --platform=platform image AS alias.

func (*Dockerfile) FromPlatform

func (d *Dockerfile) FromPlatform(platform, image string, tag ...string) *Dockerfile

FromPlatform sets FROM --platform=platform.

func (*Dockerfile) HealthCheck

func (d *Dockerfile) HealthCheck(h Health) *Dockerfile

Healthcheck sets a HEALTHCHECK instruction from a container Health value. Zero interval, timeout, start period, and retries are omitted.

func (*Dockerfile) HealthCheckNone

func (d *Dockerfile) HealthCheckNone() *Dockerfile

HealthCheckNone sets HEALTHCHECK NONE.

func (*Dockerfile) Label

func (d *Dockerfile) Label(key string, value string) *Dockerfile

Label sets a LABEL instruction.

func (*Dockerfile) Onbuild

func (d *Dockerfile) Onbuild(cmd string) *Dockerfile

Onbuild sets an ONBUILD instruction.

func (*Dockerfile) Run

func (d *Dockerfile) Run(cmd string, opts ...RunOpts) *Dockerfile

Run sets a RUN instruction. Consecutive Run calls with no flags are joined with "&& \" into one layer. A call that sets RunOpts starts a new RUN.

func (*Dockerfile) RunArgs

func (d *Dockerfile) RunArgs(args ...string) *Dockerfile

RunArgs continues the previous RUN with newline continuation and no "&&".

func (*Dockerfile) RunLayer

func (d *Dockerfile) RunLayer(cmd string, opts ...RunOpts) *Dockerfile

RunLayer starts a new RUN instruction. Unlike Run, it does not fold into the previous RUN.

func (*Dockerfile) Shell

func (d *Dockerfile) Shell(executable string, args ...string) *Dockerfile

Shell sets the SHELL instruction (JSON exec form).

func (*Dockerfile) StopSignal

func (d *Dockerfile) StopSignal(signal string) *Dockerfile

StopSignal sets a STOPSIGNAL instruction.

func (*Dockerfile) String

func (d *Dockerfile) String() string

String returns the dockerfile text.

func (*Dockerfile) Syntax

func (d *Dockerfile) Syntax(frontend string) *Dockerfile

Syntax sets the # syntax= parser directive.

func (*Dockerfile) User

func (d *Dockerfile) User(user string) *Dockerfile

User sets a USER instruction.

func (*Dockerfile) Validate

func (d *Dockerfile) Validate() error

Validate returns any errors recorded while building the dockerfile.

func (*Dockerfile) Volumes

func (d *Dockerfile) Volumes(volumes ...string) *Dockerfile

Volumes sets a VOLUME instruction.

func (*Dockerfile) Workdir

func (d *Dockerfile) Workdir(path string) *Dockerfile

Workdir sets a WORKDIR instruction.

type Down

type Down struct {
	RemoveOrphans bool
	Timeout       *int
	RemoveImage   *string
	RemoveVolumes bool

	Writer       io.Writer
	Profiles     []string
	ServiceNames []string
}

Down is the options for the compose down command

type EndpointOpts

type EndpointOpts struct {
	Aliases       []string
	Links         []string
	MacAddress    string
	DriverOptions map[string]string
	IPv4          string
	IPv6          string
	LinkLocalIPs  []string
}

EndpointOpts are optional settings for a network endpoint.

type Events

type Events struct {
	// Core event fields
	Time    string `json:"time"`
	Type    string `json:"type"`
	Action  string `json:"action"`
	ID      string `json:"id"`
	Service string `json:"service"`
	// Attributes map containing event-specific information
	Attributes map[string]string `json:"attributes"`

	// Additional fields that may be present in some events
	Scope  string `json:"scope,omitempty"`
	Status string `json:"status,omitempty"`
	From   string `json:"from,omitempty"`
}

type EventsOpt

type EventsOpt struct {
	Service  string
	Profiles []string
	Since    string
	Until    string
}

EventsOpt is the options for the compose events command. A nil EventsOpt watches every service and enables no profiles.

type Exec

type Exec struct {
	Detach     bool
	Env        []string // key=value, passed as -e each
	Index      *int     // --index for multi-replica services
	NoTTY      bool     // -T: disable TTY
	Privileged bool
	User       string // -u
	Workdir    string // -w
	Writer     io.Writer
	Stdin      io.Reader // optional; forwarded to the container after compose file is read
	Profiles   []string
	Service    string   // required: service name
	Command    []string // required: command and args (e.g. ["sh", "-c", "echo hi"])
}

Exec is the options for the compose exec command. Usage: docker compose exec [OPTIONS] SERVICE COMMAND [ARGS...] Service and Command are required; set via WithService and WithCommand.

type Generate

type Generate struct {
	Name       string
	ProjectDir string
	Format     string // yaml or json; default yaml
	Containers []string

	Writer io.Writer
}

Generate is the options for compose alpha generate.

type Global

type Global struct {
	Progress         string
	ANSI             string
	Parallel         *int
	AllResources     bool
	EnvFile          []string
	Compatibility    bool
	ProjectDirectory string
	DryRun           bool
}

Global holds Compose-wide settings applied to every command on this runner.

type Health

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

Health is a fluent container healthcheck. Pass it to Container.HealthCheck and Dockerfile.Healthcheck. Timeout/Interval/StartPeriod are seconds unless the matching *D method is used ("2s", "1m").

func NewHealth

func NewHealth() Health

NewHealth starts an empty healthcheck.

func (Health) CMD

func (h Health) CMD(args ...string) Health

CMD sets a CMD healthcheck (exec form).

func (Health) CMDShell

func (h Health) CMDShell(cmd string) Health

CMDShell sets a CMD-SHELL healthcheck.

func (Health) Interval

func (h Health) Interval(seconds int) Health

Interval sets the healthcheck interval in seconds.

func (Health) IntervalD

func (h Health) IntervalD(d string) Health

IntervalD sets the healthcheck interval from a duration string ("10s").

func (Health) None

func (h Health) None() Health

None disables the healthcheck (HEALTHCHECK NONE).

func (Health) Retries

func (h Health) Retries(n int) Health

Retries sets the number of consecutive failures needed to mark the container unhealthy.

func (Health) StartPeriod

func (h Health) StartPeriod(seconds int) Health

StartPeriod sets the start-period in seconds.

func (Health) StartPeriodD

func (h Health) StartPeriodD(d string) Health

StartPeriodD sets the start-period from a duration string ("0s").

func (Health) Test

func (h Health) Test(args ...string) Health

Test sets the healthcheck command, including the CMD / CMD-SHELL / NONE prefix.

func (Health) Timeout

func (h Health) Timeout(seconds int) Health

Timeout sets the healthcheck timeout in seconds.

func (Health) TimeoutD

func (h Health) TimeoutD(d string) Health

TimeoutD sets the healthcheck timeout from a duration string ("5s").

type IPAMPool

type IPAMPool struct {
	Subnet             string
	Gateway            string
	IPRange            string
	AuxiliaryAddresses map[string]string
}

IPAMPool is a project network IPAM pool.

type ImageOptions

type ImageOptions struct {
	Subpath string
}

ImageOptions are options for an image mount.

type Images

type Images struct {
	Format string // table | json
	Quiet  bool

	Writer       io.Writer
	Profiles     []string
	ServiceNames []string
}

Images is the options for the compose images command.

type Job

type Job struct {
	Profiles []string
	Manual   *bool
	Schedule []JobSchedule
}

Job is the trigger and profile configuration for a Compose job.

type JobSchedule

type JobSchedule struct {
	Cron        string
	Timezone    string
	Concurrency string
	MissedFires string
}

JobSchedule is one cron trigger for a Compose job.

type Kill

type Kill struct {
	Signal        *string
	RemoveOrphans bool

	Writer       io.Writer
	Profiles     []string
	ServiceNames []string
}

Kill is the options for the compose kill command

type Logs

type Logs struct {
	Tail        *int
	Follow      bool
	Index       *int
	NoColor     bool
	NoLogPrefix bool
	Since       string
	Timestamps  bool
	Until       string

	Writer       io.Writer
	Profiles     []string
	ServiceNames []string
}

Logs is the options for the compose logs command

type Ls

type Ls struct {
	All    bool
	Filter []string
	Format string
	Quiet  bool

	Writer   io.Writer
	Profiles []string
}

Ls is the options for the compose ls command (lists Compose projects on the engine).

type Model

type Model struct {
	Model        string
	ContextSize  int
	RuntimeFlags []string
}

Model is a Compose model definition.

type Mount

type Mount struct {
	Source      string
	Target      string
	Type        types.MountType
	ReadOnly    bool
	Consistency types.MountConsistency

	Bind   *BindOptions
	Volume *VolumeOptions
	Tmpfs  *TmpfsOptions
	Image  *ImageOptions
}

Mount describes one mount. Empty Type is bind, unless Volume, Tmpfs, or Image is set.

type Pause

type Pause struct {
	Writer       io.Writer
	Profiles     []string
	ServiceNames []string
}

Pause is the options for the compose pause command.

type Port

type Port struct {
	Index    *int
	Protocol string // tcp | udp

	Writer      io.Writer
	Profiles    []string
	Service     string // required
	PrivatePort int    // required
}

Port is the options for the compose port command. Service and PrivatePort are required.

type Project

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

Project is a wrapper around types.Project It provides methods to create and manage a docker Compose project.

func NewProject

func NewProject(name string) *Project

NewProject creates a new project with the given name. It initializes the project with an empty service list. The name is used as the project name in the compose file.

func (*Project) Export

func (p *Project) Export(file string, perm os.FileMode) error

Export writes the project as Compose YAML to file.

func (*Project) ForEachService

func (p *Project) ForEachService(fn func(name string, service *types.ServiceConfig) error) error

ForEachService iterates over each service in the project and calls the provided function to provide the ability to mutate a service parameters:

  • fn: the function to call for each service

returns an error if the function returns an error

func (*Project) GetService

func (p *Project) GetService(name string) (*types.ServiceConfig, error)

GetService returns a service from the project parameters:

  • name: the name of the service

returns the service and an error if the service is not found or the project has no services

func (*Project) Marshal

func (p *Project) Marshal() ([]byte, error)

Marshal marshals the project to a yaml bytes slice

func (*Project) Print

func (p *Project) Print() error

Print writes the project as Compose YAML to stdout.

func (*Project) ServiceLabel

func (p *Project) ServiceLabel(key, value string) *Project

ServiceLabel sets a label on every service that does not already have key. Empty key or value is ignored. Labels added after WithService still reach Compose Up; mutating the original *Container does not.

func (*Project) Unwrap

func (p *Project) Unwrap() *types.Project

Unwrap returns the underlying types.Project

func (*Project) Validate

func (p *Project) Validate() error

Validate validates the project returns an error if the project has errors

func (*Project) WithJob

func (p *Project) WithJob(name string, service *Container, job Job) *Project

WithJob defines a Compose job from a container spec. Deploy and develop extras are service-only.

func (*Project) WithModel

func (p *Project) WithModel(name string, model Model) *Project

WithModel defines a project-level model.

func (*Project) WithNetwork

func (p *Project) WithNetwork(name string, spec ...ProjectNetwork) *Project

WithNetwork defines a project network. spec is optional and at most one value.

func (*Project) WithSecret

func (p *Project) WithSecret(key string, spec ...ProjectSecret) *Project

WithSecret defines a new secret in the project

func (*Project) WithService

func (p *Project) WithService(service *Service) *Project

WithService adds a service to the project.

func (*Project) WithVolume

func (p *Project) WithVolume(name string, spec ...ProjectVolume) *Project

WithVolume defines a new volume in the project parameters:

  • name: the name of the volume
  • volume: the volume to create the volume from

func (*Project) WriteTo

func (p *Project) WriteTo(w io.Writer) (int64, error)

WriteTo writes the project as Compose YAML to w.

type ProjectLoad

type ProjectLoad struct {
	Name               string
	Files              []string
	WorkingDir         string
	EnvFiles           []string
	Profiles           []string
	Services           []string
	Offline            bool
	AllResources       bool
	Compatibility      bool
	InsecureRegistries []string
	OnUnsupported      func([]UnsupportedAttribute)

	Writer io.Writer
}

ProjectLoad is the options for loading a Compose project from files.

type ProjectNetwork

type ProjectNetwork struct {
	Driver        string
	DriverOptions map[string]string
	Internal      bool
	Attachable    bool
	EnableIPv6    bool
	Labels        map[string]string
	IPAMDriver    string
	IPAMPools     []IPAMPool
}

ProjectNetwork is extra config for Project.WithNetwork.

type ProjectSecret

type ProjectSecret struct {
	Name           string
	File           string
	Content        string
	Environment    string
	External       bool
	Driver         string
	DriverOptions  map[string]string
	TemplateDriver string
}

ProjectSecret is extra config for Project.WithSecret.

type ProjectVolume

type ProjectVolume struct {
	Driver        string
	DriverOptions map[string]string
	Labels        map[string]string
}

ProjectVolume is extra config for Project.WithVolume.

type Ps

type Ps struct {
	All          bool
	Filter       []string // e.g. "status=running"
	Format       string
	NoTrunc      bool
	Orphans      *bool // nil = default (true); false = --no-orphans
	Quiet        bool
	Services     bool // --services: display services
	Status       string
	Writer       io.Writer
	Profiles     []string
	ServiceNames []string
}

Ps is the options for the compose ps command

type Publish

type Publish struct {
	App                 bool
	OCIVersion          string
	ResolveImageDigests bool
	InsecureRegistry    bool
	WithEnv             bool
	Yes                 bool

	Writer     io.Writer
	Profiles   []string
	Repository string // required REPOSITORY[:TAG]
}

Publish is the options for the compose publish command. Repository is required.

type Pull

type Pull struct {
	IgnoreBuildable    bool
	IgnorePullFailures bool
	IncludeDeps        bool
	Policy             string // e.g. "missing", "always", "never"
	Quiet              bool
	Writer             io.Writer
	Profiles           []string
	ServiceNames       []string
}

Pull is the options for the compose pull command

type Push

type Push struct {
	IgnorePushFailures bool
	IncludeDeps        bool
	Quiet              bool

	Writer       io.Writer
	Profiles     []string
	ServiceNames []string
}

Push is the options for the compose push command.

type Restart

type Restart struct {
	NoDeps       bool
	Timeout      *int
	Writer       io.Writer
	Profiles     []string
	ServiceNames []string
}

Restart is the options for the compose restart command

type Rm

type Rm struct {
	Force   bool
	Stop    bool
	Volumes bool

	Writer       io.Writer
	Profiles     []string
	ServiceNames []string
}

Rm is the options for the compose rm command.

type Run

type Run struct {
	Build         bool
	CapAdd        []string
	CapDrop       []string
	Detach        bool
	Entrypoint    string
	Env           []string
	EnvFromFile   []string
	Interactive   *bool // nil = Compose default (true)
	Label         []string
	Name          string
	NoDeps        bool
	NoTTY         bool
	Pull          string
	Quiet         bool
	QuietBuild    bool
	QuietPull     bool
	RemoveOrphans bool
	IgnoreOrphans bool
	Rm            bool
	UseAliases    bool
	User          string
	Workdir       string

	Writer   io.Writer
	Stdin    io.Reader
	Profiles []string
	Service  string   // required
	Command  []string // optional
}

Run is the options for the compose run command. Service is required. Command is optional (defaults to the service command).

type RunOpts

type RunOpts struct {
	Mount    []string
	Network  string
	Security string
}

RunOpts are BuildKit flags on a RUN instruction. Setting any flag starts a new RUN. Later Run calls with empty options still fold into that instruction.

type Scale

type Scale struct {
	NoDeps   bool
	Replicas []UpScale

	Writer   io.Writer
	Profiles []string
}

Scale is the options for the compose scale command. Replicas is required (at least one SERVICE=NUM).

type Service

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

Service is a Compose service: a container plus the settings that exist only on a service.

func NewService

func NewService(name string, container *Container) *Service

NewService returns a service named name using the container as its runtime config.

func (*Service) Annotation

func (s *Service) Annotation(key, value string) *Service

Annotation sets a service annotation.

func (*Service) Build

func (s *Service) Build(build Build) *Service

Build sets the service build spec. A later Build call is applied after earlier ones.

func (*Service) DependsOn

func (s *Service) DependsOn(name string) *Service

DependsOn marks the service as depending on another (condition: started).

func (*Service) DependsOnHealthy

func (s *Service) DependsOnHealthy(name string) *Service

DependsOnHealthy marks the service as depending on another becoming healthy.

func (*Service) Deploy

func (s *Service) Deploy(deploy Deploy) *Service

Deploy sets Compose deploy configuration.

func (*Service) Develop

func (s *Service) Develop(watch Develop) *Service

Develop sets Compose watch/develop config.

func (*Service) Dockerfile

func (s *Service) Dockerfile(file DockerFile) *Service

Dockerfile sets the service's inline Dockerfile directly without needing NewBuild.

func (*Service) EnvFile

func (s *Service) EnvFile(path string) *Service

EnvFile adds a required env file to the service.

func (*Service) Model

func (s *Service) Model(name, endpointVar, modelVar string) *Service

Model binds a project model to the service.

func (*Service) NoAttach

func (s *Service) NoAttach() *Service

NoAttach sets attach to false for the service.

func (*Service) PreStart

func (s *Service) PreStart(ctr *Container, perReplica bool) *Service

PreStart adds a run-to-completion hook that runs before the service starts.

func (*Service) Profiles

func (s *Service) Profiles(profiles ...string) *Service

Profiles assigns Compose profiles to the service.

func (*Service) Secret

func (s *Service) Secret(secret ServiceSecret) *Service

Secret adds a service-level secret reference.

type ServiceSecret

type ServiceSecret struct {
	Source string
	Target string
	UID    string
	GID    string
	Mode   *int64
}

ServiceSecret is a service-level secret reference.

func (ServiceSecret) Apply

type Start

type Start struct {
	Wait         bool
	WaitTimeout  *int
	Writer       io.Writer
	Profiles     []string
	ServiceNames []string
}

Start is the options for the compose start command

type Stats

type Stats struct {
	All      bool
	Format   string
	NoStream bool
	NoTrunc  bool

	Writer       io.Writer
	Profiles     []string
	ServiceNames []string
}

Stats is the options for the compose stats command.

type Stop

type Stop struct {
	Timeout      *int
	Writer       io.Writer
	Profiles     []string
	ServiceNames []string
}

Stop is the options for the compose stop command

type TmpfsOptions

type TmpfsOptions struct {
	SizeBytes int64
	Mode      os.FileMode
	Options   [][]string
}

TmpfsOptions are options for a tmpfs mount.

type Top

type Top struct {
	Writer       io.Writer
	Profiles     []string
	ServiceNames []string
}

Top is the options for the compose top command.

type Unpause

type Unpause struct {
	Writer       io.Writer
	Profiles     []string
	ServiceNames []string
}

Unpause is the options for the compose unpause command.

type UnsupportedAttribute

type UnsupportedAttribute struct {
	Service string
	Path    string
	Reason  string
}

UnsupportedAttribute is a compose-file attribute the schema accepts and this runtime does not apply outside Swarm.

type Up

type Up struct {
	Detach                  bool
	AbortOnContainerExit    bool
	AbortOnContainerFailure bool
	AlwaysRecreateDeps      bool
	Attach                  *string
	AttachDependencies      bool
	Build                   bool
	NoBuild                 bool
	ForceRecreate           bool
	Menu                    bool
	ExitCodeFrom            *string
	NoAttach                *string
	NoColor                 bool
	NoDeps                  bool
	NoLogPrefix             bool
	NoRecreate              bool
	Pull                    *string
	NoStart                 bool
	QuietPull               bool
	RemoveOrphans           bool
	IgnoreOrphans           bool
	RenewAnonVolumes        bool
	Scale                   []UpScale
	Timeout                 *int
	Timestamps              bool
	Wait                    bool
	WaitTimeout             *int
	Watch                   bool
	Yes                     bool

	Profiles     []string
	Writer       io.Writer
	ServiceNames []string
}

Up is the options for the compose up command

type UpScale

type UpScale struct {
	Service string
	Num     int
}

UpScale is the scale for the compose up command

type Version

type Version struct {
	Format string // pretty | json
	Short  bool

	Writer   io.Writer
	Profiles []string
}

Version is the options for the compose version command.

type Viz

type Viz struct {
	Networks        bool
	Ports           bool
	Image           bool
	IndentationSize *int // default 1
	Spaces          bool

	Writer   io.Writer
	Profiles []string
}

Viz is the options for compose alpha viz.

type VolumeOptions

type VolumeOptions struct {
	NoCopy        bool
	Labels        map[string]string
	Subpath       string
	Driver        string
	DriverOptions map[string]string
}

VolumeOptions are options for a named volume mount.

type Volumes

type Volumes struct {
	Format string
	Quiet  bool

	Writer       io.Writer
	Profiles     []string
	ServiceNames []string
}

Volumes is the options for the compose volumes command.

type Wait

type Wait struct {
	DownProject bool

	Writer       io.Writer
	Profiles     []string
	ServiceNames []string // required
}

Wait is the options for the compose wait command. ServiceNames is required.

type Watch

type Watch struct {
	NoUp    bool
	NoPrune bool // --prune=false; Compose defaults to true
	Quiet   bool

	Writer       io.Writer
	Profiles     []string
	ServiceNames []string
}

Watch is the options for the compose watch command.

type WatchAction

type WatchAction string

WatchAction is a Compose develop watch action.

const (
	WatchActionSync        WatchAction = "sync"
	WatchActionRebuild     WatchAction = "rebuild"
	WatchActionSyncRestart WatchAction = "sync+restart"
)

Directories

Path Synopsis
Package types holds Docker Engine and Compose SDK wrappers used by kit.
Package types holds Docker Engine and Compose SDK wrappers used by kit.

Jump to

Keyboard shortcuts

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