testcontainers package - github.com/testcontainers/testcontainers-go - Go Packages (original) (raw)

View Source

const ( Bridge = "bridge" Podman = "podman" ReaperDefault = "reaper_default"

)

View Source

const (

TestcontainerLabel = "org.testcontainers.golang"

TestcontainerLabelSessionID = [TestcontainerLabel](#TestcontainerLabel) + ".sessionId"

TestcontainerLabelIsReaper = [TestcontainerLabel](#TestcontainerLabel) + ".reaper"

)

StderrLog is the log type for STDERR

StdoutLog is the log type for STDOUT

View Source

var ( ErrDuplicateMountTarget = errors.New("duplicate mount target detected") ErrInvalidBindMount = errors.New("invalid bind mount") )

View Source

var DefaultLoggingHook = func(logger log.Logger) ContainerLifecycleHooks { shortContainerID := func(c Container) string { return c.GetContainerID()[:12] }

return [ContainerLifecycleHooks](#ContainerLifecycleHooks){
    PreBuilds: [][ContainerRequestHook](#ContainerRequestHook){
        func(_ [context](/context).[Context](/context#Context), req [ContainerRequest](#ContainerRequest)) [error](/builtin#error) {
            logger.Printf("🐳 Building image %s:%s", req.GetRepo(), req.GetTag())
            return [nil](/builtin#nil)
        },
    },
    PostBuilds: [][ContainerRequestHook](#ContainerRequestHook){
        func(_ [context](/context).[Context](/context#Context), req [ContainerRequest](#ContainerRequest)) [error](/builtin#error) {
            logger.Printf("✅ Built image %s", req.Image)
            return [nil](/builtin#nil)
        },
    },
    PreCreates: [][ContainerRequestHook](#ContainerRequestHook){
        func(_ [context](/context).[Context](/context#Context), req [ContainerRequest](#ContainerRequest)) [error](/builtin#error) {
            logger.Printf("🐳 Creating container for image %s", req.Image)
            return [nil](/builtin#nil)
        },
    },
    PostCreates: [][ContainerHook](#ContainerHook){
        func(_ [context](/context).[Context](/context#Context), c [Container](#Container)) [error](/builtin#error) {
            logger.Printf("✅ Container created: %s", shortContainerID(c))
            return [nil](/builtin#nil)
        },
    },
    PreStarts: [][ContainerHook](#ContainerHook){
        func(_ [context](/context).[Context](/context#Context), c [Container](#Container)) [error](/builtin#error) {
            logger.Printf("🐳 Starting container: %s", shortContainerID(c))
            return [nil](/builtin#nil)
        },
    },
    PostStarts: [][ContainerHook](#ContainerHook){
        func(_ [context](/context).[Context](/context#Context), c [Container](#Container)) [error](/builtin#error) {
            logger.Printf("✅ Container started: %s", shortContainerID(c))
            return [nil](/builtin#nil)
        },
    },
    PostReadies: [][ContainerHook](#ContainerHook){
        func(_ [context](/context).[Context](/context#Context), c [Container](#Container)) [error](/builtin#error) {
            logger.Printf("🔔 Container is ready: %s", shortContainerID(c))
            return [nil](/builtin#nil)
        },
    },
    PreStops: [][ContainerHook](#ContainerHook){
        func(_ [context](/context).[Context](/context#Context), c [Container](#Container)) [error](/builtin#error) {
            logger.Printf("🐳 Stopping container: %s", shortContainerID(c))
            return [nil](/builtin#nil)
        },
    },
    PostStops: [][ContainerHook](#ContainerHook){
        func(_ [context](/context).[Context](/context#Context), c [Container](#Container)) [error](/builtin#error) {
            logger.Printf("✅ Container stopped: %s", shortContainerID(c))
            return [nil](/builtin#nil)
        },
    },
    PreTerminates: [][ContainerHook](#ContainerHook){
        func(_ [context](/context).[Context](/context#Context), c [Container](#Container)) [error](/builtin#error) {
            logger.Printf("🐳 Terminating container: %s", shortContainerID(c))
            return [nil](/builtin#nil)
        },
    },
    PostTerminates: [][ContainerHook](#ContainerHook){
        func(_ [context](/context).[Context](/context#Context), c [Container](#Container)) [error](/builtin#error) {
            logger.Printf("🚫 Container terminated: %s", shortContainerID(c))
            return [nil](/builtin#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") )

AddGenericLabels adds the generic labels to target.

CleanupContainer is a helper function that schedules the container to be stopped / terminated when the test ends.

This should be called as a defer directly after (before any error check) of GenericContainer(...) or a modules Run(...) in a test to ensure the container is stopped when the function ends.

before any error check. If container is nil, it's a no-op.

CleanupNetwork is a helper function that schedules the network to be removed when the test ends. This should be the first call after NewNetwork(...) in a test before any error check. If network is nil, it's a no-op.

DockerImageAuth returns the auth config for the given Docker image, extracting first its Docker registry. Finally, it will use the credential helpers to extract the information from the docker config file for that registry, if it exists.

func ExtractDockerSocket() string

Deprecated: use MustExtractDockerHost instead.

GenericLabels returns a map of labels that can be used to identify resources created by this library. This includes the standard LabelSessionID if the reaper is enabled, otherwise this is excluded to prevent resources being incorrectly reaped.

MustExtractDockerSocket Extracts the docker socket from the different alternatives, removing the socket schema. Use this function to get the docker socket path, not the host (e.g. mounting the socket in a container). This function does not consider Windows containers at the moment. The possible alternatives are:

  1. Docker host from the "tc.host" property in the ~/.testcontainers.properties file.
  2. The TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE environment variable.
  3. Using a Docker client, check if the Info().OperatingSystem is "Docker Desktop" and return the default docker socket path for rootless docker.
  4. Else, Get the current Docker Host from the existing strategies: see MustExtractDockerHost.
  5. If the socket contains the unix schema, the schema is removed (e.g. unix:///var/run/docker.sock -> /var/run/docker.sock)
  6. Else, the default location of the docker socket is used (/var/run/docker.sock)

It panics if a Docker client cannot be created, or the Docker host cannot be discovered.

Deprecated: Use NewDockerClientWithOpts instead.

RequireContainerExec is a helper function that executes a command in a container It insures that there is no error during the execution Finally returns the output of its execution

SessionID returns a unique session ID for the current test session. Because each Go package will be run in a separate process, we need a way to identify the current test session. By test session, we mean:

As a consequence, with the sole goal of aggregating test execution across multiple packages, this variable will contain the value of the parent process ID (pid) of the current process and its creation date, to use it to generate a unique session ID. We are using the parent pid because the current process will be a child process of:

Finally, we will hash the combination of the "testcontainers-go:" string with the parent pid and the creation date of that parent process to generate a unique session ID.

This sessionID will be used to:

SkipIfDockerDesktop is a utility function capable of skipping tests if tests are run using Docker Desktop.

SkipIfNotDockerDesktop is a utility function capable of skipping tests if tests are not run using Docker Desktop.

func SkipIfProviderIsNotHealthy(t *testing.T)

SkipIfProviderIsNotHealthy is a utility function capable of skipping tests if the provider is not healthy, or running at all. This is a function designed to be used in your test, when Docker is not mandatory for CI/CD. In this way tests that depend on Testcontainers won't run if the provider is provisioned correctly.

SkipIfProviderIsNotHealthy(&testing.T{})

func TerminateContainer(container Container, options ...TerminateOption) error

TerminateContainer calls [Container.Terminate] on the container if it is not nil.

This should be called as a defer directly after GenericContainer(...) or a modules Run(...) to ensure the container is terminated when the function ends.

Deprecated: use Files or HostConfigModifier in the ContainerRequest, or copy files container APIs to make containers portable across Docker environments BindMounter can optionally be implemented by mount sources to support advanced scenarios based on mount.BindOptions

type Container interface { GetContainerID() string
Endpoint(context.Context, string) (string, error)
PortEndpoint(ctx context.Context, port nat.Port, proto string) (string, error) Host(context.Context) (string, error)
Inspect(context.Context) (*container.InspectResponse, error)
MappedPort(context.Context, nat.Port) (nat.Port, error)
Ports(context.Context) (nat.PortMap, error)
SessionID() string
IsRunning() bool
Start(context.Context) error
Stop(context.Context, *time.Duration) error

Terminate(ctx [context](/context).[Context](/context#Context), opts ...[TerminateOption](#TerminateOption)) [error](/builtin#error)

Logs([context](/context).[Context](/context#Context)) ([io](/io).[ReadCloser](/io#ReadCloser), [error](/builtin#error))                    
FollowOutput([LogConsumer](#LogConsumer))                                       
StartLogProducer([context](/context).[Context](/context#Context), ...[LogProductionOption](#LogProductionOption)) [error](/builtin#error) 
StopLogProducer() [error](/builtin#error)                                         
Name([context](/context).[Context](/context#Context)) ([string](/builtin#string), [error](/builtin#error))                           
State([context](/context).[Context](/context#Context)) (*[container](/github.com/docker/docker/api/types/container).[State](/github.com/docker/docker/api/types/container#State), [error](/builtin#error))                
Networks([context](/context).[Context](/context#Context)) ([][string](/builtin#string), [error](/builtin#error))                     
NetworkAliases([context](/context).[Context](/context#Context)) (map[[string](/builtin#string)][][string](/builtin#string), [error](/builtin#error))    
Exec(ctx [context](/context).[Context](/context#Context), cmd [][string](/builtin#string), options ...[tcexec](/github.com/testcontainers/testcontainers-go@v0.40.0/exec).[ProcessOption](/github.com/testcontainers/testcontainers-go@v0.40.0/exec#ProcessOption)) ([int](/builtin#int), [io](/io).[Reader](/io#Reader), [error](/builtin#error))
ContainerIP([context](/context).[Context](/context#Context)) ([string](/builtin#string), [error](/builtin#error))    
ContainerIPs([context](/context).[Context](/context#Context)) ([][string](/builtin#string), [error](/builtin#error)) 
CopyToContainer(ctx [context](/context).[Context](/context#Context), fileContent [][byte](/builtin#byte), containerFilePath [string](/builtin#string), fileMode [int64](/builtin#int64)) [error](/builtin#error)
CopyDirToContainer(ctx [context](/context).[Context](/context#Context), hostDirPath [string](/builtin#string), containerParentPath [string](/builtin#string), fileMode [int64](/builtin#int64)) [error](/builtin#error)
CopyFileToContainer(ctx [context](/context).[Context](/context#Context), hostFilePath [string](/builtin#string), containerFilePath [string](/builtin#string), fileMode [int64](/builtin#int64)) [error](/builtin#error)
CopyFileFromContainer(ctx [context](/context).[Context](/context#Context), filePath [string](/builtin#string)) ([io](/io).[ReadCloser](/io#ReadCloser), [error](/builtin#error))
GetLogProductionErrorChannel() <-chan [error](/builtin#error)

}

Container allows getting info about and controlling a single container instance

GenericContainer creates a generic container with parameters

ctx := context.Background()

// buildFromDockerfileWithModifier { c, err := Run(ctx, "", WithDockerfile(FromDockerfile{ Context: "testdata", Dockerfile: "target.Dockerfile", KeepImage: false, BuildOptionsModifier: func(buildOptions *build.ImageBuildOptions) { buildOptions.Target = "target2" }, }), ) // } defer func() { if err := TerminateContainer(c); err != nil { log.Printf("failed to terminate container: %s", err) } }() if err != nil { log.Printf("failed to start container: %v", err) return }

r, err := c.Logs(ctx) if err != nil { log.Printf("failed to get logs: %v", err) return }

logs, err := io.ReadAll(r) if err != nil { log.Printf("failed to read logs: %v", err) return }

fmt.Println(string(logs))

Output:

target2

ctx := context.Background()

// applyImageSubstitutors { ctr, err := testcontainers.Run(ctx, "alpine:latest", testcontainers.WithImageSubstitutors(dockerImageSubstitutor{})) defer func() { if err := testcontainers.TerminateContainer(ctr); err != nil { log.Printf("failed to terminate container: %s", err) } }()

// } if err != nil { log.Printf("could not start container: %v", err) return }

fmt.Println(ctr.Image)

Output:

registry.hub.docker.com/library/alpine:latest

ParallelContainers creates a generic containers with parameters and run it in parallel mode

type ContainerCustomizer interface { Customize(req *GenericContainerRequest) error }

ContainerCustomizer is an interface that can be used to configure the Testcontainers container request. The passed request will be merged with the default one.

ContainerHook is a hook that will be 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 For that, it will receive a Container, modify it and return an error if needed.

type ContainerLifecycleHooks struct { PreBuilds []ContainerRequestHook PostBuilds []ContainerRequestHook PreCreates []ContainerRequestHook PostCreates []ContainerHook PreStarts []ContainerHook PostStarts []ContainerHook PostReadies []ContainerHook PreStops []ContainerHook PostStops []ContainerHook PreTerminates []ContainerHook PostTerminates []ContainerHook }

ContainerLifecycleHooks is a struct that contains all the hooks that can be used to modify the container lifecycle. All the container lifecycle hooks except the PreCreates hooks will be passed to the container once it's created

Building is a hook that will be called before a container image is built.

Building is a hook that will be called before a container image is built.

Created is a hook that will be called after a container is created

Creating is a hook that will be called before a container is created.

Readied is a hook that will be called after a container is ready

Started is a hook that will be called after a container is started

Starting is a hook that will be called before a container is started

Stopped is a hook that will be called after a container is stopped

Stopping is a hook that will be called before a container is stopped

Terminated is a hook that will be called after a container is terminated

Terminating is a hook that will be called before a container is terminated

type ContainerMount struct {

Source [ContainerMountSource](#ContainerMountSource)

Target [ContainerMountTarget](#ContainerMountTarget)

ReadOnly [bool](/builtin#bool)

}

ContainerMount models a mount into a container

Deprecated: use Files or HostConfigModifier in the ContainerRequest, or copy files container APIs to make containers portable across Docker environments BindMount returns a new ContainerMount with a GenericBindMountSource as source This is a convenience method to cover typical use cases.

ImageMount returns a new ContainerMount with a GenericImageMountSource as source This is a convenience method to cover typical use cases.

func VolumeMount(volumeName string, mountTarget ContainerMountTarget) ContainerMount

VolumeMount returns a new ContainerMount with a GenericVolumeMountSource as source This is a convenience method to cover typical use cases.

type ContainerMountSource interface {

Source() [string](/builtin#string)


Type() [MountType](#MountType)

}

ContainerMountSource is the base for all mount sources

type ContainerMountTarget string

ContainerMountTarget represents the target path within a container where the mount will be available Note that mount targets must be unique. It's not supported to mount different sources to the same target.

type ContainerMounts []ContainerMount

ContainerMounts represents a collection of mounts for a container

func Mounts(mounts ...ContainerMount) ContainerMounts

Mounts returns a ContainerMounts to support a more fluent API

PrepareMounts maps the given []ContainerMount to the corresponding []mount.Mount for further processing

type ContainerOption func(*containerOptions)

Deprecated: it will be removed in the next major release functional option for setting the reaper image

Deprecated: it will be removed in the next major release WithImageName sets the reaper image name

func WithRegistryCredentials(registryCredentials string) ContainerOption

Deprecated: Testcontainers will detect registry credentials automatically, and it will be removed in the next major release WithRegistryCredentials sets the reaper registry credentials

ContainerProvider allows the creation of containers on an arbitrary system

ContainerRequest represents the parameters used to get a running container

BuildLogWriter returns the io.Writer for output of log when building a Docker image from a Dockerfile. It returns the BuildLogWriter from the ContainerRequest, defaults to io.Discard. For backward compatibility, if BuildLogWriter is default and PrintBuildLog is true, the function returns os.Stderr.

BuildOptions returns the image build options when building a Docker image from a Dockerfile. It will apply some defaults and finally call the BuildOptionsModifier from the FromDockerfile struct, if set.

Deprecated: Testcontainers will detect registry credentials automatically, and it will be removed in the next major release. GetAuthConfigs returns the auth configs to be able to pull from an authenticated docker registry. Panics if an error occurs.

GetBuildArgs returns the env args to be used when creating from Dockerfile

GetContext retrieve the build context for the request Must be closed when no longer needed.

GetDockerfile returns the Dockerfile from the ContainerRequest, defaults to "Dockerfile". Sets FromDockerfile.Dockerfile to the default if blank.

GetRepo returns the Repo label for image from the ContainerRequest, defaults to UUID. Sets FromDockerfile.Repo to the default value if blank.

GetTag returns the Tag label for image from the ContainerRequest, defaults to UUID. Sets FromDockerfile.Tag to the default value if blank.

func (c *ContainerRequest) ShouldBuildImage() bool

func (c *ContainerRequest) ShouldKeepBuiltImage() bool

Validate ensures that the ContainerRequest does not have invalid parameters configured to it ex. make sure you are not specifying both an image as well as a context

ContainerRequestHook is a hook that will be called before a container is created. It can be used to modify container configuration before it is created, using the different lifecycle hooks that are available: - Creating For that, it will receive a ContainerRequest, modify it and return an error if needed.

type CustomHubSubstitutor struct {

}

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(hub string) CustomHubSubstitutor

NewCustomHubSubstitutor creates a new CustomHubSubstitutor

Description returns the name of the type and a short description of how it modifies the image.

Substitute replaces the hub of the image with the provided one, with certain conditions:

type CustomizeRequestOption func(req *GenericContainerRequest) error

CustomizeRequestOption is a type that can be used to configure the Testcontainers container request. The passed request will be merged with the default one.

func CustomizeRequest(src GenericContainerRequest) CustomizeRequestOption

CustomizeRequest returns a function that can be used to merge the passed container request with the one that is used by the container. Slices and Maps will be appended.

func WithAdditionalLifecycleHooks(hooks ...ContainerLifecycleHooks) CustomizeRequestOption

WithAdditionalLifecycleHooks appends lifecycle hooks to the existing ones for a container

WithAdditionalWaitStrategy appends the wait strategy for a container, using 60 seconds as deadline

func WithAfterReadyCommand added in v0.28.0

func WithAfterReadyCommand(execs ...Executable) CustomizeRequestOption

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() CustomizeRequestOption

WithAlwaysPull will pull the image before starting the container

WithCmd completely replaces the command for a container

WithCmdArgs appends the command arguments to the command for a container

WithConfigModifier allows to override the default container config

func WithDockerfile(df FromDockerfile) CustomizeRequestOption

WithDockerfile allows to build a container from a Dockerfile

WithEndpointSettingsModifier allows to override the default endpoint settings

func WithEntrypoint(entrypoint ...string) CustomizeRequestOption

WithEntrypoint completely replaces the entrypoint of a container

func WithEntrypointArgs(entrypointArgs ...string) CustomizeRequestOption

WithEntrypointArgs appends the entrypoint arguments to the entrypoint of a container

WithEnv sets the environment variables for a container. If the environment variable already exists, it will be overridden.

WithExposedPorts appends the ports to the exposed ports for a container

func WithFiles(files ...ContainerFile) CustomizeRequestOption

WithFiles appends the files to the files for a container

WithHostConfigModifier allows to override the default host config

func WithHostPortAccess(ports ...int) CustomizeRequestOption

WithHostPortAccess allows to expose the host ports to the container

WithImage sets the image for a container

WithImageMount mounts an image to a container, passing the source image name, the relative subpath to mount in that image, and the mount point in the target container. This option validates that the subpath is a relative path, raising an error otherwise.

WithImagePlatform sets the platform for a container

func WithImageSubstitutors(fn ...ImageSubstitutor) CustomizeRequestOption

WithImageSubstitutors sets the image substitutors for a container

WithLabels appends the labels to the labels for a container

func WithLifecycleHooks(hooks ...ContainerLifecycleHooks) CustomizeRequestOption

WithLifecycleHooks completely replaces the lifecycle hooks for a container

func WithLogConsumerConfig(config *LogConsumerConfig) CustomizeRequestOption

WithLogConsumerConfig sets the log consumer config for a container. Beware that this option completely replaces the existing log consumer config, including the log consumers and the log production options, so it should be used with care.

func WithLogConsumers(consumer ...LogConsumer) CustomizeRequestOption

WithLogConsumers sets the log consumers for a container

func WithMounts(mounts ...ContainerMount) CustomizeRequestOption

WithMounts appends the mounts to the mounts for a container

WithName will set the name of the container.

func WithNoStart() CustomizeRequestOption

WithNoStart will prevent the container from being started after creation.

func WithProvider(provider ProviderType) CustomizeRequestOption

WithProvider sets the provider type for a container

func WithReuseByName(containerName string) CustomizeRequestOption

WithReuseByName will mark a container to be reused if it exists or create a new one if it doesn't. A container name must be provided to identify the container to be reused.

func WithStartupCommand added in v0.25.0

func WithStartupCommand(execs ...Executable) CustomizeRequestOption

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.

WithTmpfs appends the tmpfs mounts to the tmpfs mounts for a container

WithWaitStrategy replaces the wait strategy for a container, using 60 seconds as deadline

func WithWaitStrategyAndDeadline added in v0.20.0

WithWaitStrategyAndDeadline replaces the wait strategy for a container, including deadline

Deprecated: will be removed in the future.

func (n DefaultNetwork) ApplyDockerTo(opts *DockerProviderOptions)

Deprecated: will be removed in the future.

func (n DefaultNetwork) ApplyGenericTo(opts *GenericProviderOptions)

Deprecated: will be removed in the future.

DeprecatedContainer shows methods that were supported before, but are now deprecated Deprecated: Use Container

Deprecated: use Files or HostConfigModifier in the ContainerRequest, or copy files container APIs to make containers portable across Docker environments

Deprecated: use Files or HostConfigModifier in the ContainerRequest, or copy files container APIs to make containers portable across Docker environments

Deprecated: use Files or HostConfigModifier in the ContainerRequest, or copy files container APIs to make containers portable across Docker environments

func (DockerBindMountSource) Type() MountType

Deprecated: use Files or HostConfigModifier in the ContainerRequest, or copy files container APIs to make containers portable across Docker environments

DockerClient is a wrapper around the docker client that is used by testcontainers-go. It implements the SystemAPIClient interface in order to cache the docker info and reuse it.

DiskUsage returns the disk usage of all images.

Events returns a channel to listen to events that happen to the docker daemon.

Info returns information about the docker server. The result of Info is cached and reused every time Info is called. It will also print out the docker server info, and the resolved Docker paths, to the default logger.

Ping pings the docker server.

RegistryLogin logs into a Docker registry.

DockerContainer represents a container started using Docker

Run is a convenience function that creates a new container and starts it. It calls the GenericContainer function and returns a concrete DockerContainer type.

ctx := context.Background()

nw, err := network.New(ctx) if err != nil { log.Printf("failed to create network: %s", err) return } defer func() { if err := nw.Remove(ctx); err != nil { log.Printf("failed to remove network: %s", err) } }()

testFileContent := "Hello from file!"

ctr, err := testcontainers.Run( ctx, "nginx:alpine", network.WithNetwork([]string{"nginx-alias"}, nw), testcontainers.WithFiles(testcontainers.ContainerFile{ Reader: strings.NewReader(testFileContent), ContainerFilePath: "/tmp/file.txt", FileMode: 0o644, }), testcontainers.WithTmpfs(map[string]string{ "/tmp": "rw", }), testcontainers.WithLabels(map[string]string{ "testcontainers.label": "true", }), testcontainers.WithEnv(map[string]string{ "TEST": "true", }), testcontainers.WithExposedPorts("80/tcp"), testcontainers.WithAfterReadyCommand(testcontainers.NewRawCommand([]string{"echo", "hello", "world"})), testcontainers.WithWaitStrategy(wait.ForListeningPort("80/tcp").WithStartupTimeout(time.Second*5)), ) defer func() { if err := testcontainers.TerminateContainer(ctr); err != nil { log.Printf("failed to terminate container: %s", err) } }() if err != nil { log.Printf("failed to start container: %s", err) return }

state, err := ctr.State(ctx) if err != nil { log.Printf("failed to get container state: %s", err) return } fmt.Println(state.Running)

cli, err := testcontainers.NewDockerClientWithOpts(ctx) if err != nil { log.Printf("failed to create docker client: %s", err) return }

ctrResp, err := cli.ContainerInspect(ctx, ctr.GetContainerID()) if err != nil { log.Printf("failed to inspect container: %s", err) return }

// networks respNw, ok := ctrResp.NetworkSettings.Networks[nw.Name] if !ok { log.Printf("network not found") return } fmt.Println(respNw.Aliases)

// env fmt.Println(ctrResp.Config.Env[0])

// tmpfs tmpfs, ok := ctrResp.HostConfig.Tmpfs["/tmp"] if !ok { log.Printf("tmpfs not found") return } fmt.Println(tmpfs)

// labels fmt.Println(ctrResp.Config.Labels["testcontainers.label"])

// files // copyFileFromContainer { f, err := ctr.CopyFileFromContainer(context.Background(), "/tmp/file.txt") if err != nil { log.Printf("failed to copy file from container: %s", err) return }

content, err := io.ReadAll(f) if err != nil { log.Printf("failed to read file: %s", err) return } // } fmt.Println(string(content))

Output:

true [nginx-alias] TEST=true rw true Hello from file!

ContainerIP gets the IP address of the primary network within the container.

ContainerIPs gets the IP addresses of all the networks within the container.

CopyDirToContainer copies the contents of a directory to a parent path in the container. This parent path must exist in the container first as we cannot create it

CopyToContainer copies fileContent data to a file in container

Endpoint gets proto://host:port string for the lowest numbered exposed port Will returns just host:port if proto is ""

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.Readermay result in unexpected bytes due to custom stream multiplexing headers. Use tcexec.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.

func (c *DockerContainer) FollowOutput(consumer LogConsumer)

Deprecated: use the ContainerRequest.LogConsumerConfig field instead.

func (c *DockerContainer) GetLogProductionErrorChannel() <-chan error

GetLogProductionErrorChannel exposes the only way for the consumer to be able to listen to errors and react to them.

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 You can use the "TESTCONTAINERS_HOST_OVERRIDE" env variable to set this yourself

Inspect gets the raw container info

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.

MappedPort gets externally mapped port for a container port

Deprecated: use c.Inspect(ctx).Name instead. Name gets the name of the container.

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

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

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.

Deprecated: use c.Inspect(ctx).NetworkSettings.Ports instead. Ports gets the exposed ports for the container.

SessionID gets the current session id

SetLogger sets the logger for the container

func (c *DockerContainer) SetProvider(provider *DockerProvider)

SetProvider sets the provider for the container

func (c *DockerContainer) SetTerminationSignal(signal chan bool)

SetTerminationSignal sets the termination signal for the container

Start will start an already created container

Deprecated: use the ContainerRequest.LogConsumerConfig field instead.

State returns container's running state.

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 the timeout is nil, the container's StopTimeout value is used, if set, 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:

If the container is already stopped, the method is a no-op.

func (c *DockerContainer) StopLogProducer() error

Deprecated: it will be removed in the next major release.

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:

Default: timeout is 10 seconds.

type DockerImageMountSource struct {

}

DockerImageMountSource is a mount source for an image

NewDockerImageMountSource creates a new DockerImageMountSource

ImageOptions returns the image options for the image mount

Source returns the image name for the image mount

func (s DockerImageMountSource) Type() MountType

Type returns the mount type for the image mount

Validate validates the source of the mount, ensuring that the subpath is a relative path

DockerNetwork represents a network started using Docker

Remove is used to remove the network. It is usually triggered by as defer function.

func (n *DockerNetwork) SetTerminationSignal(signal chan bool)

type DockerProvider struct { *DockerProviderOptions

}

DockerProvider implements the ContainerProvider interface

func NewDockerProvider(provOpts ...DockerProviderOption) (*DockerProvider, error)

NewDockerProvider creates a Docker provider with the EnvClient

BuildImage will build and image from context and Dockerfile, then return the tag

Client gets the docker client used by the provider

Close closes the docker client used by the provider

func (p *DockerProvider) Config() TestcontainersConfig

Config provides the TestcontainersConfig read from $HOME/.testcontainers.properties or the environment variables

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

CreateContainer fulfils a request for a container without starting it

ctx := context.Background() nginxC, err := Run( ctx, nginxAlpineImage, WithExposedPorts("80/tcp"), WithWaitStrategy(wait.ForHTTP("/").WithStartupTimeout(10*time.Second)), ) defer func() { if err := TerminateContainer(nginxC); err != nil { log.Printf("failed to terminate container: %s", err) } }() if err != nil { log.Printf("failed to create container: %s", err) return }

state, err := nginxC.State(ctx) if err != nil { log.Printf("failed to get container state: %s", err) return }

fmt.Println(state.Running)

Output:

true

Deprecated: use network.New instead CreateNetwork returns the object representing a new network identified by its name

DaemonHost gets the host or ip of the Docker daemon where ports are exposed on Warning: this is based on your Docker host setting. Will fail if using an SSH tunnel You can use the "TESTCONTAINERS_HOST_OVERRIDE" env variable to set this yourself

GetNetwork returns the object representing the network identified by its name

Health measure the healthiness of the provider. Right now we leverage the docker-client Info endpoint to see if the daemon is reachable.

ListImages list images from the provider. If an image has multiple Tags, each tag is reported individually with the same ID and same labels

PullImage pulls image from registry

RunContainer takes a RequestContainer as input and it runs a container via the docker sdk

SaveImages exports a list of images as an uncompressed tar

SaveImagesWithOpts exports a list of images as an uncompressed tar, passing options to the provider

SetClient sets the docker client to be used by the provider

type DockerProviderOption interface { ApplyDockerTo(opts *DockerProviderOptions) }

DockerProviderOption defines a common interface to modify DockerProviderOptions These can be passed to NewDockerProvider in a variadic way to customize the returned DockerProvider instance

func Generic2DockerOptions(opts ...GenericProviderOption) []DockerProviderOption

func WithDefaultBridgeNetwork(bridgeNetworkName string) DockerProviderOption

type DockerProviderOptionFunc func(opts *DockerProviderOptions)

DockerProviderOptionFunc is a shorthand to implement the DockerProviderOption interface

func (f DockerProviderOptionFunc) ApplyDockerTo(opts *DockerProviderOptions)

type DockerProviderOptions struct { *GenericProviderOptions

}

DockerProviderOptions defines options applicable to DockerProvider

type ExecOptions struct {

}

ExecOptions is a struct that provides a default implementation for the Options method of the Executable interface.

Executable represents an executable command to be sent to a container, including options, as part of the different lifecycle hooks.

type FileFromContainer struct {

}

FromDockerfile represents the parameters needed to build an image from a Dockerfile rather than using a pre-built one

type GenericBindMountSource struct {

HostPath [string](/builtin#string)

}

Deprecated: use Files or HostConfigModifier in the ContainerRequest, or copy files container APIs to make containers portable across Docker environments GenericBindMountSource implements ContainerMountSource and represents a bind mount Optionally mount.BindOptions might be added for advanced scenarios

Deprecated: use Files or HostConfigModifier in the ContainerRequest, or copy files container APIs to make containers portable across Docker environments

Deprecated: use Files or HostConfigModifier in the ContainerRequest, or copy files container APIs to make containers portable across Docker environments

GenericContainerRequest represents parameters to a generic container

type GenericImageMountSource struct {

}

GenericImageMountSource implements ContainerMountSource and represents an image mount

NewGenericImageMountSource creates a new GenericImageMountSource

Source returns the name of the image to be mounted

Type returns the type of the mount

Validate validates the source of the mount

type GenericNetworkRequest struct { NetworkRequest
ProviderType ProviderType }

Deprecated: will be removed in the future. GenericNetworkRequest represents parameters to a generic network

type GenericProvider interface { ContainerProvider NetworkProvider ImageProvider }

GenericProvider represents an abstraction for container and network providers

type GenericProviderOption interface { ApplyGenericTo(opts *GenericProviderOptions) }

GenericProviderOption defines a common interface to modify GenericProviderOptions These options can be passed to GetProvider in a variadic way to customize the returned GenericProvider instance

type GenericProviderOptionFunc func(opts *GenericProviderOptions)

GenericProviderOptionFunc is a shorthand to implement the GenericProviderOption interface

func (f GenericProviderOptionFunc) ApplyGenericTo(opts *GenericProviderOptions)

type GenericProviderOptions struct { Logger log.Logger

}

GenericProviderOptions defines options applicable to all providers

type GenericTmpfsMountSource struct{}

GenericTmpfsMountSource implements ContainerMountSource and represents a TmpFS mount Optionally mount.TmpfsOptions might be added for advanced scenarios

type GenericVolumeMountSource struct {

Name [string](/builtin#string)

}

GenericVolumeMountSource implements ContainerMountSource and represents a volume mount

ImageBuildInfo defines what is needed to build an image

ImageInfo represents summary information of an image

ImageMounter can optionally be implemented by mount sources to support advanced scenarios based on mount.ImageOptions

ImageProvider allows manipulating images

ImageSubstitutor represents a way to substitute container image names

Log represents a message that was created by a process, LogType is either "STDOUT" or "STDERR", Content is the byte contents of the message itself

type LogConsumer interface { Accept(Log) }

LogConsumer represents any object that can handle a Log, it is up to the LogConsumer instance what to do with the log

type LogConsumerConfig struct { Opts []LogProductionOption Consumers []LogConsumer
}

LogConsumerConfig is a configuration object for the producer/consumer pattern

type LogProductionOption func(*DockerContainer)

WithLogProductionTimeout is a functional option that sets the timeout for the log production. If the timeout is lower than 5s or greater than 60s it will be set to 5s or 60s respectively.

type LoggerOption struct {

}

LoggerOption is a generic option that sets the logger to be used.

It can be used to set the logger for providers and containers.

WithLogger returns a generic option that sets the logger to be used.

Consider calling this before other "With functions" as these may generate logs.

This can be given a TestLogger to collect the logs from testcontainers into a test case.

func (o LoggerOption) ApplyDockerTo(opts *DockerProviderOptions)

ApplyDockerTo implements DockerProviderOption.

func (o LoggerOption) ApplyGenericTo(opts *GenericProviderOptions)

ApplyGenericTo implements GenericProviderOption.

Customize implements ContainerCustomizer.

const ( MountTypeBind MountType = iota MountTypeVolume MountTypeTmpfs MountTypePipe MountTypeImage )

Deprecated: will be removed in the future Network allows getting info about a single network instance

Deprecated: use network.New instead GenericNetwork creates a generic network with parameters

NetworkProvider allows the creation of networks on an arbitrary system

Deprecated: will be removed in the future NetworkRequest represents the parameters used to get a network

type ParallelContainerRequest []GenericContainerRequest

type ParallelContainersError struct { Errors []ParallelContainersRequestError }

type ParallelContainersOptions struct { WorkersCount int }

ParallelContainersOptions represents additional options for parallel running

type ParallelContainersRequestError struct { Request GenericContainerRequest Error error }

ParallelContainersRequestError represents error from parallel request

ProviderType is an enum for the possible providers

const ( ProviderDefault ProviderType = iota ProviderDocker ProviderPodman )

possible provider types

GetProvider provides the provider implementation for a certain type

type RawCommand added in v0.27.0

type RawCommand struct { ExecOptions

}

RawCommand is a type that implements Executable and represents a command to be sent to a container

func (RawCommand) AsCommand added in v0.27.0

AsCommand returns the command as a slice of strings

Reaper is used to start a sidecar container that cleans up resources

NewReaper creates a Reaper with a sessionID to identify containers and a provider to use Deprecated: it's not possible to create a reaper any more. Compose module uses this method to create a reaper for the compose stack.

The caller must call Connect at least once on the returned Reaper and use the returned result otherwise the reaper will be kept open until the process exits.

Connect connects to the reaper container and sends the labels to it so that it can clean up the containers with the same labels.

It returns a channel that can be closed to terminate the connection. Returns an error if config.RyukDisabled is true.

Labels returns the container labels to use so that this Reaper cleans them up Deprecated: internally replaced by core.DefaultLabels(sessionID)

ReaperProvider represents a provider for the reaper to run itself with The ContainerProvider interface should usually satisfy this as well, so it is pluggable

type SaveImageOption func(*saveImageOptions) error

type StdoutLogConsumer struct{}

StdoutLogConsumer is a LogConsumer that prints the log to stdout

func (lc *StdoutLogConsumer) Accept(l Log)

Accept prints the log to stdout

type TerminateOption func(*TerminateOptions)

TerminateOption is a type that represents an option for terminating a container.

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.

StopContext returns a TerminateOption that sets the context. Default: context.Background().

StopTimeout returns a TerminateOption that sets the timeout. Default: See [Container.Stop].

type TerminateOptions struct {

}

TerminateOptions is a type that holds the options for terminating a container.

NewTerminateOptions returns a fully initialised TerminateOptions. Defaults: StopTimeout: 10 seconds.

Cleanup performs any clean up needed

Context returns the context to use during a Terminate.

StopTimeout returns the stop timeout to use during a Terminate.

type TestcontainersConfig struct { Host string properties:"docker.host,default="
TLSVerify int properties:"docker.tls.verify,default=0"
CertPath string properties:"docker.cert.path,default="
RyukDisabled bool properties:"ryuk.disabled,default=false"
RyukPrivileged bool properties:"ryuk.container.privileged,default=false" Config config.Config }

TestcontainersConfig represents the configuration for Testcontainers

func ReadConfig() TestcontainersConfig

ReadConfig reads from testcontainers properties file, storing the result in a singleton instance of the TestcontainersConfig struct

TmpfsMounter can optionally be implemented by mount sources to support advanced scenarios based on mount.TmpfsOptions

type Validator interface {

Validate() [error](/builtin#error)

}

Validator is an interface that can be implemented by types that need to validate their state.

VolumeMounter can optionally be implemented by mount sources to support advanced scenarios based on mount.VolumeOptions