container

package
v1.12.2 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Overview

Package container contains code related to dealing with docker containers

Index

Constants

This section is empty.

Variables

View Source
var (

	// ErrContainerNotFound is returned by Client operations (StopContainer,
	// future StartContainer) when the daemon reports the container no longer
	// exists. Lets callers distinguish a benign mid-scan disappearance from
	// a real failure so the scan can skip the container and continue.
	ErrContainerNotFound = errors.New("container not found")

	// ErrPinnedImage is returned by PullImage when the container's image is
	// pinned to a content-addressable digest (sha256:...) — there's no tag
	// to follow, so there's nothing for watchtower to update. Lets the
	// scan-loop demote the resulting "skipped" log line to debug instead of
	// firing every poll with a warn that operators can't act on. Message
	// preserved verbatim from the pre-typed-error wording so existing
	// downstream parsers and notification templates keep matching.
	ErrPinnedImage = errors.New("container uses a pinned image, and cannot be updated by watchtower")
)

Functions

func ContainsWatchtowerLabel

func ContainsWatchtowerLabel(labels map[string]string) bool

ContainsWatchtowerLabel takes a map of labels and values and tells the consumer whether it contains a valid watchtower instance label

func GetRunningContainerID

func GetRunningContainerID() (cid types.ContainerID, err error)

GetRunningContainerID tries to resolve the current container ID from the current process cgroup information

Types

type Client

type Client interface {
	ListContainers(t.Filter) ([]t.Container, error)
	GetContainer(containerID t.ContainerID) (t.Container, error)
	StopContainer(t.Container, time.Duration) error
	StartContainer(t.Container) (t.ContainerID, error)
	RenameContainer(t.Container, string) error
	IsContainerStale(t.Container, t.UpdateParams) (stale bool, latestImage t.ImageID, err error)
	ExecuteCommand(containerID t.ContainerID, command string, timeout int) (skipUpdate bool, err error)
	RemoveImageByID(t.ImageID) error
	WarnOnHeadPullFailed(container t.Container) bool
	// WatchImageEvents opens a stream of image-lifecycle events (tag, load)
	// from the Docker daemon. The caller cancels the ctx to close the stream;
	// the error channel emits once and is closed when the stream terminates.
	// Reconnection is the caller's responsibility.
	WatchImageEvents(ctx context.Context) (<-chan t.ImageEvent, <-chan error)
}

A Client is the interface through which watchtower interacts with the Docker API.

func NewClient

func NewClient(opts ClientOptions) Client

NewClient returns a new Client instance which can be used to interact with the Docker API. The client reads its configuration from the following environment variables:

  • DOCKER_HOST the docker-engine host to send api requests to
  • DOCKER_TLS_VERIFY whether to verify tls certificates
  • DOCKER_API_VERSION the docker api version to pin the client to (skips negotiation when set)

When DOCKER_API_VERSION is unset, the client negotiates down to the daemon's reported version on first use so the same binary works against both older and newer daemons (including Docker Engine 29+, whose minimum API floor is 1.44).

type ClientOptions

type ClientOptions struct {
	RemoveVolumes     bool
	IncludeStopped    bool
	ReviveStopped     bool
	IncludeRestarting bool
	WarnOnHeadFailed  WarningStrategy
}

ClientOptions contains the options for how the docker client wrapper should behave

type Container

type Container struct {
	LinkedToRestarting bool
	Stale              bool
	// contains filtered or unexported fields
}

Container represents a running Docker container.

func NewContainer

func NewContainer(containerInfo *dockercontainer.InspectResponse, imageInfo *image.InspectResponse) *Container

NewContainer returns a new Container instance instantiated with the specified ContainerInfo and ImageInfo structs.

func (Container) ComposeDependencies added in v1.12.0

func (c Container) ComposeDependencies() []string

ComposeDependencies returns the list of service names this container declared as `depends_on` in its Compose file. Empty when the container isn't Compose-managed or has no depends_on.

Compose v2 serialises depends_on as a comma-separated list where each entry may carry optional modifiers: `service:service_started:required` or `service:service_healthy:false`. We drop the modifiers and return just the service names — Watchtower's sorter only cares about the graph edge; the condition/required bits govern Compose's own startup ordering which is orthogonal to updates.

func (Container) ComposeProject added in v1.12.0

