container

package module
v0.1.0-alpha009 Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2025 License: Apache-2.0 Imports: 33 Imported by: 0

README

Docker Containers

This package provides a simple API to create and manage Docker containers.

This library is a fork of github.com/testcontainers/testcontainers-go. Read the NOTICE file for more details.

Installation

go get github.com/docker/go-sdk/container

Usage

The Run function is the main function to create and manage containers. It can be used to create a new container, start it, wait for it to be ready, and stop it. It receives a Go context, and a variadic list of options to customize the container definition:

err = container.Run(ctx, container.WithImage("nginx:alpine"))
if err != nil {
    log.Fatalf("failed to run container: %v", err)
}

Container Definition

The container definition is a struct that contains the configuration for the container. It represents the container's configuration before it's started, and it's used to create the container in the desired state. You can customize the container definition using functional options when calling the Run function. More on this below.

Container Lifecycle Hooks

The container lifecycle hooks are a set of functions that are called at different stages of the container's lifecycle.

  • PreCreate
  • PostCreate
  • PreStart
  • PostStart
  • PostReady
  • PreStop
  • PostStop
  • PreTerminate
  • PostTerminate

They allow you to customize the container's behavior at different stages of its lifecycle, running custom code before or after the container is created, started, ready, stopped or terminated.

Copy Files

It's possible to copy files to the container, and this can happen in different stages of the container's lifecycle:

  • After the container is created but before it's started: using the WithFiles option, you can add files to the container.
  • After the container is started: using the container's CopyToContainer method, you can copy files to the container.

If you need to copy a directory, you can use the CopyDirToContainer method, which uses the parent directory of the container path as the target directory.

It's also possible to copy files from the container to the host, using the container's CopyFromContainer method.

Defining the readiness state for the container

In order to wait for the container to be ready, you can use the WithWaitStrategy options, that can be used to define a custom wait strategy for the container. The library provides some predefined wait strategies in the wait package:

  • ForExec: waits for a command to exit
  • ForExit: waits for a container to exit
  • ForFile: waits for a file to exist
  • ForHealth: waits for a container to be healthy
  • ForListeningPort: waits for a port to be listening
  • ForHTTP: waits for a container to respond to an HTTP request
  • ForLog: waits for a container to log a message
  • ForSQL: waits for a SQL connection to be established
  • ForAll: waits for a combination of strategies

You can also define your own wait strategy by implementing the wait.Strategy interface.

Using wait strategies, you don't need to poll the container state, as the wait strategy will block the execution until the condition is met. This is useful to avoid adding time.Sleep to your code, making it more reliable, even on slower systems.

Customizing the Run function

The Run function can be customized using functional options. The following options are available:

Available Options

The following options are available to customize the container definition:

  • WithAdditionalLifecycleHooks(hooks ...LifecycleHooks) CustomizeDefinitionOption
  • WithAdditionalWaitStrategy(strategies ...wait.Strategy) CustomizeDefinitionOption
  • WithAdditionalWaitStrategyAndDeadline(deadline time.Duration, strategies ...wait.Strategy) CustomizeDefinitionOption
  • WithAfterReadyCommand(execs ...Executable) CustomizeDefinitionOption
  • WithAlwaysPull() CustomizeDefinitionOption
  • WithBridgeNetwork() CustomizeDefinitionOption
  • WithCmd(cmd ...string) CustomizeDefinitionOption
  • WithCmdArgs(cmdArgs ...string) CustomizeDefinitionOption
  • WithConfigModifier(modifier func(config *container.Config)) CustomizeDefinitionOption
  • WithDockerClient(dockerClient *client.Client) CustomizeDefinitionOption
  • WithEndpointSettingsModifier(modifier func(settings map[string]*apinetwork.EndpointSettings)) CustomizeDefinitionOption
  • WithEntrypoint(entrypoint ...string) CustomizeDefinitionOption
  • WithEntrypointArgs(entrypointArgs ...string) CustomizeDefinitionOption
  • WithEnv(envs map[string]string) CustomizeDefinitionOption
  • WithExposedPorts(ports ...string) CustomizeDefinitionOption
  • WithFiles(files ...File) CustomizeDefinitionOption
  • WithHostConfigModifier(modifier func(hostConfig *container.HostConfig)) CustomizeDefinitionOption
  • WithImage(image string) CustomizeDefinitionOption
  • WithImagePlatform(platform string) CustomizeDefinitionOption
  • WithImageSubstitutors(fn ...ImageSubstitutor) CustomizeDefinitionOption
  • WithLabels(labels map[string]string) CustomizeDefinitionOption
  • WithLifecycleHooks(hooks ...LifecycleHooks) CustomizeDefinitionOption
  • WithName(containerName string) CustomizeDefinitionOption
  • WithNetwork(aliases []string, nw *network.Network) CustomizeDefinitionOption
  • WithNetworkName(aliases []string, networkName string) CustomizeDefinitionOption
  • WithNewNetwork(ctx context.Context, aliases []string, opts ...network.Option) CustomizeDefinitionOption
  • WithNoStart() CustomizeDefinitionOption
  • WithStartupCommand(execs ...Executable) CustomizeDefinitionOption
  • WithWaitStrategy(strategies ...wait.Strategy) CustomizeDefinitionOption
  • WithWaitStrategyAndDeadline(deadline time.Duration, strategies ...wait.Strategy) CustomizeDefinitionOption

