Documentation
¶
Overview ¶
Package api is the contract between the Compose engine and the programs that drive it: the compose CLI, and any third-party software using Compose as a library (see Compose).
Zero values ¶
An option struct left at its zero value does NOT always behave like the matching `docker compose` command run without flags: the CLI fills in some defaults before calling the API. The fields where the difference matters are listed here; each one is also documented on the field itself.
- CreateOptions.Inherit: false recreates the anonymous volumes of recreated containers, as `up --renew-anon-volumes` does for them (the flag also forces the recreation of every container). The CLI default is to retrieve their data from the previous container (Inherit: true).
- CreateOptions.Recreate and RecreateDependencies: the empty string means RecreateDiverged. Any value other than the Recreate* constants is rejected by CreateOptions.Validate before anything is changed.
- CreateOptions.RemoveOrphans and IgnoreOrphans: when both are false, orphan containers are kept and a warning is logged. IgnoreOrphans silences that warning, RemoveOrphans removes the containers.
- Timeout, on every options struct that has one: nil leaves the choice to the engine, which applies the stop timeout of the container (the service's stop_grace_period) or its own default.
- StartOptions.WaitTimeout: 0 means no time limit on dependency waits.
- StartOptions.Attach: nil selects the detached mode of Up, a non-nil consumer selects the interactive session, which StartOptions.Wait ends once the services are running or healthy. See UpOptions.Validate for the options that only make sense in one of the two modes.
- Project, on the options of operations that take a project name: for Start, Stop, Restart, Kill and Down, nil means the project is rebuilt from the labels of its containers. Pause and Logs only use it to narrow the services; Remove does too, and forwards it to Stop when Stop is set (nil then means the same rebuild). Ps and Attach ignore it.
- Services, when empty: every service of the project, subject to what the field documents (in some options it is not a filter).
- DownOptions.Images: the zero value, ImagePruneNone, keeps every image.
Replica selection ¶
The Index field of the options of exec, port, export, commit, attach, logs and cp selects a replica by its container number, starting at 1. Index 0 means "no particular replica", and what that gives depends on the operation:
- exec, port, export, commit and attach act on one container: the one with the lowest number, one-off containers coming last;
- logs reads the containers of every selected service, one-off containers excluded;
- cp copies from the first container of the service, or to every container of the service when copying to it. One-off containers are excluded unless All is set, and All only applies when Index is 0: a given replica is looked up among the regular containers.
The word All ¶
The boolean All field has a different meaning in each options struct, and is always documented there:
- ListOptions: takes stopped containers into account, so that a project whose containers are all stopped is listed;
- PsOptions: includes the stopped containers and the one-off ones;
- KillOptions: also targets the containers that are not running (the one-off ones are targeted either way);
- CopyOptions: includes the one-off containers of the service;
- ProjectLoadOptions: includes the resources no service uses.
Index ¶
- Constants
- Variables
- func GetDependentImages(service types.ServiceConfig, projectName string) []string
- func GetImageNameOrDefault(service types.ServiceConfig, projectName string) string
- func IsAlreadyExistsError(err error) booldeprecated
- func IsErrCanceled(err error) bool
- func IsErrIncompatibleOptions(err error) bool
- func IsErrInvalidOption(err error) bool
- func IsErrNotImplemented(err error) bool
- func IsErrNotRunning(err error) bool
- func IsErrParsingFailed(err error) bool
- func IsErrUnsupportedFlag(err error) booldeprecated
- func IsForbiddenError(err error) booldeprecated
- func IsNotFoundError(err error) bool
- func IsUnknownError(err error) booldeprecated
- type AttachOptions
- type BuildOptions
- type Cascade
- type CommitOptions
- type Compose
- type ConfigOptionsdeprecated
- type ContainerEvent
- type ContainerEventListener
- type ContainerProcSummary
- type ContainerSummary
- type ContextInfo
- type CopyOptions
- type CreateOptions
- type DownOptions
- type Event
- type EventProcessor
- type EventStatus
- type EventsOptions
- type ExportOptions
- type Feature
- type GenerateOptions
- type ImageManager
- type ImagePruneMode
- type ImageSummary
- type ImagesOptions
- type IncompatibleOptionsError
- type Inspector
- type InvalidOptionError
- type KillOptions
- type Lifecycle
- type ListOptions
- type LoadListener
- type LogConsumer
- type LogOptions
- type OCIOptions
- type OCIVersion
- type PauseOptions
- type PortOptions
- type PortPublisher
- type PortPublishers
- type ProjectLoadOptions
- type ProjectLoader
- type PsOptions
- type PublishOptions
- type PullOptions
- type PushOptions
- type RemoveOptions
- type Resource
- type RestartOptions
- type RunOptions
- type Runner
- type ScaleOptions
- type ServiceNotRunningError
- type ServiceStatusdeprecated
- type Stack
- type StartOptions
- type StopOptions
- type UnsupportedAttribute
- type UpOptions
- type VizOptions
- type VolumesOptions
- type VolumesSummary
- type WaitOptions
- type WatchOptions
- type Watcher
Constants ¶
const ( // STARTING indicates that stack is being deployed // // Deprecated: Stack.Status never takes this value, it will be removed. STARTING string = "Starting" // RUNNING indicates that stack is deployed and services are running // // Deprecated: Stack.Status never takes this value, it will be removed. RUNNING string = "Running" // UPDATING indicates that some stack resources are being recreated // // Deprecated: Stack.Status never takes this value, it will be removed. UPDATING string = "Updating" // REMOVING indicates that stack is being deleted // // Deprecated: Stack.Status never takes this value, it will be removed. REMOVING string = "Removing" // UNKNOWN indicates unknown stack state // // Deprecated: Stack.Status never takes this value, it will be removed. UNKNOWN string = "Unknown" // FAILED indicates that stack deployment failed // // Deprecated: Stack.Status never takes this value, it will be removed. FAILED string = "Failed" )
const ( // RecreateDiverged to recreate services which configuration diverges from compose model RecreateDiverged = "diverged" // RecreateForce to force service container being recreated RecreateForce = "force" // RecreateNever to never recreate existing service containers RecreateNever = "never" )
const ( // ContainerEventLog is a ContainerEvent of type log on stdout. Line is set ContainerEventLog = iota // ContainerEventErr is a ContainerEvent of type log on stderr. Line is set ContainerEventErr // ContainerEventStarted let consumer know a container has been started ContainerEventStarted // ContainerEventRestarted let consumer know a container has been restarted ContainerEventRestarted // ContainerEventStopped is a ContainerEvent of type stopped. ContainerEventStopped // ContainerEventCreated let consumer know a new container has been created ContainerEventCreated // ContainerEventRecreated let consumer know container stopped but his being replaced ContainerEventRecreated // ContainerEventExited is a ContainerEvent of type exit. ExitCode is set ContainerEventExited // UserCancel user canceled compose up, we are stopping containers HookEventLog )
const ( StatusError = "Error" StatusCreating = "Creating" StatusStarting = "Starting" StatusStarted = "Started" StatusWaiting = "Waiting" StatusHealthy = "Healthy" StatusExited = "Exited" StatusRestarting = "Restarting" StatusRestarted = "Restarted" StatusRunning = "Running" StatusCreated = "Created" StatusStopping = "Stopping" StatusStopped = "Stopped" StatusKilling = "Killing" StatusKilled = "Killed" StatusRemoving = "Removing" StatusRemoved = "Removed" StatusBuilding = "Building" StatusBuilt = "Built" StatusPulling = "Pulling" StatusPulled = "Pulled" StatusCommitting = "Committing" StatusCommitted = "Committed" StatusCopying = "Copying" StatusCopied = "Copied" StatusExporting = "Exporting" StatusExported = "Exported" StatusDownloading = "Downloading" StatusDownloadComplete = "Download complete" StatusConfiguring = "Configuring" StatusConfigured = "Configured" )
const ( // ProjectLabel allow to track resource related to a compose project ProjectLabel = "com.docker.compose.project" // ServiceLabel allow to track resource related to a compose service ServiceLabel = "com.docker.compose.service" // ConfigHashLabel stores configuration hash for a compose service ConfigHashLabel = "com.docker.compose.config-hash" // ContainerNumberLabel stores the container index of a replicated service ContainerNumberLabel = "com.docker.compose.container-number" // VolumeLabel allow to track resource related to a compose volume VolumeLabel = "com.docker.compose.volume" // NetworkLabel allow to track resource related to a compose network NetworkLabel = "com.docker.compose.network" // WorkingDirLabel stores absolute path to compose project working directory WorkingDirLabel = "com.docker.compose.project.working_dir" // ConfigFilesLabel stores absolute path to compose project configuration files ConfigFilesLabel = "com.docker.compose.project.config_files" // EnvironmentFileLabel stores absolute path to compose project env file set by `--env-file` EnvironmentFileLabel = "com.docker.compose.project.environment_file" // OneoffLabel stores value 'True' for one-off containers created by `compose run` OneoffLabel = "com.docker.compose.oneoff" // RelayLabel marks the network relay container compose deploys in place // of a provider-managed service (see the publish-endpoint provider // message). Its value is a hash of the relay's routes, used to decide // whether an existing relay can be kept on the next up. Commands that // act on a service's process (exec, ...) refuse relay containers. RelayLabel = "com.docker.compose.relay" // RelayNetworkLabel marks the dedicated bridge network created for one // provider-managed service's relay link — the sole channel between the // relay container and the provider's own runtime (see get-relay-info). // Never a project's user-declared network, and never joined by any // dependent or sibling container: only the relay connects to it. That is // isolation by network membership: the gateway is a host address, so a // provider must also pin its bind to the bridge's interface to keep other // local containers from reaching it by IP. RelayNetworkLabel = "com.docker.compose.relay-network" // SlugLabel stores unique slug used for one-off container identity SlugLabel = "com.docker.compose.slug" // ImageDigestLabel stores digest of the container image used to run service ImageDigestLabel = "com.docker.compose.image" // ImageVolumeDigestLabel stores the content digest of each `type: image` // volume's source image, as "target=digest" pairs joined by ",", so // mustRecreate can detect a rebuilt/updated source image independently of // the mount Source (which must stay a resolvable name, not a digest). ImageVolumeDigestLabel = "com.docker.compose.image-volume-digest" // DependenciesLabel stores service dependencies DependenciesLabel = "com.docker.compose.depends_on" // VersionLabel stores the compose tool version used to build/run application VersionLabel = "com.docker.compose.version" // ImageBuilderLabel stores the builder (classic or BuildKit) used to produce the image. ImageBuilderLabel = "com.docker.compose.image.builder" // ContainerReplaceLabel is set when container is created to replace another container (recreated) ContainerReplaceLabel = "com.docker.compose.replace" // ContainerEngineLabel stores the name of the engine that runs the container ContainerEngineLabel = "com.docker.compose.engine" // HookLabel identifies an ephemeral lifecycle-hook container and stores the // hook type, e.g. "pre_start". It is applied to every runner container // created by createPreStartContainer so stale runners from a previous // failed run can be found and removed by project+service+hook label // filters, and down can sweep them all by project+hook label. HookLabel = "com.docker.compose.hook" // HookIndexLabel stores the position of the hook in its service's hook // list (e.g. pre_start[2] → "2"), so the start phase can match each // declared hook with the runner container the reconciliation plan // prepared for it. HookIndexLabel = "com.docker.compose.hook-index" // JobLabel allow to track resource related to a compose job JobLabel = "com.docker.compose.job" )
const ComposeCompatibility = "COMPOSE_COMPATIBILITY"
ComposeCompatibility try to mimic compose v1 as much as possible
const ( // ExitCodeLoginRequired exit code when command cannot execute because it requires cloud login // This will be used by VSCode to detect when creating context if the user needs to login first // // Deprecated: Compose has no cloud login anymore and never exits with this code, it will be removed. ExitCodeLoginRequired = 5 )
const ResourceCompose = "Compose"
ResourceCompose is a special resource ID used when event applies to all resources in the application
const WatchLogger = "#watch"
WatchLogger is a reserved name to log watch events
Variables ¶
var ( // ErrNotFound is returned when an object is not found ErrNotFound = errors.New("not found") // ErrAlreadyExists is returned when an object already exists // // Deprecated: Compose never returns it, it will be removed. ErrAlreadyExists = errors.New("already exists") // ErrForbidden is returned when an operation is not permitted // // Deprecated: Compose never returns it, it will be removed. ErrForbidden = errors.New("forbidden") // ErrUnknown is returned when the error type is unmapped // // Deprecated: Compose never returns it, it will be removed. ErrUnknown = errors.New("unknown") // ErrNotImplemented is returned when a backend doesn't implement an action ErrNotImplemented = errors.New("not implemented") // ErrUnsupportedFlag is returned when a backend doesn't support a flag // // Deprecated: Compose never returns it, it will be removed. ErrUnsupportedFlag = errors.New("unsupported flag") // ErrCanceled is returned when the command was canceled by user ErrCanceled = errors.New("canceled") // ErrParsingFailed is returned when a string cannot be parsed ErrParsingFailed = errors.New("parsing failed") // ErrNoResources is returned when operation didn't selected any resource ErrNoResources = errors.New("no resources") // ErrIncompatibleOptions is returned when a set of options that cannot be // honored together is requested. See IncompatibleOptionsError. ErrIncompatibleOptions = errors.New("incompatible options") // ErrNotRunning is returned when an operation targets a service, or a // replica of it, that has no running container. See ServiceNotRunningError. ErrNotRunning = errors.New("not running") // ErrInvalidOption is returned when an option is set to a value it does // not accept. See InvalidOptionError. ErrInvalidOption = errors.New("invalid option") // ErrJobsNotSupported is returned when a job operation requires an engine with usable jobs support (the jobs API and its extension enabled) ErrJobsNotSupported = errors.New("jobs are not supported by the engine") )
var ComposeVersion string
ComposeVersion is the compose tool version as declared by label VersionLabel
var Separator = "-"
Separator is used for naming components
Functions ¶
func GetDependentImages ¶ added in v5.4.0
func GetDependentImages(service types.ServiceConfig, projectName string) []string
GetDependentImages returns the additional images a service depends on beyond its main image. Currently this is the set of pre_start hook images, which run as ephemeral init containers with their own image. A hook without an explicit image, or one reusing the service image, is skipped as that image is already accounted for as the service image.
func GetImageNameOrDefault ¶
func GetImageNameOrDefault(service types.ServiceConfig, projectName string) string
GetImageNameOrDefault computes the default image name for a service, used to tag built images
func IsAlreadyExistsError
deprecated
func IsErrCanceled ¶
IsErrCanceled returns true if the unwrapped error is ErrCanceled
func IsErrIncompatibleOptions ¶ added in v5.7.0
IsErrIncompatibleOptions returns true if the unwrapped error is ErrIncompatibleOptions
func IsErrInvalidOption ¶ added in v5.7.2
IsErrInvalidOption returns true if the unwrapped error is ErrInvalidOption
func IsErrNotImplemented ¶
IsErrNotImplemented returns true if the unwrapped error is ErrNotImplemented
func IsErrNotRunning ¶ added in v5.7.2
IsErrNotRunning returns true if the unwrapped error is ErrNotRunning
func IsErrParsingFailed ¶
IsErrParsingFailed returns true if the unwrapped error is ErrParsingFailed
func IsErrUnsupportedFlag
deprecated
func IsForbiddenError
deprecated
func IsNotFoundError ¶
IsNotFoundError returns true if the unwrapped error is ErrNotFound
func IsUnknownError
deprecated
Types ¶
type AttachOptions ¶
type AttachOptions struct {
Project *types.Project
Service string
Index int
DetachKeys string
NoStdin bool
Proxy bool
}
AttachOptions group options of the Attach API
type BuildOptions ¶
type BuildOptions struct {
// Pull always attempt to pull a newer version of the image
Pull bool
// Push pushes service images
Push bool
// Progress set type of progress output ("auto", "plain", "tty")
Progress string
// Args set build-time args
Args types.MappingWithEquals
// NoCache disables cache use
NoCache bool
// Quiet make the build process not output to the console
Quiet bool
// Services passed in the command line to be built
Services []string
// Deps also build selected services dependencies
Deps bool
// Ssh authentications passed in the command line
SSHs []types.SSHKey
// Memory limit for the build container
Memory int64
// Builder name passed in the command line
Builder string
// Print don't actually run builder but print equivalent build config
Print bool
// Check let builder validate build configuration
Check bool
// Attestations enables attestation generation
Attestations bool
// Provenance generate a provenance attestation
Provenance string
// SBOM generate a SBOM attestation
SBOM string
// Out is the stream to write build progress
Out io.Writer
}
BuildOptions group options of the Build API
type CommitOptions ¶
type CommitOptions struct {
Service string
Reference string
Pause bool
Comment string
Author string
Changes opts.ListOpts
Index int
}
CommitOptions group options of the Commit API
type Compose ¶
type Compose interface {
Lifecycle
Inspector
ImageManager
Runner
Watcher
ProjectLoader
}
Compose is the API interface one can use to programmatically use docker/compose in a third-party software Use [compose.NewComposeService] to get an actual instance
Methods act on the whole *types.Project they receive: to scope an operation to a subset of services, narrow the project itself before calling — at load time through ProjectLoadOptions.Services, or with types.Project.WithSelectedServices. The Services fields found on some option structs are not filters: they mark the services the user explicitly named, and only drive side concerns (recreation policy, log scoping) as documented on each field.
type ConfigOptions
deprecated
type ConfigOptions struct {
// Format define the output format used to dump converted application model (json|yaml)
Format string
// Output defines the path to save the application model
Output string
// Resolve image reference to digests
ResolveImageDigests bool
}
ConfigOptions group options of the Config API
Deprecated: no operation of Compose takes these options, they will be removed.
type ContainerEvent ¶
type ContainerEvent struct {
Type int
Time int64
Container *ContainerSummary
// Source is the name of the container _without the project prefix_.
//
// This is only suitable for display purposes within Compose, as it's
// not guaranteed to be unique across services.
Source string
ID string
Service string
Line string
// ExitCode is only set on ContainerEventExited events
ExitCode int
Restarting bool
}
ContainerEvent notify an event has been collected on source container implementing Service
type ContainerEventListener ¶
type ContainerEventListener func(event ContainerEvent)
ContainerEventListener is a callback to process ContainerEvent from services
type ContainerProcSummary ¶
type ContainerProcSummary struct {
ID string
Name string
Processes [][]string
Titles []string
Service string
Replica string
}
ContainerProcSummary holds container processes top data
type ContainerSummary ¶
type ContainerSummary struct {
ID string
Name string
Names []string
Image string
Command string
Project string
Service string
Created int64
State container.ContainerState
Status string
Health container.HealthStatus
ExitCode int
Publishers PortPublishers
Labels map[string]string
SizeRw int64 `json:",omitempty"`
SizeRootFs int64 `json:",omitempty"`
Mounts []string
Networks []string
LocalVolumes int
}
ContainerSummary hold high-level description of a container
type ContextInfo ¶
type ContextInfo interface {
// CurrentContext returns the name of the current Docker context
// Returns "default" for simple clients without context support
CurrentContext() string
// ServerOSType returns the Docker daemon's operating system (linux/windows/darwin)
// Used for OS-specific compatibility checks
ServerOSType() string
// BuildKitEnabled determines whether BuildKit should be used for builds
// Checks DOCKER_BUILDKIT env var, config, and daemon capabilities
BuildKitEnabled() (bool, error)
}
ContextInfo provides Docker context information for advanced scenarios
type CopyOptions ¶
type CopyOptions struct {
Source string
Destination string
// All includes the one-off containers of the service
All bool
Index int
FollowLink bool
CopyUIDGID bool
}
CopyOptions group options of the cp API
type CreateOptions ¶
type CreateOptions struct {
Build *BuildOptions
// Services names the services the user explicitly targeted. It does NOT
// restrict what gets created — the whole project converges; narrow the
// project instead. Targeted services follow the Recreate policy, the
// others follow RecreateDependencies. Empty means every service is
// targeted.
Services []string
// Remove legacy containers for services that are not defined in the project
RemoveOrphans bool
// Ignore legacy containers for services that are not defined in the project
IgnoreOrphans bool
// Recreate define the strategy to apply on existing containers: one of
// RecreateDiverged (the default, also used for ""), RecreateForce or
// RecreateNever. Any other value is rejected by Validate.
Recreate string
// RecreateDependencies define the strategy to apply on dependencies
// services, with the same values as Recreate.
RecreateDependencies string
// Inherit reuse anonymous volumes from previous container. Beware that
// the zero value (false) recreates the anonymous volumes of the containers
// that get recreated, like `up --renew-anon-volumes` does for them: set it
// to true to get what the CLI does by default.
Inherit bool
// Timeout set delay to wait for container to gracefully stop before sending SIGKILL
Timeout *time.Duration
// QuietPull makes the pulling process quiet
QuietPull bool
// SkipProviders skips provider services during convergence (e.g. watch rebuild)
SkipProviders bool
}
CreateOptions group options of the Create API
func (CreateOptions) Validate ¶ added in v5.7.2
func (o CreateOptions) Validate() error
Validate checks that the values of the options are among the ones they accept: Recreate and RecreateDependencies must be empty (which means RecreateDiverged) or one of the Recreate* constants. It is a pure function, called by Create and Up before they do anything, and can also be called by integrators to fail early.
It returns nil, or an error matching ErrInvalidOption. With several invalid options, the errors are joined with errors.Join: errors.Is still holds, but errors.As to *InvalidOptionError only yields the first one.
type DownOptions ¶
type DownOptions struct {
// RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
RemoveOrphans bool
// Project is the compose project used to define this app. Might be nil if user ran `down` just with project name
Project *types.Project
// Timeout override container stop timeout
Timeout *time.Duration
// Images removes images used by the services: ImagePruneAll removes
// every project image, ImagePruneLocal only those without a custom tag,
// ImagePruneNone (the zero value) keeps them all. Down rejects any other
// value before touching a single resource.
Images ImagePruneMode
// Volumes remove volumes, both declared in the `volumes` section and anonymous ones
Volumes bool
// Services passed in the command line to be stopped
Services []string
}
DownOptions group options of the Down API
type Event ¶
type Event struct {
Timestamp time.Time
Service string
Container string
Status string
Attributes map[string]string
}
Event is a container runtime event served by Events API
type EventProcessor ¶
type EventProcessor interface {
// Start is triggered as a Compose operation is starting with context
Start(ctx context.Context, operation string)
// On notify about (sub)task and progress processing operation
On(events ...Resource)
// Done is triggered as a Compose operation completed.
// success is true when the operation completed without error; it is false
// when the operation failed, including when it was cancelled (e.g. Ctrl-C).
Done(operation string, success bool)
}
EventProcessor is notified about Compose operations and tasks
Event contract ¶
The event stream is ordered per resource, not globally: operations run concurrently and events of distinct resources interleave freely, but a given resource's events follow a fixed progression. Consumers must key on Resource.ID and must not rely on global ordering.
Typical per-resource progressions (statuses from the Status* constants):
container being created: Creating → Created
container being started: Starting → Started (pre_start/post_start
hooks, when declared, run silently within it)
container being replaced: Recreate → Recreated
container stop/removal: Stopping → Stopped, Removing → Removed
dependency being waited: Waiting → Healthy | Exited
networks and volumes: Creating → Created, Removing → Removed
Any progression can end early with an Error status, or — for optional outcomes such as a dependency declared with required: false — with a Skipped status carrying the reason. Status texts are stable identifiers: tools may match on them.
type EventStatus ¶
type EventStatus int
EventStatus indicates the status of an action
const ( // Working means that the current task is working Working EventStatus = iota // Done means that the current task is done Done // Warning means that the current task has warning Warning // Error means that the current task has errored Error )
type EventsOptions ¶
type EventsOptions struct {
Services []string
Consumer func(event Event) error
Since string
Until string
}
EventsOptions group options of the Events API
type ExportOptions ¶
ExportOptions group options of the Export API
type Feature ¶ added in v5.7.0
Feature is a compose feature that can be started and stopped on demand, e.g. by a command of the interactive menu of `compose up`.
type GenerateOptions ¶
type ImageManager ¶ added in v5.7.0
type ImageManager interface {
// Build executes the equivalent to a `compose build`
Build(ctx context.Context, project *types.Project, options BuildOptions) error
// Push executes the equivalent to a `compose push`
Push(ctx context.Context, project *types.Project, options PushOptions) error
// Pull executes the equivalent of a `compose pull`
Pull(ctx context.Context, project *types.Project, options PullOptions) error
// Publish executes the equivalent to a `compose publish`
Publish(ctx context.Context, project *types.Project, repository string, options PublishOptions) error
}
ImageManager groups the operations on the images of a project: building them and moving them to or from a registry.
type ImagePruneMode ¶ added in v5.7.0
type ImagePruneMode string
ImagePruneMode controls how aggressively `down` removes the images associated with the project.
const ( // ImagePruneNone keeps all project images. ImagePruneNone ImagePruneMode = "" // ImagePruneLocal removes only the images built locally by Compose // (no custom tag). ImagePruneLocal ImagePruneMode = "local" // ImagePruneAll removes every project-associated image, remote ones // included. ImagePruneAll ImagePruneMode = "all" )
func (ImagePruneMode) Valid ¶ added in v5.7.0
func (m ImagePruneMode) Valid() bool
Valid reports whether the mode is one of the declared values.
type ImageSummary ¶
type ImageSummary struct {
ID string
Repository string
Tag string
Platform platforms.Platform
Size int64
Created *time.Time
LastTagTime time.Time
}
ImageSummary holds container image description
type ImagesOptions ¶
type ImagesOptions struct {
Services []string
}
ImagesOptions group options of the Images API
type IncompatibleOptionsError ¶ added in v5.7.0
type IncompatibleOptionsError struct {
// Options names the conflicting option fields, as Go selectors relative to
// the options type that was validated (e.g. "Start.Wait").
Options []string
// Reason explains why the options, as set, cannot be honored together.
Reason string
}
IncompatibleOptionsError reports options, or option values, that were requested together but cannot be honored together. It is returned, before any side effect, by UpOptions.Validate and therefore by Compose.Up.
It matches ErrIncompatibleOptions with errors.Is, and callers needing the details can retrieve it with errors.As:
var incompatible *api.IncompatibleOptionsError
if errors.As(err, &incompatible) {
log.Printf("conflict between %v: %s", incompatible.Options, incompatible.Reason)
}
func (*IncompatibleOptionsError) Error ¶ added in v5.7.0
func (e *IncompatibleOptionsError) Error() string
func (*IncompatibleOptionsError) Unwrap ¶ added in v5.7.0
func (e *IncompatibleOptionsError) Unwrap() error
Unwrap makes errors.Is(err, ErrIncompatibleOptions) hold.
type Inspector ¶ added in v5.7.0
type Inspector interface {
// Ps executes the equivalent to a `compose ps`
Ps(ctx context.Context, projectName string, options PsOptions) ([]ContainerSummary, error)
// List executes the equivalent to a `docker stack ls`
List(ctx context.Context, options ListOptions) ([]Stack, error)
// Top executes the equivalent to a `compose top`
Top(ctx context.Context, projectName string, services []string) ([]ContainerProcSummary, error)
// Ports executes the equivalent to a `compose port`
Ports(ctx context.Context, projectName string, service string, port uint16, options PortOptions) (PortPublishers, error)
// Images executes the equivalent of a `compose images`
Images(ctx context.Context, projectName string, options ImagesOptions) (map[string]ImageSummary, error)
// Volumes executes the equivalent to a `docker volume ls`
Volumes(ctx context.Context, project string, options VolumesOptions) ([]VolumesSummary, error)
// Events executes the equivalent to a `compose events`
Events(ctx context.Context, projectName string, options EventsOptions) error
// Logs executes the equivalent to a `compose logs`
Logs(ctx context.Context, projectName string, consumer LogConsumer, options LogOptions) error
// Viz generates a graphviz graph of the project services
Viz(ctx context.Context, project *types.Project, options VizOptions) (string, error)
}
Inspector groups the read-only operations that report on a project and its resources.
type InvalidOptionError ¶ added in v5.7.2
type InvalidOptionError struct {
// Option names the option field, as a Go selector relative to the options
// type that was validated (e.g. "Recreate").
Option string
// Value is the value that was set.
Value string
// Allowed lists the values the option accepts.
Allowed []string
}
InvalidOptionError reports an option set to a value it does not accept. It is returned, before any side effect, by CreateOptions.Validate and therefore by Compose.Create and Compose.Up.
It matches ErrInvalidOption with errors.Is, and callers needing the details can retrieve it with errors.As.
func (*InvalidOptionError) Error ¶ added in v5.7.2
func (e *InvalidOptionError) Error() string
func (*InvalidOptionError) Unwrap ¶ added in v5.7.2
func (e *InvalidOptionError) Unwrap() error
Unwrap makes errors.Is(err, ErrInvalidOption) hold.
type KillOptions ¶
type KillOptions struct {
// RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
RemoveOrphans bool
// Project is the compose project used to define this app. Might be nil if user ran command just with project name
Project *types.Project
// Services passed in the command line to be killed
Services []string
// Signal to send to containers
Signal string
// All can be set to true to try to kill all found containers, independently of their state
All bool
}
KillOptions group options of the Kill API
type Lifecycle ¶ added in v5.7.0
type Lifecycle interface {
// Create executes the equivalent to a `compose create`
Create(ctx context.Context, project *types.Project, options CreateOptions) error
// Start executes the equivalent to a `compose start`
Start(ctx context.Context, projectName string, options StartOptions) error
// Restart restarts containers
Restart(ctx context.Context, projectName string, options RestartOptions) error
// Stop executes the equivalent to a `compose stop`
Stop(ctx context.Context, projectName string, options StopOptions) error
// Up executes the equivalent to a `compose up`
Up(ctx context.Context, project *types.Project, options UpOptions) error
// Down executes the equivalent to a `compose down`
Down(ctx context.Context, projectName string, options DownOptions) error
// Kill executes the equivalent to a `compose kill`
Kill(ctx context.Context, projectName string, options KillOptions) error
// Pause executes the equivalent to a `compose pause`
Pause(ctx context.Context, projectName string, options PauseOptions) error
// UnPause executes the equivalent to a `compose unpause`
UnPause(ctx context.Context, projectName string, options PauseOptions) error
// Scale sets the number of replicas of the selected services
// (ScaleOptions.Replicas) and converges the project to it, creating,
// removing and starting containers as needed
Scale(ctx context.Context, project *types.Project, options ScaleOptions) error
// Remove executes the equivalent to a `compose rm`
Remove(ctx context.Context, projectName string, options RemoveOptions) error
// Wait blocks until at least one of the services' container exits
Wait(ctx context.Context, projectName string, options WaitOptions) (int64, error)
}
Lifecycle groups the operations that create, run, change and remove a project's resources.
type ListOptions ¶
type ListOptions struct {
// All takes stopped containers into account, so that a project whose
// containers are all stopped is listed
All bool
}
ListOptions group options of the ls API
type LoadListener ¶
LoadListener receives events during project loading. Events include:
- "extends": when a service extends another (metadata: service info)
- "include": when including external compose files (metadata: {"path": StringList})
Multiple listeners can be registered, and all will be notified of events.
type LogConsumer ¶
type LogConsumer interface {
Log(containerName, message string)
Err(containerName, message string)
Status(container, msg string)
}
LogConsumer is a callback to process log messages from services
type LogOptions ¶
type LogOptions struct {
Project *types.Project
Index int
Services []string
Tail string
Since string
Until string
Follow bool
Timestamps bool
}
LogOptions defines optional parameters for the `Log` API
type OCIOptions ¶
type OCIOptions struct {
InsecureRegistries []string
}
type OCIVersion ¶
type OCIVersion string
OCIVersion controls manifest generation to ensure compatibility with different registries.
Currently, this is not exposed as an option to the user – Compose uses OCI 1.0 mode automatically for ECR registries based on domain and OCI 1.1 for all other registries.
There are likely other popular registries that do not support the OCI 1.1 format, so it might make sense to expose this as a CLI flag or see if there's a way to generically probe the registry for support level.
const ( OCIVersion1_0 OCIVersion = "1.0" OCIVersion1_1 OCIVersion = "1.1" )
type PauseOptions ¶
type PauseOptions struct {
// Services passed in the command line to be started
Services []string
// Project is the compose project used to define this app. Might be nil if user ran command just with project name
Project *types.Project
}
PauseOptions group options of the Pause API
type PortOptions ¶
PortOptions group options of the Port API
type PortPublisher ¶
PortPublisher hold status about published port
func (PortPublisher) HostPort ¶ added in v5.6.0
func (p PortPublisher) HostPort() string
HostPort renders the host-side address the port is published on
func (PortPublisher) String ¶ added in v5.6.0
func (p PortPublisher) String() string
type PortPublishers ¶
type PortPublishers []PortPublisher
PortPublishers is a slice of PortPublisher
func (PortPublishers) Less ¶
func (p PortPublishers) Less(i, j int) bool
Less implements sort.Interface
type ProjectLoadOptions ¶
type ProjectLoadOptions struct {
// ProjectName to use, or empty to infer from directory
ProjectName string
// ConfigPaths are paths to compose files
ConfigPaths []string
// WorkingDir is the project directory
WorkingDir string
// EnvFiles are paths to .env files
EnvFiles []string
// Profiles to activate
Profiles []string
// Services narrows the loaded project to the named services and their
// dependencies, and enables the profiles they require (empty = all).
// This is where an operation's scope is decided: the Services fields of
// downstream option structs do not filter.
Services []string
// Offline mode disables remote resource loading
Offline bool
// All includes all resources (not just those used by services)
All bool
// Compatibility enables v1 compatibility mode
Compatibility bool
// ProjectOptionsFns are compose-go project options to apply.
// Use cli.WithInterpolation(false), cli.WithNormalization(false), etc.
// This is optional - pass nil or empty slice to use defaults.
ProjectOptionsFns []cli.ProjectOptionsFn
// LoadListeners receive events during project loading.
// All registered listeners will be notified of events.
// This is optional - pass nil or empty slice if not needed.
LoadListeners []LoadListener
// OnUnsupportedAttribute, when set, is invoked once during loading with
// every compose-file attribute detected as unsupported by this runtime
// outside Swarm mode. Detection only runs when this is set; leave nil to
// skip it entirely (e.g. for name-only project resolution).
OnUnsupportedAttribute func([]UnsupportedAttribute)
OCI OCIOptions
}
ProjectLoadOptions configures how a Compose project should be loaded
type ProjectLoader ¶ added in v5.7.0
type ProjectLoader interface {
// LoadProject loads and validates a Compose project from configuration files.
// Set ProjectLoadOptions.OnUnsupportedAttribute to also be notified of
// compose-file attributes accepted by the schema but not honored by this
// runtime outside Swarm mode.
LoadProject(ctx context.Context, options ProjectLoadOptions) (*types.Project, error)
// Generate generates a Compose Project from existing containers
Generate(ctx context.Context, options GenerateOptions) (*types.Project, error)
}
ProjectLoader groups the operations that obtain a Compose project, from configuration files or from existing containers.
type PsOptions ¶
type PsOptions struct {
Project *types.Project
// All includes the stopped containers and the one-off containers, which
// are both left out by default
All bool
Services []string
}
PsOptions group options of the Ps API
type PublishOptions ¶
type PublishOptions struct {
ResolveImageDigests bool
Application bool
WithEnvironment bool
OCIVersion OCIVersion
// Use plain HTTP to access registry. Should only be used for testing purpose
InsecureRegistry bool
}
PublishOptions group options of the Publish API
type PullOptions ¶
PullOptions group options of the Pull API
type PushOptions ¶
type PushOptions struct {
Quiet bool
IgnoreFailures bool
// IgnoreMissing skips the images that are not available locally instead of failing to push them
IgnoreMissing bool
ImageMandatory bool
}
PushOptions group options of the Push API
type RemoveOptions ¶
type RemoveOptions struct {
// Project is the compose project used to define this app. Might be nil if user ran command just with project name
Project *types.Project
// Stop option passed in the command line
Stop bool
// Volumes remove anonymous volumes
Volumes bool
// Force don't ask to confirm removal
Force bool
// Services passed in the command line to be removed
Services []string
}
RemoveOptions group options of the Remove API
type Resource ¶
type Resource struct {
ID string
ParentID string
Text string
Details string
Status EventStatus
Current int64
Percent int
Total int64
}
Resource represents status change and progress for a compose resource.
func (*Resource) StatusText ¶
type RestartOptions ¶
type RestartOptions struct {
// Project is the compose project used to define this app. Might be nil if user ran command just with project name
Project *types.Project
// Timeout override container restart timeout
Timeout *time.Duration
// Services passed in the command line to be restarted
Services []string
// NoDeps ignores services dependencies
NoDeps bool
}
RestartOptions group options of the Restart API
type RunOptions ¶
type RunOptions struct {
// CreateOptions is embedded, but creating the one-off's dependencies
// only honors Build, IgnoreOrphans, RemoveOrphans, QuietPull, Recreate
// and RecreateDependencies; Inherit is always true, and the other fields
// (Timeout, Services, SkipProviders) are ignored.
CreateOptions
// Project is the compose project used to define this app. Might be nil if user ran command just with project name
Project *types.Project
Name string
Service string
Command []string
Entrypoint []string
Detach bool
AutoRemove bool
Tty bool
Interactive bool
WorkingDir string
User string
Environment []string
CapAdd []string
CapDrop []string
Labels types.Labels
Privileged bool
UseNetworkAliases bool
NoDeps bool
// Index selects the replica to target; only used by Exec.
Index int
}
RunOptions group options of the Run API — and, for historical reasons, of the Exec API, which only honors the exec-relevant subset: Service, Index, Command, Environment, WorkingDir, User, Privileged, Interactive, Tty and Detach.
type Runner ¶ added in v5.7.0
type Runner interface {
// RunOneOffContainer creates a service oneoff container and starts its dependencies
RunOneOffContainer(ctx context.Context, project *types.Project, opts RunOptions) (int, error)
// RunJob triggers a Run of the job on the engine's jobs API, starts its
// dependencies first, streams the logs and returns the Run's exit code
// (124 on timeout, 130 when cancelled). A manual job goes through
// CreateAndRun; a scheduled job is run as `up` or `create` registered it: an
// override in options, or a job the engine does not know, is an error. The job must already be in
// project.Services, the way the CLI materializes it, and options.Service
// must be name. options carries the same CLI overrides RunOneOffContainer
// accepts (User, Command, Entrypoint, WorkingDir, CapAdd/CapDrop,
// Environment, Labels, NoDeps). Name has no effect: the jobs API assigns the
// run container's identity itself. A manual job is registered under the
// project and job name and removed when its run ends, so concurrent runs of
// the same manual job are not supported: the first to end cancels the others.
// Detach is refused, a run is waited for;
// a dry run starts the dependencies and stops there. When the engine cannot
// run jobs, the error wraps ErrJobsNotSupported and nothing was done, so the
// caller can fall back to RunOneOffContainer.
RunJob(ctx context.Context, project *types.Project, name string, options RunOptions) (int, error)
// Exec executes a command in a running service container
Exec(ctx context.Context, projectName string, options RunOptions) (int, error)
// Attach STDIN,STDOUT,STDERR to a running service container
Attach(ctx context.Context, projectName string, options AttachOptions) error
// Copy copies a file/folder between a service container and the local filesystem
Copy(ctx context.Context, projectName string, options CopyOptions) error
// Export a service container's filesystem as a tar archive
Export(ctx context.Context, projectName string, options ExportOptions) error
// Create a new image from a service container's changes
Commit(ctx context.Context, projectName string, options CommitOptions) error
}
Runner groups the operations that run, or interact with, a command in a service container.
type ScaleOptions ¶
type ScaleOptions struct {
// Replicas maps a service name to the number of replicas it must run.
// Scale applies these counts to the project model before converging it.
Replicas map[string]int
// Services selects the services whose containers may be recreated on
// configuration divergence while converging (see CreateOptions.Services);
// it does not scale anything by itself. When empty, it defaults to the
// keys of Replicas.
Services []string
}
type ServiceNotRunningError ¶ added in v5.7.2
type ServiceNotRunningError struct {
// Service is the name of the service that was targeted.
Service string
// Index is the replica that was asked for, 0 when none in particular was.
Index int
}
ServiceNotRunningError reports that an operation which acts on one container of a service (exec, port, export, commit, attach…) found no matching container, that is no running one for most of them. It matches ErrNotRunning with errors.Is, and callers needing the details can retrieve it with errors.As.
func (*ServiceNotRunningError) Error ¶ added in v5.7.2
func (e *ServiceNotRunningError) Error() string
func (*ServiceNotRunningError) Unwrap ¶ added in v5.7.2
func (e *ServiceNotRunningError) Unwrap() error
Unwrap makes errors.Is(err, ErrNotRunning) hold.
type ServiceStatus
deprecated
type StartOptions ¶
type StartOptions struct {
// Project is the compose project used to define this app. Might be nil if user ran command just with project name.
// Ignored by Up, which works on the project it is given.
Project *types.Project
// Attach receives the containers' logs during Up's foreground session.
// It doubles as the mode switch: when nil, Up returns once containers
// are started (detached mode); when set, Up keeps running the
// interactive session (log streaming, cascade, keyboard menu), which Wait
// ends once the services are running or healthy.
// Ignored by Start.
Attach LogConsumer
// AttachTo carries two unrelated meanings: for Start, the service names
// used to rebuild a project from container labels when Project is nil;
// for Up's foreground session, the services whose logs are streamed.
AttachTo []string
// OnExit defines behavior when a container stops. Honored by Up's
// foreground session only; ignored by Start.
OnExit Cascade
// ExitCodeFrom reports the exit code of the specified service. Honored
// by Up's foreground session only; ignored by Start.
ExitCodeFrom string
// Wait won't return until containers reached the running|healthy state.
// Up honors it in detached mode (Attach nil), and combined with Attach it
// streams the logs until that state is reached, then returns leaving the
// containers running. The session options OnExit, ExitCodeFrom and Watch
// are rejected with it, see UpOptions.Validate.
Wait bool
WaitTimeout time.Duration
// Services names the services the user explicitly targeted; it only
// scopes the log monitor of Up's foreground session. Start ignores it:
// narrow the project instead.
Services []string
// Watch enables watch mode during Up's foreground session; ignored by
// Start.
Watch bool
// ignored by Start, and by Up when Wait is set.
NavigationMenu bool
}
StartOptions group options of the Start API
type StopOptions ¶
type StopOptions struct {
// Project is the compose project used to define this app. Might be nil if user ran command just with project name
Project *types.Project
// Timeout override container stop timeout
Timeout *time.Duration
// Services passed in the command line to be stopped
Services []string
}
StopOptions group options of the Stop API
type UnsupportedAttribute ¶ added in v5.6.0
type UnsupportedAttribute struct {
Service string // service name; empty for project-scoped attributes
Path string // dotted attribute path, e.g. "deploy.update_config.failure_action"
Reason string // one-line human-readable explanation, ready to print as-is
}
UnsupportedAttribute reports a compose-file attribute that is accepted by the schema but has no effect on this runtime outside Swarm mode.
func (UnsupportedAttribute) String ¶ added in v5.6.0
func (u UnsupportedAttribute) String() string
type UpOptions ¶
type UpOptions struct {
Create CreateOptions
Start StartOptions
}
UpOptions group options of the Up API
func (UpOptions) Validate ¶ added in v5.7.0
Validate checks that the options requested for Up can be honored together. It is a pure function, called by Up before it does anything, and can also be called by integrators to fail early. It returns nil, or an error matching ErrIncompatibleOptions describing every conflict found, or ErrInvalidOption when Create holds a value that CreateOptions.Validate rejects.
Up has two modes, selected by Start.Attach: detached (nil) returns once the containers are started, interactive (set) keeps running a foreground session, which Wait ends once the services are running or healthy. Validate only checks the combinations listed below: OnExit, ExitCodeFrom or Watch without Attach, or with Wait. Other mode-specific fields (e.g. Services, AttachTo, NavigationMenu) are not checked and may be ignored in the mode they do not apply to.
With a single conflict the error is an *IncompatibleOptionsError. With several, the conflicts are reported together as an error joined with errors.Join: errors.Is(err, ErrIncompatibleOptions) still holds, but errors.As to *IncompatibleOptionsError only yields the first conflict. To inspect all of them, walk the joined error through its Unwrap() []error method.
The compose CLI refuses the same combinations, with messages naming its flags; Validate is the safety net for programs using the library directly.
type VizOptions ¶
type VizOptions struct {
// IncludeNetworks if true, network names a container is attached to should appear in the graph node
IncludeNetworks bool
// IncludePorts if true, ports a container exposes should appear in the graph node
IncludePorts bool
// IncludeImageName if true, name of the image used to create a container should appear in the graph node
IncludeImageName bool
// Indentation string to be used to indent graphviz code, e.g. "\t", " "
Indentation string
}
type VolumesOptions ¶
type VolumesOptions struct {
Services []string
}
type VolumesSummary ¶
type WaitOptions ¶
type WatchOptions ¶
type WatchOptions struct {
Build *BuildOptions
LogTo LogConsumer
Prune bool
Services []string
}
WatchOptions group options of the Watch API