func (c Container) ComposeProject() string

ComposeProject returns the com.docker.compose.project label (or "" if the container wasn't created by Docker Compose).

func (Container) ComposeService added in v1.12.0

func (c Container) ComposeService() string

ComposeService returns the com.docker.compose.service label (or "" if the container wasn't created by Docker Compose).

func (Container) ContainerInfo

func (c Container) ContainerInfo() *dockercontainer.InspectResponse

ContainerInfo fetches JSON info for the container

func (Container) Enabled

func (c Container) Enabled() (bool, bool)

Enabled returns the value of the container enabled label and if the label was set.

func (Container) GetCreateConfig

func (c Container) GetCreateConfig() *dockercontainer.Config

GetCreateConfig returns the container's current Config converted into a format that can be re-submitted to the Docker create API.

Ideally, we'd just be able to take the ContainerConfig from the old container and use it as the starting point for creating the new container; however, the ContainerConfig that comes back from the Inspect call merges the default configuration (the stuff specified in the metadata for the image itself) with the overridden configuration (the stuff that you might specify as part of the "docker run").

In order to avoid unintentionally overriding the defaults in the new image we need to separate the override options from the default options. To do this we have to compare the ContainerConfig for the running container with the ContainerConfig from the image that container was started from. This function returns a ContainerConfig which contains just the options overridden at runtime.

func (Container) GetCreateHostConfig

func (c Container) GetCreateHostConfig() *dockercontainer.HostConfig

GetCreateHostConfig returns the container's current HostConfig with any links re-written so that they can be re-submitted to the Docker create API.

func (Container) GetLifecyclePostCheckCommand

func (c Container) GetLifecyclePostCheckCommand() string

GetLifecyclePostCheckCommand returns the post-check command set in the container metadata or an empty string

func (Container) GetLifecyclePostUpdateCommand

func (c Container) GetLifecyclePostUpdateCommand() string

GetLifecyclePostUpdateCommand returns the post-update command set in the container metadata or an empty string

func (Container) GetLifecyclePreCheckCommand

func (c Container) GetLifecyclePreCheckCommand() string

GetLifecyclePreCheckCommand returns the pre-check command set in the container metadata or an empty string

func (Container) GetLifecyclePreUpdateCommand

func (c Container) GetLifecyclePreUpdateCommand() string

GetLifecyclePreUpdateCommand returns the pre-update command set in the container metadata or an empty string

func (Container) HasImageInfo

func (c Container) HasImageInfo() bool

HasImageInfo returns whether image information could be retrieved for the container

func (Container) HasPublishedPorts added in v1.12.1

func (c Container) HasPublishedPorts() bool

HasPublishedPorts reports whether any of the container's ports are bound to a host port. Used to detect the "watchtower publishes its /v1/* API on the host and wants to self-update" case — Watchtower's rename-and-respawn self-update pattern can't work when the old and new containers would both try to bind the same host port during the brief overlap window.

A binding "counts" as published when at least one entry in HostConfig specifies a non-empty HostPort. Ports that are only EXPOSE'd (no host binding) don't collide with anything, so they don't count.

func (Container) HealthCheckTimeout added in v1.10.0

func (c Container) HealthCheckTimeout() (time.Duration, bool)

HealthCheckTimeout returns the per-container override for --health-check-gated parsed from the com.centurylinklabs.watchtower.health-check-timeout label. Second return is false when the label is absent or unparseable, so callers can fall back to a computed-from-HEALTHCHECK default or the global flag.

func (Container) ID

func (c Container) ID() wt.ContainerID

ID returns the Docker container ID.

func (Container) ImageCooldown added in v1.12.0

func (c Container) ImageCooldown() (time.Duration, bool)

ImageCooldown returns the per-container override for --image-cooldown parsed from the com.centurylinklabs.watchtower.image-cooldown label. An operator sets this on individual services that warrant stricter (or looser) supply-chain gating than the global default — e.g. `24h` on a production database while dev containers inherit the fleet-wide policy.

Second return is false when the label is absent or unparseable. `0` is treated as unset rather than "disable cooldown for this container" to avoid surprising the operator on typos; remove the label explicitly to opt out.

func (Container) ImageID

func (c Container) ImageID() wt.ImageID

ImageID returns the ID of the Docker image that was used to start the container. May cause nil dereference if imageInfo is not set!

func (Container) ImageIdentity added in v1.12.2

func (c Container) ImageIdentity() *ImageIdentity

ImageIdentity returns the per-image provenance record, or nil if the daemon did not expose one (classic docker-image-store or an older engine).

func (Container) ImageInfo

func (c Container) ImageInfo() *image.InspectResponse

ImageInfo fetches the ImageInspect data of the current container

func (Container) ImageIsLocal added in v1.12.1

func (c Container) ImageIsLocal() bool

ImageIsLocal reports whether the container's image was produced by this daemon (`docker build`, `docker buildx build`, `docker load`) rather than pulled from a registry.

Watchtower uses this as a signal to skip the registry roundtrip: there's nothing to pull for a locally-built image, and attempting one only produces a noisy "No such image" or "pull access denied" error from the daemon every poll. The locally-tagged image is still picked up by HasNewImage when a rebuild changes the tag's image ID, so `docker build -t app:latest .` followed by a poll triggers the expected recreate.

Two signals, in order of precedence:

  1. The containerd-snapshotter "Identity" record (Docker 25+). If the engine recorded a Build entry and no Pull entry, the image is local. This is the authoritative signal — on the containerd image store a real registry pull and a local `docker build` both appear as "name@sha256:..." in RepoDigests and are otherwise indistinguishable, so the heuristic below would false-positive on every Docker Hub image.
  2. Empty RepoDigests (the classic docker-image-store path). Fallback for daemons that don't populate Identity — there, a local build genuinely has no manifest digest because it never went through a registry push.

Returns false when image info isn't available — be conservative, let the existing pull path surface the real error.

func (Container) ImageName

func (c Container) ImageName() string

ImageName returns the name of the Docker image that was used to start the container. If the original image was specified without a particular tag, the "latest" tag is assumed.

func (Container) IsInfrastructure added in v1.11.1

func (c Container) IsInfrastructure() bool

IsInfrastructure reports whether this container is Docker-managed scaffolding (buildx builder, Desktop internals) rather than a user workload. Such containers come and go on their own cadence and shouldn't count toward the "unmanaged" audit bucket — they'd otherwise generate noise every `docker buildx build` invocation.

func (*Container) IsLinkedToRestarting

func (c *Container) IsLinkedToRestarting() bool

IsLinkedToRestarting returns the current value of the LinkedToRestarting field for the container

func (Container) IsMonitorOnly

func (c Container) IsMonitorOnly(params wt.UpdateParams) bool

IsMonitorOnly returns whether the container should only be monitored based on values of the monitor-only label, the monitor-only argument and the label-take-precedence argument.

func (Container) IsNoPull

func (c Container) IsNoPull(params wt.UpdateParams) bool

IsNoPull returns whether the image should be pulled based on values of the no-pull label, the no-pull argument and the label-take-precedence argument.

func (Container) IsRestarting

func (c Container) IsRestarting() bool

IsRestarting returns a boolean flag indicating whether or not the current container is restarting. The status is determined by the value of the container's "State.Restarting" property.

func (Container) IsRunning

func (c Container) IsRunning() bool

IsRunning returns a boolean flag indicating whether or not the current container is running. The status is determined by the value of the container's "State.Running" property.

func (*Container) IsStale

func (c *Container) IsStale() bool

IsStale returns the current value of the Stale field for the container

func (Container) IsWatchtower

func (c Container) IsWatchtower() bool

IsWatchtower returns a boolean flag indicating whether or not the current container is the watchtower container itself. The watchtower container is identified by the presence of the "com.centurylinklabs.watchtower" label in the container metadata.

func (c Container) Links() []string

Links returns a list containing the names of all the containers to which this container is linked.

func (Container) Name

func (c Container) Name() string

Name returns the Docker container name.

func (Container) PostUpdateTimeout

func (c Container) PostUpdateTimeout() int

PostUpdateTimeout checks whether a container has a specific timeout set for how long the post-update command is allowed to run. This value is expressed either as an integer, in minutes, or as 0 which will allow the command/script to run indefinitely. Users should be cautious with the 0 option, as that could result in watchtower waiting forever.

func (Container) PreUpdateTimeout

func (c Container) PreUpdateTimeout() int

PreUpdateTimeout checks whether a container has a specific timeout set for how long the pre-update command is allowed to run. This value is expressed either as an integer, in minutes, or as 0 which will allow the command/script to run indefinitely. Users should be cautious with the 0 option, as that could result in watchtower waiting forever.

func (Container) SafeImageID

func (c Container) SafeImageID() wt.ImageID

SafeImageID returns the ID of the Docker image that was used to start the container if available, otherwise returns an empty string

func (Container) Scope

func (c Container) Scope() (string, bool)

Scope returns the value of the scope UID label and if the label was set.

func (*Container) SetImageIdentity added in v1.12.2

func (c *Container) SetImageIdentity(identity *ImageIdentity)

SetImageIdentity attaches provenance data decoded from the extended image inspect JSON. Safe to pass nil — ImageIsLocal falls back to RepoDigests.

func (*Container) SetLinkedToRestarting

func (c *Container) SetLinkedToRestarting(value bool)

SetLinkedToRestarting sets the LinkedToRestarting field for the container

func (*Container) SetStale

func (c *Container) SetStale(value bool)

SetStale implements sets the Stale field for the container

func (Container) SourceImageID added in v1.9.0

func (c Container) SourceImageID() wt.ImageID

SourceImageID returns the ID Docker recorded against the container itself at creation time, not the ID of whichever image is currently tagged. This stays stable even when the image has been garbage-collected and GetContainer fell back to the name-resolved imageInfo, so it's the correct ID for --cleanup (we want to remove the *old* image, not the freshly-pulled replacement).

func (Container) StopSignal

func (c Container) StopSignal() string

StopSignal returns the custom stop signal (if any) that is encoded in the container's metadata. If the container has not specified a custom stop signal, the empty string "" is returned.

func (Container) StopTimeout added in v1.12.0

func (c Container) StopTimeout() time.Duration

StopTimeout returns the container's configured SIGTERM-to-SIGKILL grace period if one was set on the container itself (via `docker run --stop-timeout` or Compose's `stop_grace_period`). Returns 0 when the container carries no explicit timeout, in which case the caller should fall back to the global --stop-timeout flag. Matches upstream Docker's precedence of per-container timeout over daemon default.

func (Container) ToRestart

func (c Container) ToRestart() bool

ToRestart return whether the container should be restarted, either because is stale or linked to another stale container.

func (Container) VerifyConfiguration

func (c Container) VerifyConfiguration() error

VerifyConfiguration checks the container and image configurations for nil references to make sure that the container can be recreated once deleted

type ImageBuildIdentity added in v1.12.2

type ImageBuildIdentity struct {
	Ref       string `json:"Ref,omitempty"`
	CreatedAt string `json:"CreatedAt,omitempty"`
}

ImageBuildIdentity is one entry in ImageIdentity.Build. Only the fields Watchtower needs are decoded.

type ImageIdentity added in v1.12.2

type ImageIdentity struct {
	// Build lists local build provenance entries. Non-empty means the image
	// was produced by `docker build` / `docker buildx build` / `docker load`
	// against this daemon.
	Build []ImageBuildIdentity `json:"Build,omitempty"`
	// Pull lists registry pull provenance entries. Non-empty means at least
	// one registry hands out the same manifest digest, so Watchtower can
	// meaningfully attempt a pull.
	Pull []ImagePullIdentity `json:"Pull,omitempty"`
}

ImageIdentity captures the Docker engine's per-image provenance record as returned in the raw inspect JSON under the top-level "Identity" key. Only the fields Watchtower acts on are decoded; everything else is dropped. The field is populated by the containerd image store (Docker 25+ with containerd-snapshotter) and absent on the classic docker-image-store path, so callers must treat a nil ImageIdentity as "signal unavailable", not "image has no provenance".

type ImagePullIdentity added in v1.12.2

type ImagePullIdentity struct {
	Repository string `json:"Repository,omitempty"`
}

ImagePullIdentity is one entry in ImageIdentity.Pull.

type WarningStrategy

type WarningStrategy string

WarningStrategy is a value determining when to show warnings

const (
	// WarnAlways warns whenever the problem occurs
	WarnAlways WarningStrategy = "always"
	// WarnNever never warns when the problem occurs
	WarnNever WarningStrategy = "never"
	// WarnAuto skips warning when the problem was expected
	WarnAuto WarningStrategy = "auto"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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