Documentation
¶
Index ¶
- Variables
- func Cleanup(tb testing.TB, ctr TerminableContainer, options ...TerminateOption)
- func Terminate(ctr TerminableContainer, options ...TerminateOption) error
- func Version() string
- type Container
- func FromID(ctx context.Context, dockerClient client.SDKClient, containerID string) (*Container, error)
- func FromResponse(ctx context.Context, dockerClient client.SDKClient, response container.Summary) (*Container, error)
- func Run(ctx context.Context, opts ...ContainerCustomizer) (*Container, error)
- func (c *Container) Client() client.SDKClient
- func (c *Container) ContainerIP(ctx context.Context) (netip.Addr, error)
- func (c *Container) ContainerIPs(ctx context.Context) ([]netip.Addr, error)
- func (c *Container) CopyDirToContainer(ctx context.Context, hostDirPath string, containerFilePath string, ...) error
- func (c *Container) CopyFromContainer(ctx context.Context, containerFilePath string) (io.ReadCloser, error)
- func (c *Container) CopyToContainer(ctx context.Context, fileContent []byte, containerFilePath string, ...) error
- func (c *Container) Endpoint(ctx context.Context, proto string) (string, error)
- func (c *Container) Exec(ctx context.Context, cmd []string, options ...exec.ProcessOption) (int, io.Reader, error)
- func (c *Container) Host(ctx context.Context) (string, error)
- func (c *Container) ID() string
- func (c *Container) Image() string
- func (c *Container) Inspect(ctx context.Context) (client.ContainerInspectResult, error)
- func (c *Container) InspectWithOptions(ctx context.Context, options client.ContainerInspectOptions) (client.ContainerInspectResult, error)
- func (c *Container) IsRunning() bool
- func (c *Container) Logger() *slog.Logger
- func (c *Container) Logs(ctx context.Context) (io.ReadCloser, error)
- func (c *Container) MappedPort(ctx context.Context, port network.Port) (network.Port, error)
- func (c *Container) NetworkAliases(ctx context.Context) (map[string][]string, error)
- func (c *Container) Networks(ctx context.Context) ([]string, error)
- func (c *Container) PortEndpoint(ctx context.Context, port network.Port, proto string) (string, error)
- func (c *Container) Running(b bool)
- func (c *Container) ShortID() string
- func (c *Container) Start(ctx context.Context) error
- func (c *Container) State(ctx context.Context) (*container.State, error)
- func (c *Container) Stop(ctx context.Context, opts ...StopOption) error
- func (c *Container) Terminate(ctx context.Context, opts ...TerminateOption) error
- func (c *Container) WaitingFor() wait.Strategy
- type ContainerCustomizer
- type ContainerExecutor
- type ContainerFileOperator
- type ContainerHook
- type ContainerInfo
- type ContainerStateManager
- type ContainerWaiter
- type CustomHubSubstitutor
- type CustomizeDefinitionOption
- func WithAdditionalConfigModifier(modifier func(config *container.Config)) CustomizeDefinitionOption
- func WithAdditionalEndpointSettingsModifier(modifier func(settings map[string]*apinetwork.EndpointSettings)) CustomizeDefinitionOption
- func WithAdditionalHostConfigModifier(modifier func(hostConfig *container.HostConfig)) CustomizeDefinitionOption
- func WithAdditionalLifecycleHooks(hooks ...LifecycleHooks) CustomizeDefinitionOption
- func WithAdditionalWaitStrategy(strategies ...wait.Strategy) CustomizeDefinitionOption
- func WithAdditionalWaitStrategyAndDeadline(deadline time.Duration, strategies ...wait.Strategy) CustomizeDefinitionOption
- func WithAfterReadyCommand(execs ...Executable) CustomizeDefinitionOption
- func WithAlwaysPull() CustomizeDefinitionOption
- func WithBridgeNetwork() CustomizeDefinitionOption
- func WithClient(cli client.SDKClient) CustomizeDefinitionOption
- func WithCmd(cmd ...string) CustomizeDefinitionOption
- func WithCmdArgs(cmdArgs ...string) CustomizeDefinitionOption
- func WithConfigModifier(modifier func(config *container.Config)) CustomizeDefinitionOption
- func WithDefinition(def *Definition) CustomizeDefinitionOption
- func WithEndpointSettingsModifier(modifier func(settings map[string]*apinetwork.EndpointSettings)) CustomizeDefinitionOption
- func WithEntrypoint(entrypoint ...string) CustomizeDefinitionOption
- func WithEntrypointArgs(entrypointArgs ...string) CustomizeDefinitionOption
- func WithEnv(envs map[string]string) CustomizeDefinitionOption
- func WithExposedPorts(ports ...string) CustomizeDefinitionOption
- func WithFiles(files ...File) CustomizeDefinitionOption
- func WithHostConfigModifier(modifier func(hostConfig *container.HostConfig)) CustomizeDefinitionOption
- func WithImage(image string) CustomizeDefinitionOption
- func WithImagePlatform(platform string) CustomizeDefinitionOption
- func WithImageSubstitutors(fn ...ImageSubstitutor) CustomizeDefinitionOption
- func WithLabels(labels map[string]string) CustomizeDefinitionOption
- func WithLifecycleHooks(hooks ...LifecycleHooks) CustomizeDefinitionOption
- func WithName(containerName string) CustomizeDefinitionOption
- func WithNetwork(aliases []string, nw *network.Network) CustomizeDefinitionOption
- func WithNetworkName(aliases []string, networkName string) CustomizeDefinitionOption
- func WithNewNetwork(ctx context.Context, aliases []string, opts ...network.Option) CustomizeDefinitionOption
- func WithNoStart() CustomizeDefinitionOption
- func WithPullHandler(handler func(r io.ReadCloser) error) CustomizeDefinitionOption
- func WithStartupCommand(execs ...Executable) CustomizeDefinitionOption
- func WithValidateFuncs(fn ...func() error) CustomizeDefinitionOption
- func WithWaitStrategy(strategies ...wait.Strategy) CustomizeDefinitionOption
- func WithWaitStrategyAndDeadline(deadline time.Duration, strategies ...wait.Strategy) CustomizeDefinitionOption
- type Definition
- func (d *Definition) DockerClient() client.SDKClient
- func (d *Definition) HostConfigModifier() func(*container.HostConfig)
- func (d *Definition) Image() string
- func (d *Definition) ImageSubstitutors() []ImageSubstitutor
- func (d *Definition) Labels() map[string]string
- func (d *Definition) Name() string
- func (d *Definition) Networks() []string
- type DefinitionHook
- type Executable
- type File
- type FileFromContainer
- type ImageSubstitutor
- type LifecycleHooks
- type StopOption
- type StopOptions
- type TerminableContainer
- type TerminateOption
- type TerminateOptions
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrDuplicateMountTarget is returned when a duplicate mount target is detected. ErrDuplicateMountTarget = errors.New("duplicate mount target detected") // ErrInvalidBindMount is returned when an invalid bind mount is detected. ErrInvalidBindMount = errors.New("invalid bind mount") )
var DefaultLoggingHook = LifecycleHooks{ PreCreates: []DefinitionHook{ func(_ context.Context, def *Definition) error { def.dockerClient.Logger().Info("Creating container", "image", def.image) return nil }, }, PostCreates: []ContainerHook{ func(_ context.Context, c ContainerInfo) error { c.Logger().Info("Container created", "containerID", c.ShortID()) return nil }, }, PreStarts: []ContainerHook{ func(_ context.Context, c ContainerInfo) error { c.Logger().Info("Starting container", "containerID", c.ShortID()) return nil }, }, PostStarts: []ContainerHook{ func(_ context.Context, c ContainerInfo) error { c.Logger().Info("Container started", "containerID", c.ShortID()) return nil }, }, PostReadies: []ContainerHook{ func(_ context.Context, c ContainerInfo) error { c.Logger().Info("Container is ready", "containerID", c.ShortID()) return nil }, }, PreStops: []ContainerHook{ func(_ context.Context, c ContainerInfo) error { c.Logger().Info("Stopping container", "containerID", c.ShortID()) return nil }, }, PostStops: []ContainerHook{ func(_ context.Context, c ContainerInfo) error { c.Logger().Info("Container stopped", "containerID", c.ShortID()) return nil }, }, PreTerminates: []ContainerHook{ func(_ context.Context, c ContainerInfo) error { c.Logger().Info("Terminating container", "containerID", c.ShortID()) return nil }, }, PostTerminates: []ContainerHook{ func(_ context.Context, c ContainerInfo) error { c.Logger().Info("Container terminated", "containerID", c.ShortID()) return nil }, }, }
DefaultLoggingHook is a hook that will log the container lifecycle events
var ErrContainerNameEmpty = errors.New("container name mustn't be empty")
Functions ¶
func Cleanup ¶
func Cleanup(tb testing.TB, ctr TerminableContainer, options ...TerminateOption)
Cleanup is a helper function that schedules a TerminableContainer to be terminated when the test ends.
This should be called directly after (before any error check) [Create](...) in a test to ensure the container is pruned when the function ends. If the container is nil, it's a no-op.
func Terminate ¶
func Terminate(ctr TerminableContainer, options ...TerminateOption) error
Terminate calls [TerminableContainer.Terminate] on the container if it is not nil.
This should be called as a defer directly after [Create](...) to ensure the container is terminated when the function ends.
Types ¶
type Container ¶
type Container struct {
// contains filtered or unexported fields
}
Container represents a container
Example (Copy) ¶
package main
import (
"bytes"
"context"
"fmt"
"io"
"github.com/docker/go-sdk/container"
)
func main() {
ctr, err := container.Run(context.Background(), container.WithImage("alpine:latest"))
fmt.Println(err)
content := []byte("Hello, World!")
err = ctr.CopyToContainer(context.Background(), content, "/tmp/test.txt", 0o644)
fmt.Println(err)
rc, err := ctr.CopyFromContainer(context.Background(), "/tmp/test.txt")
fmt.Println(err)
buf := new(bytes.Buffer)
_, err = io.Copy(buf, rc)
fmt.Println(err)
fmt.Println(buf.String())
err = ctr.Terminate(context.Background())
fmt.Println(err)
}
Output: <nil> <nil> <nil> <nil> Hello, World! <nil>
Example (Lifecycle) ¶
package main
import (
"context"
"fmt"
"github.com/docker/go-sdk/container"
)
func main() {
ctr, err := container.Run(
context.Background(),
container.WithImage("alpine:latest"),
container.WithNoStart(),
)
fmt.Println(err)
err = ctr.Start(context.Background())
fmt.Println(err)
err = ctr.Stop(context.Background())
fmt.Println(err)
err = ctr.Start(context.Background())
fmt.Println(err)
err = ctr.Terminate(context.Background())
fmt.Println(err)
}
Output: <nil> <nil> <nil> <nil> <nil>
func FromID ¶
func FromID(ctx context.Context, dockerClient client.SDKClient, containerID string) (*Container, error)
FromID builds a container struct from a container ID, using the Docker API to inspect the container. If dockerClient is nil, a new client will be created using the default configuration.
Example ¶
package main
import (
"bytes"
"context"
"fmt"
"io"
"github.com/docker/go-sdk/container"
)
func main() {
// First, create a container using Run
ctr, err := container.Run(context.Background(), container.WithImage("alpine:latest"))
if err != nil {
fmt.Println(err)
return
}
// Use the SDK client from the existing container
cli := ctr.Client()
// Now recreate the container using FromID with the container ID
// This is useful when you only have a container ID and need to perform operations on it
recreated, err := container.FromID(context.Background(), cli, ctr.ID())
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Container IDs match:", recreated.ID() == ctr.ID())
// Now you can use operations like CopyToContainer on the recreated container
content := []byte("Hello from FromID!")
if err := recreated.CopyToContainer(context.Background(), content, "/tmp/test.txt", 0o644); err != nil {
fmt.Println(err)
return
}
// Verify the file was copied
rc, err := recreated.CopyFromContainer(context.Background(), "/tmp/test.txt")
if err != nil {
fmt.Println(err)
return
}
buf := new(bytes.Buffer)
if _, err := io.Copy(buf, rc); err != nil {
fmt.Println(err)
return
}
fmt.Println("File content:", buf.String())
// Terminate the recreated container
err = recreated.Terminate(context.Background())
if err != nil {
fmt.Println(err)
return
}
// Terminate the original container should fail
err = ctr.Terminate(context.Background())
if err == nil {
// Termination unexpectedly succeeded; a failure path for the example
return
}
fmt.Println("Container did not exist")
}
Output: Container IDs match: true File content: Hello from FromID! Container did not exist
func FromResponse ¶
func FromResponse(ctx context.Context, dockerClient client.SDKClient, response container.Summary) (*Container, error)
FromResponse builds a container struct from the response of the Docker API. If dockerClient is nil, a new client will be created using the default configuration.
Example ¶
package main
import (
"bytes"
"context"
"fmt"
"io"
containertypes "github.com/moby/moby/api/types/container"
dockerclient "github.com/moby/moby/client"
"github.com/docker/go-sdk/container"
)
func main() {
// First, create a container using Run
ctr, err := container.Run(context.Background(), container.WithImage("alpine:latest"))
if err != nil {
fmt.Println(err)
return
}
// Use the SDK client from the existing container
cli := ctr.Client()
// List containers to get the Summary (this is what you'd typically get from the Docker API)
containers, err := cli.ContainerList(context.Background(), dockerclient.ContainerListOptions{All: true})
if err != nil {
fmt.Println(err)
return
}
// Find our container in the list
var summary containertypes.Summary
for _, c := range containers.Items {
if c.ID == ctr.ID() {
summary = c
break
}
}
// Now recreate the container using FromResponse with the container summary
// This is useful when you only have a container ID and need to perform operations on it
recreated, err := container.FromResponse(context.Background(), cli, summary)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Container IDs match:", recreated.ID() == ctr.ID())
// Now you can use operations like CopyToContainer on the recreated container
content := []byte("Hello from FromResponse!")
if err := recreated.CopyToContainer(context.Background(), content, "/tmp/test.txt", 0o644); err != nil {
fmt.Println(err)
return
}
// Verify the file was copied
rc, err := recreated.CopyFromContainer(context.Background(), "/tmp/test.txt")
if err != nil {
fmt.Println(err)
return
}
buf := new(bytes.Buffer)
if _, err := io.Copy(buf, rc); err != nil {
fmt.Println(err)
return
}
fmt.Println("File content:", buf.String())
// Terminate the recreated container
err = recreated.Terminate(context.Background())
if err != nil {
fmt.Println(err)
return
}
// Terminate the original container should fail
err = ctr.Terminate(context.Background())
if err == nil {
// Termination unexpectedly succeeded; a failure path for the example
return
}
fmt.Println("Container did not exist")
}
Output: Container IDs match: true File content: Hello from FromResponse! Container did not exist
func Run ¶
func Run(ctx context.Context, opts ...ContainerCustomizer) (*Container, error)
Run is a convenience function that creates a new container and starts it. By default, the container is started after creation, unless requested otherwise using the WithNoStart option.
Example ¶
package main
import (
"context"
"fmt"
"github.com/docker/go-sdk/container"
)
func main() {
ctr, err := container.Run(context.Background(), container.WithImage("alpine:latest"))
fmt.Println(err)
fmt.Println(ctr.ID() != "")
err = ctr.Terminate(context.Background())
fmt.Println(err)
}
Output: <nil> true <nil>
func (*Container) ContainerIP ¶
ContainerIP gets the IP address of the primary network within the container. If there are multiple networks, it returns an empty string.
func (*Container) ContainerIPs ¶
ContainerIPs gets the IP addresses of all the networks within the container.
func (*Container) CopyDirToContainer ¶
func (c *Container) CopyDirToContainer(ctx context.Context, hostDirPath string, containerFilePath string, fileMode int64) error
CopyDirToContainer copies a directory to a container, using the parent directory of the container path as the target directory.
func (*Container) CopyFromContainer ¶
func (c *Container) CopyFromContainer(ctx context.Context, containerFilePath string) (io.ReadCloser, error)
CopyFromContainer copies a file from the container to the local filesystem.
func (*Container) CopyToContainer ¶
func (c *Container) CopyToContainer(ctx context.Context, fileContent []byte, containerFilePath string, fileMode int64) error
CopyToContainer copies fileContent data to a file in container
func (*Container) Endpoint ¶
Endpoint gets proto://host:port string for the lowest numbered exposed port Will return just host:port if proto is empty
func (*Container) Exec ¶
func (c *Container) Exec(ctx context.Context, cmd []string, options ...exec.ProcessOption) (int, io.Reader, error)
Exec executes a command in the current container. It returns the exit status of the executed command, an io.Reader containing the combined stdout and stderr, and any encountered error. Note that reading directly from the io.Reader may result in unexpected bytes due to custom stream multiplexing headers. Use [cexec.Multiplexed] option to read the combined output without the multiplexing headers. Alternatively, to separate the stdout and stderr from io.Reader and interpret these headers properly, github.com/moby/moby/api/pkg/stdcopy.StdCopy from the Docker API should be used.
Example ¶
package main
import (
"bytes"
"context"
"fmt"
"io"
"github.com/docker/go-sdk/container"
"github.com/docker/go-sdk/container/exec"
)
func main() {
ctr, err := container.Run(context.Background(), container.WithImage("nginx:alpine"))
fmt.Println(err)
code, rc, err := ctr.Exec(
context.Background(),
[]string{"pwd"},
exec.Multiplexed(),
exec.WithWorkingDir("/usr/share/nginx/html"),
)
fmt.Println(err)
fmt.Println(code)
buf := new(bytes.Buffer)
_, err = io.Copy(buf, rc)
fmt.Println(err)
fmt.Print(buf.String()) // not adding a newline to the output
err = ctr.Terminate(context.Background())
fmt.Println(err)
}
Output: <nil> <nil> 0 <nil> /usr/share/nginx/html <nil>
func (*Container) Host ¶
Host gets host (ip or name) of the docker daemon where the container port is exposed Warning: this is based on your Docker host setting. Will fail if using an SSH tunnel
func (*Container) Inspect ¶
Inspect returns the container's raw info
Example ¶
package main
import (
"context"
"fmt"
"github.com/docker/go-sdk/container"
)
func main() {
ctr, err := container.Run(context.Background(), container.WithImage("alpine:latest"))
fmt.Println(err)
inspect, err := ctr.Inspect(context.Background())
fmt.Println(err)
fmt.Println(inspect.Container.ID != "")
err = ctr.Terminate(context.Background())
fmt.Println(err)
}
Output: <nil> <nil> true <nil>
func (*Container) InspectWithOptions ¶
func (c *Container) InspectWithOptions(ctx context.Context, options client.ContainerInspectOptions) (client.ContainerInspectResult, error)
InspectWithOptions returns the container's raw info, passing custom options.
This method may be deprecated in the near future, to be replaced by functional options for Inspect.
func (*Container) Logs ¶
Logs will fetch both STDOUT and STDERR from the current container. Returns a ReadCloser and leaves it up to the caller to extract what it wants.
Example ¶
package main
import (
"bytes"
"context"
"fmt"
"io"
"strings"
"github.com/docker/go-sdk/container"
)
func main() {
ctr, err := container.Run(context.Background(), container.WithImage("hello-world:latest"))
fmt.Println(err)
logs, err := ctr.Logs(context.Background())
fmt.Println(err)
buf := new(bytes.Buffer)
_, err = io.Copy(buf, logs)
fmt.Println(err)
fmt.Println(strings.Contains(buf.String(), "Hello from Docker!"))
err = ctr.Terminate(context.Background())
fmt.Println(err)
}
Output: <nil> <nil> <nil> true <nil>
func (*Container) MappedPort ¶
MappedPort gets externally mapped port for a container port
func (*Container) NetworkAliases ¶
NetworkAliases gets the aliases of the container for the networks it is attached to.
func (*Container) PortEndpoint ¶
func (c *Container) PortEndpoint(ctx context.Context, port network.Port, proto string) (string, error)
PortEndpoint gets proto://host:port string for the given exposed port It returns proto://host:port or proto://[IPv6host]:port string for the given exposed port. It returns just host:port or [IPv6host]:port if proto is blank.
TODO(robmry) - remove proto and use port.Proto()
func (*Container) ShortID ¶
ShortID returns the short container ID, using the first 12 characters of the ID
func (*Container) Stop ¶
func (c *Container) Stop(ctx context.Context, opts ...StopOption) error
Stop stops the container.
In case the container fails to stop gracefully within a time frame specified by the timeout argument, it is forcefully terminated (killed).
If no timeout is passed, the default StopTimeout value is used, 10 seconds, otherwise the engine default. A negative timeout value can be specified, meaning no timeout, i.e. no forceful termination is performed.
All hooks are called in the following order:
- [LifecycleHooks.PreStops]
- [LifecycleHooks.PostStops]
If the container is already stopped, the method is a no-op.
func (*Container) Terminate ¶
func (c *Container) Terminate(ctx context.Context, opts ...TerminateOption) error
Terminate calls stops and then removes the container including its volumes. If its image was built it and all child images are also removed unless the [FromDockerfile.KeepImage] on the [ContainerRequest] was set to true.
The following hooks are called in order:
- [LifecycleHooks.PreTerminates]
- [LifecycleHooks.PostTerminates]
Default: timeout is 10 seconds.
Example ¶
package main
import (
"context"
"fmt"
"github.com/docker/go-sdk/container"
)
func main() {
ctr, err := container.Run(context.Background(), container.WithImage("alpine:latest"))
fmt.Println(err)
err = ctr.Terminate(context.Background())
fmt.Println(err)
}
Output: <nil> <nil>
func (*Container) WaitingFor ¶
WaitingFor returns the waiting strategy used by the container.
type ContainerCustomizer ¶
type ContainerCustomizer interface {
Customize(def *Definition) error
}
ContainerCustomizer is an interface that can be used to configure the container definition. The passed definition is merged with the default one.
type ContainerExecutor ¶
type ContainerExecutor interface {
Exec(ctx context.Context, cmd []string, opts ...exec.ProcessOption) (int, io.Reader, error)
}
ContainerExecutor is an optional capability interface that can be used to execute commands in the container.
type ContainerFileOperator ¶
type ContainerFileOperator interface {
CopyDirToContainer(ctx context.Context, hostDirPath string, containerFilePath string, fileMode int64) error
CopyToContainer(ctx context.Context, fileContent []byte, containerFilePath string, fileMode int64) error
}
ContainerFileOperator is an optional capability interface that can be used to copy files to and from the container.
type ContainerHook ¶
type ContainerHook func(ctx context.Context, ctrInfo ContainerInfo) error
ContainerHook is a hook that is called after a container is created It can be used to modify the state of the container after it is created, using the different lifecycle hooks that are available: - Created - Starting - Started - Readied - Stopping - Stopped - Terminating - Terminated It receives a ContainerInfo interface, allowing custom implementations to be used with the SDK.
type ContainerInfo ¶
Core interface - always available
type ContainerStateManager ¶
ContainerStateManager is an optional capability interface that can be used to manage the state of the container.
type ContainerWaiter ¶
type ContainerWaiter interface {
wait.StrategyTarget
WaitingFor() wait.Strategy
}
ContainerWaiter is an optional capability interface that can be used to wait for the container to be ready. It embeds the wait.StrategyTarget interface to allow the wait strategy to be used to wait for the container to be ready.
type CustomHubSubstitutor ¶
type CustomHubSubstitutor struct {
// contains filtered or unexported fields
}
CustomHubSubstitutor represents a way to substitute the hub of an image with a custom one, using provided value with respect to the HubImageNamePrefix configuration value.
func NewCustomHubSubstitutor ¶
func NewCustomHubSubstitutor(hub string) CustomHubSubstitutor
NewCustomHubSubstitutor creates a new CustomHubSubstitutor
func (CustomHubSubstitutor) Description ¶
func (c CustomHubSubstitutor) Description() string
Description returns the name of the type and a short description of how it modifies the image.
func (CustomHubSubstitutor) Substitute ¶
func (c CustomHubSubstitutor) Substitute(image string) (string, error)
Substitute replaces the hub of the image with the provided one, with certain conditions:
- if the hub is empty, the image is returned as is.
- if the image already contains a registry, the image is returned as is.
type CustomizeDefinitionOption ¶
type CustomizeDefinitionOption func(def *Definition) error
CustomizeDefinitionOption is a type that can be used to configure the container definition. The passed definition is merged with the default one.
func WithAdditionalConfigModifier ¶
func WithAdditionalConfigModifier(modifier func(config *container.Config)) CustomizeDefinitionOption
WithAdditionalConfigModifier allows to add additional config to the container. It applies the additional config after the original config.
func WithAdditionalEndpointSettingsModifier ¶
func WithAdditionalEndpointSettingsModifier(modifier func(settings map[string]*apinetwork.EndpointSettings)) CustomizeDefinitionOption
WithAdditionalEndpointSettingsModifier allows to add additional endpoint settings to the container. It will merge the additional endpoint settings with the existing endpoint settings.
func WithAdditionalHostConfigModifier ¶
func WithAdditionalHostConfigModifier(modifier func(hostConfig *container.HostConfig)) CustomizeDefinitionOption
WithAdditionalHostConfigModifier allows to add additional host config to the container. It applies the additional host config after the original host config.
func WithAdditionalLifecycleHooks ¶
func WithAdditionalLifecycleHooks(hooks ...LifecycleHooks) CustomizeDefinitionOption
WithAdditionalLifecycleHooks appends lifecycle hooks to the existing ones for a container
func WithAdditionalWaitStrategy ¶
func WithAdditionalWaitStrategy(strategies ...wait.Strategy) CustomizeDefinitionOption
WithAdditionalWaitStrategy appends the wait strategy for a container, using 60 seconds as deadline
func WithAdditionalWaitStrategyAndDeadline ¶
func WithAdditionalWaitStrategyAndDeadline(deadline time.Duration, strategies ...wait.Strategy) CustomizeDefinitionOption
WithAdditionalWaitStrategyAndDeadline appends the wait strategy for a container, including deadline
func WithAfterReadyCommand ¶
func WithAfterReadyCommand(execs ...Executable) CustomizeDefinitionOption
WithAfterReadyCommand will execute the command representation of each Executable into the container. It will leverage the container lifecycle hooks to call the command right after the container is ready.
func WithAlwaysPull ¶
func WithAlwaysPull() CustomizeDefinitionOption
WithAlwaysPull will pull the image before starting the container. Do not use this option in case the image is the result of a build and not yet pushed to a registry. It will try to pull the image from the registry, and fail.
func WithBridgeNetwork ¶
func WithBridgeNetwork() CustomizeDefinitionOption
WithBridgeNetwork attachs a container to the "bridge" network. There is no need to set the network alias, as it is not supported for the "bridge" network.
func WithClient ¶
func WithClient(cli client.SDKClient) CustomizeDefinitionOption
WithClient sets the client for a container
func WithCmd ¶
func WithCmd(cmd ...string) CustomizeDefinitionOption
WithCmd completely replaces the command for a container
func WithCmdArgs ¶
func WithCmdArgs(cmdArgs ...string) CustomizeDefinitionOption
WithCmdArgs appends the command arguments to the command for a container
func WithConfigModifier ¶
func WithConfigModifier(modifier func(config *container.Config)) CustomizeDefinitionOption
WithConfigModifier allows to override the default container config
func WithDefinition ¶
func WithDefinition(def *Definition) CustomizeDefinitionOption
WithDefinition allows to use the client definition in order to create the container. This option is useful when client code defines a definition and wants its values to be updated on container creation. If used, it's mandatory to pass this option as the last option to the container creation, so that the client definition is updated with the SDK definition.
func WithEndpointSettingsModifier ¶
func WithEndpointSettingsModifier(modifier func(settings map[string]*apinetwork.EndpointSettings)) CustomizeDefinitionOption
WithEndpointSettingsModifier allows to override the default endpoint settings
func WithEntrypoint ¶
func WithEntrypoint(entrypoint ...string) CustomizeDefinitionOption
WithEntrypoint completely replaces the entrypoint of a container
func WithEntrypointArgs ¶
func WithEntrypointArgs(entrypointArgs ...string) CustomizeDefinitionOption
WithEntrypointArgs appends the entrypoint arguments to the entrypoint of a container
func WithEnv ¶
func WithEnv(envs map[string]string) CustomizeDefinitionOption
WithEnv sets the environment variables for a container. If the environment variable already exists, it will be overridden.
func WithExposedPorts ¶
func WithExposedPorts(ports ...string) CustomizeDefinitionOption
WithExposedPorts appends the ports to the exposed ports for a container
func WithFiles ¶
func WithFiles(files ...File) CustomizeDefinitionOption
WithFiles appends the files to the files for a container
func WithHostConfigModifier ¶
func WithHostConfigModifier(modifier func(hostConfig *container.HostConfig)) CustomizeDefinitionOption
WithHostConfigModifier allows to override the default host config
func WithImage ¶
func WithImage(image string) CustomizeDefinitionOption
WithImage sets the image for a container
func WithImagePlatform ¶
func WithImagePlatform(platform string) CustomizeDefinitionOption
WithImagePlatform sets the platform for a container
func WithImageSubstitutors ¶
func WithImageSubstitutors(fn ...ImageSubstitutor) CustomizeDefinitionOption
WithImageSubstitutors sets the image substitutors for a container
func WithLabels ¶
func WithLabels(labels map[string]string) CustomizeDefinitionOption
WithLabels appends the labels to the labels for a container
func WithLifecycleHooks ¶
func WithLifecycleHooks(hooks ...LifecycleHooks) CustomizeDefinitionOption
WithLifecycleHooks completely replaces the lifecycle hooks for a container
func WithName ¶
func WithName(containerName string) CustomizeDefinitionOption
WithName will set the name of the container. It returns an error if the container name is empty.
func WithNetwork ¶
func WithNetwork(aliases []string, nw *network.Network) CustomizeDefinitionOption
WithNetwork reuses an already existing network, attaching the container to it. Finally it sets the network alias on that network to the given alias.
func WithNetworkName ¶
func WithNetworkName(aliases []string, networkName string) CustomizeDefinitionOption
WithNetworkName attachs a container to an already existing network, by its name. If the network is not "bridge", it sets the network alias on that network to the given alias, else, it returns an error. This is because network-scoped alias is supported only for containers in user defined networks.
func WithNewNetwork ¶
func WithNewNetwork(ctx context.Context, aliases []string, opts ...network.Option) CustomizeDefinitionOption
WithNewNetwork creates a new network with random name and customizers, and attaches the container to it. Finally it sets the network alias on that network to the given alias.
func WithNoStart ¶
func WithNoStart() CustomizeDefinitionOption
WithNoStart will prevent the container from being started after creation.
func WithPullHandler ¶
func WithPullHandler(handler func(r io.ReadCloser) error) CustomizeDefinitionOption
WithPullOptions is an adapter for the image.WithPullHandler option. It allows to change the default behavior for the pull-image operation.
func WithStartupCommand ¶
func WithStartupCommand(execs ...Executable) CustomizeDefinitionOption
WithStartupCommand will execute the command representation of each Executable into the container. It will leverage the container lifecycle hooks to call the command right after the container is started.
func WithValidateFuncs ¶
func WithValidateFuncs(fn ...func() error) CustomizeDefinitionOption
WithValidateFuncs sets the validate functions for a container. By default, the container is validated using the following functions: - an image is required - mounts are validated The validate functions are executed in the order they are added. If one of the functions returns an error, the container is not created. If no validate functions are provided, the container is validated using the default functions.
func WithWaitStrategy ¶
func WithWaitStrategy(strategies ...wait.Strategy) CustomizeDefinitionOption
WithWaitStrategy replaces the wait strategy for a container, using 60 seconds as deadline
func WithWaitStrategyAndDeadline ¶
func WithWaitStrategyAndDeadline(deadline time.Duration, strategies ...wait.Strategy) CustomizeDefinitionOption
WithWaitStrategyAndDeadline replaces the wait strategy for a container, including deadline
func (CustomizeDefinitionOption) Customize ¶
func (opt CustomizeDefinitionOption) Customize(def *Definition) error
Customize implements the ContainerCustomizer interface.
type Definition ¶
type Definition struct {
// contains filtered or unexported fields
}
Definition is the definition of a container.
func (*Definition) DockerClient ¶
func (d *Definition) DockerClient() client.SDKClient
DockerClient returns the docker client used by the definition.
func (*Definition) HostConfigModifier ¶
func (d *Definition) HostConfigModifier() func(*container.HostConfig)
HostConfigModifier returns the host config modifier of the container.
func (*Definition) Image ¶
func (d *Definition) Image() string
Image returns the image used by the definition.
func (*Definition) ImageSubstitutors ¶
func (d *Definition) ImageSubstitutors() []ImageSubstitutor
ImageSubstitutors returns the image substitutors used by the definition.
func (*Definition) Labels ¶
func (d *Definition) Labels() map[string]string
Labels returns the labels used by the definition.
func (*Definition) Name ¶
func (d *Definition) Name() string
Name returns the name of the container.
func (*Definition) Networks ¶
func (d *Definition) Networks() []string
Networks returns the networks of the container.
type DefinitionHook ¶
type DefinitionHook func(ctx context.Context, def *Definition) error
DefinitionHook is a hook that will be called before a container is started. It can be used to modify the container definition on container creation, using the different lifecycle hooks that are available: - Building - Creating For that, it will receive a Definition, modify it and return an error if needed.
type Executable ¶
type Executable interface {
AsCommand() []string
// Options can container two different types of options:
// - Docker's ExecConfigs (WithUser, WithWorkingDir, WithEnv, etc.)
// - SDK's ProcessOptions (i.e. Multiplexed response)
Options() []exec.ProcessOption
}
Executable represents an executable command to be sent to a container, including options, as part of the different lifecycle hooks.
type File ¶
type File struct {
// Reader the reader to read the file from.
// It takes precedence over [HostPath].
Reader io.Reader
// HostPath the path to the file on the host.
// If [Reader] is not specified, the file will be read from the host path.
HostPath string
// ContainerPath the path to the file in the container.
// Use the slash character that matches the path separator of the operating system
// for the container.
ContainerPath string
// Mode the mode of the file
Mode int64
}
File represents a file that will be copied when container starts
type FileFromContainer ¶
type FileFromContainer struct {
// contains filtered or unexported fields
}
FileFromContainer implements io.ReadCloser and tar.Reader for a single file in a container.
func (*FileFromContainer) Close ¶
func (fc *FileFromContainer) Close() error
Close closes the file from the container.
type ImageSubstitutor ¶
type ImageSubstitutor interface {
// Description returns the name of the type and a short description of how it modifies the image.
// Useful to be printed in logs
Description() string
Substitute(image string) (string, error)
}
ImageSubstitutor represents a way to substitute container image names
type LifecycleHooks ¶
type LifecycleHooks struct {
PreCreates []DefinitionHook
PostCreates []ContainerHook
PreStarts []ContainerHook
PostStarts []ContainerHook
PostReadies []ContainerHook
PreStops []ContainerHook
PostStops []ContainerHook
PreTerminates []ContainerHook
PostTerminates []ContainerHook
}
type StopOption ¶
type StopOption func(*StopOptions)
StopOption is a type that represents an option for stopping a container.
func StopTimeout ¶
func StopTimeout(timeout time.Duration) StopOption
StopTimeout returns a StopOption that sets the timeout. Default: See Container.Stop.
type StopOptions ¶
type StopOptions struct {
// contains filtered or unexported fields
}
StopOptions is a type that holds the options for stopping a container.
func NewStopOptions ¶
func NewStopOptions(ctx context.Context, opts ...StopOption) *StopOptions
NewStopOptions returns a fully initialised StopOptions. Defaults: StopTimeout: 10 seconds.
func (*StopOptions) Context ¶
func (o *StopOptions) Context() context.Context
Context returns the context to use during a Stop or Terminate.
func (*StopOptions) StopTimeout ¶
func (o *StopOptions) StopTimeout() time.Duration
StopTimeout returns the stop timeout to use during a Stop or Terminate.
type TerminableContainer ¶
type TerminableContainer interface {
Terminate(ctx context.Context, opts ...TerminateOption) error
}
TerminableContainer is a container that can be terminated.
type TerminateOption ¶
type TerminateOption func(*TerminateOptions)
TerminateOption is a type that represents an option for terminating a container.
func RemoveVolumes ¶
func RemoveVolumes(volumes ...string) TerminateOption
RemoveVolumes returns a TerminateOption that sets additional volumes to remove. This is useful when the container creates named volumes that should be removed which are not removed by default. Default: nil.
func TerminateTimeout ¶
func TerminateTimeout(timeout time.Duration) TerminateOption
TerminateTimeout returns a TerminateOption that sets the timeout. Default: See Container.Stop.
type TerminateOptions ¶
type TerminateOptions struct {
*StopOptions
// contains filtered or unexported fields
}
TerminateOptions is a type that holds the options for terminating a container.
func NewTerminateOptions ¶
func NewTerminateOptions(ctx context.Context, opts ...TerminateOption) *TerminateOptions
NewTerminateOptions returns a fully initialised TerminateOptions. Defaults: StopTimeout: 10 seconds.
Source Files
¶
- container.exec.go
- container.go
- container.logs.go
- container.network.go
- container.run.go
- container.start.go
- container.stop.go
- container.terminate.go
- definition.go
- files.go
- generate.go
- image_substitutors.go
- inspect.go
- lifecycle.create.go
- lifecycle.go
- lifecycle.start.go
- lifecycle.stop.go
- lifecycle.terminate.go
- options.go
- ports.go
- testing.go
- version.go