Please consider that the options using the WithAdditional prefix are cumulative, so you can add multiple options to customize the container definition. On the same hand, the options modifying a map are also cumulative, so you can add multiple options to modify the same map.

For slices, the options are not cumulative, so the last option will override the previous ones. The library offers some helper functions to add elements to the slices, like WithCmdArgs or WithEntrypointArgs, making them cumulative.

The Container type

The Container type is a struct that represents the created container. It provides methods to interact with the container, such as starting, stopping, executing commands, and accessing logs.

Available Methods

The following methods are available on the Container type:

Lifecycle Methods
  • Start(ctx context.Context) error - Starts the container
  • Stop(ctx context.Context, opts ...StopOption) error - Stops the container
  • Terminate(ctx context.Context, opts ...TerminateOption) error - Terminates and removes the container
Information Methods
  • ID() string - Returns the container ID
  • ShortID() string - Returns the short container ID (first 12 characters)
  • Image() string - Returns the image used by the container
  • Host(ctx context.Context) (string, error) - Gets the host of the docker daemon
  • Inspect(ctx context.Context) (*container.InspectResponse, error) - Inspects the container
  • State(ctx context.Context) (*container.State, error) - Gets the container state
Network Methods
  • ContainerIP(ctx context.Context) (string, error) - Gets the container's IP address
  • ContainerIPs(ctx context.Context) ([]string, error) - Gets all container IP addresses
  • NetworkAliases(ctx context.Context) (map[string][]string, error) - Gets network aliases
  • Networks(ctx context.Context) ([]string, error) - Gets network names
Port Methods
  • MappedPort(ctx context.Context, port nat.Port) (nat.Port, error) - Gets the mapped port for a container's exposed port
Execution Methods
  • Exec(ctx context.Context, cmd []string, options ...exec.ProcessOption) (int, io.Reader, error) - Executes a command in the container
File Operations
  • CopyFromContainer(ctx context.Context, containerFilePath string) (io.ReadCloser, error) - Copies a file from the container
  • CopyToContainer(ctx context.Context, fileContent []byte, containerFilePath string, fileMode int64) error - Copies a file to the container
Logging Methods
  • Logger() *slog.Logger - Returns the container's logger, which is a slog.Logger instance, set at the Docker client level
  • Logs(ctx context.Context) (io.ReadCloser, error) - Gets container logs

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
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")
)
View Source
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

View Source
var ErrReuseEmptyName = errors.New("with reuse option a 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.

func Version

func Version() string

Version returns the version of the container package.

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 FromResponse

func FromResponse(_ context.Context, response container.Summary) (*Container, error)

FromResponse builds a container struct from the response of the Docker API

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

func (c *Container) ContainerIP(ctx context.Context) (string, error)

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

func (c *Container) ContainerIPs(ctx context.Context) ([]string, error)

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) DockerClient

func (c *Container) DockerClient() *client.Client

DockerClient returns the docker client used by the container.

func (*Container) Endpoint

func (c *Container) Endpoint(ctx context.Context, proto string) (string, error)

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/docker/docker/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

func (c *Container) Host(ctx context.Context) (string, error)

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) ID

func (c *Container) ID() string

ID returns the container ID

func (*Container) Image

func (c *Container) Image() string

Image returns the image used by the container.

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.ID != "")

	err = ctr.Terminate(context.Background())
	fmt.Println(err)

}
Output:

<nil>
<nil>
true
<nil>

func (*Container) IsRunning

func (c *Container) IsRunning() bool

IsRunning returns the running state of the container.

func (*Container) Logger

func (c *Container) Logger() *slog.Logger

Logger returns the logger for the container.

func (*Container) Logs

func (c *Container) Logs(ctx context.Context) (io.ReadCloser, error)

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

func (c *Container) MappedPort(ctx context.Context, port nat.Port) (nat.Port, error)

MappedPort gets externally mapped port for a container port

func (*Container) NetworkAliases

func (c *Container) NetworkAliases(ctx context.Context) (map[string][]string, error)

NetworkAliases gets the aliases of the container for the networks it is attached to.

func (*Container) Networks

func (c *Container) Networks(ctx context.Context) ([]string, error)

Networks gets the names of the networks the container is attached to.

func (*Container) PortEndpoint

func (c *Container) PortEndpoint(ctx context.Context, port nat.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.

func (*Container) Running

func (c *Container) Running(b bool)

Running sets the running state of the container.

func (*Container) ShortID

func (c *Container) ShortID() string

ShortID returns the short container ID, using the first 12 characters of the ID

func (*Container) Start

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

Start will start an already created container

func (*Container) State

func (c *Container) State(ctx context.Context) (*container.State, error)

State returns container's running state.

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

func (c *Container) WaitingFor() wait.Strategy

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

type ContainerInfo interface {
	ID() string
	Image() string
	ShortID() string
	Logger() *slog.Logger
}

Core interface - always available

type ContainerStateManager

type ContainerStateManager interface {
	IsRunning() bool
	Running(b bool)
}

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 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

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 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 WithDockerClient

func WithDockerClient(dockerClient *client.Client) CustomizeDefinitionOption

WithDockerClient sets the docker client for a container

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.

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 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 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.Client

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) 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.

func (*FileFromContainer) Read

func (fc *FileFromContainer) Read(b []byte) (int, error)

Read reads 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.

func (*TerminateOptions) Cleanup

func (o *TerminateOptions) Cleanup(cli *client.Client) error

Cleanup performs any clean up needed

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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