Skip to main content

testcontainers_dart 0.2.0 copy "testcontainers_dart: ^0.2.0" to clipboard
testcontainers_dart: ^0.2.0 copied to clipboard

Disposable Docker containers for Dart integration tests, with readiness checks, logs, exec and cleanup.

Testcontainers Dart #

CI Coverage Dart SDK: ^3.13.7 Docker required License: MIT Made with love

Run disposable Docker containers in Dart.

Installation #

Requires Dart 3.13.7+ and a running Docker daemon. The Docker CLI is not required.

dart pub add --dev testcontainers_dart

Quick start #

import 'package:testcontainers_dart/testcontainers_dart.dart';

Future<void> main() async {
  final container = await Testcontainers.run(
    ContainerConfig(
      image: 'redis:7-alpine',
      exposedPorts: const [Port.tcp(6379)],
      waitStrategy: .forSuccessfulCommand(['redis-cli', 'ping']),
    ),
  );

  try {
    final port = await container.mappedPort(6379);
    print('Redis is available on ${container.host}:$port');
  } finally {
    await container.terminate();
  }
}

In package:test, register cleanup immediately after startup:

final container = await Testcontainers.run(config);
addTearDown(container.terminate);

Images are pulled only when missing from the local Docker daemon by default. An omitted tag means latest; prefer an explicit version for reproducible tests.

Container configuration #

ContainerConfig accepts an image, optional name, environment variables, command, TCP/UDP ports, labels, bind mounts and a readiness strategy:

final config = ContainerConfig(
  image: 'redis:7-alpine',
  environment: const {'MODE': 'test'},
  command: const ['redis-server', '--appendonly', 'yes'],
  exposedPorts: const [Port.tcp(6379)],
  labels: const {'project': 'my-app'},
  waitStrategy: .forSuccessfulCommand(['redis-cli', 'ping']),
);

Ports are assigned automatically. Use container.host and await container.mappedPort(port) rather than hardcoding localhost or a host port. For UDP, use Port.udp(port) and mappedPort(port, protocol: 'udp').

Bind mounts use BindMount(source: '/absolute/path', target: '/container/path') and are read-only unless readOnly: false is set. Source paths must exist on the Docker daemon's host, not necessarily the machine running your tests. The org.testcontainers label namespace is reserved.

Image pull policy #

ContainerConfig.pullPolicy and RyukConfig.pullPolicy default to PullPolicy.ifNotPresent:

  • ifNotPresent: use the local image; pull only when Docker reports it missing.
  • always: pull on every startup, even when the image is already cached.
  • never: require a local image; fail without pulling if it is missing.
final container = await Testcontainers.run(
  const ContainerConfig(image: 'my-local-app:test', pullPolicy: .never),
  ryuk: const RyukConfig(pullPolicy: .never),
);

Local images are those on the Docker daemon's host, including locally built images. A cached application image and Ryuk image allow startup without registry access. ifNotPresent does not check for updated tags; use always to refresh them. For ifNotPresent, only an image-inspect 404 triggers a pull; permission, daemon and connection errors are propagated instead of falling back to the registry.

Waiting for readiness #

final config = ContainerConfig(
  image: 'nginx:1.28-alpine',
  exposedPorts: const [Port.tcp(80)],
  waitStrategy: .forAll([
    .forLogMessage('Configuration complete'),
    .forHttp(port: 80),
  ]),
);
Wait.forNothing(); // Default: starts the container without checking readiness.
Wait.forListeningPort(port: 8080);
Wait.forLogMessage(RegExp(r'Listening on port \d+'), times: 1);
Wait.forHttp(port: 8080, path: '/health', statusCode: 200);
Wait.forHealthcheck(); // Requires a Docker HEALTHCHECK in the image.
Wait.forSuccessfulCommand(['redis-cli', 'ping']);
Wait.forAll([firstStrategy, secondStrategy]);

Polling strategies accept timeout (default 60 seconds) and pollInterval (default 100 milliseconds). forAll runs strategies sequentially, each with its own timeout. An open TCP port alone does not prove that a service is ready; prefer an application-level check.

Working with a container #

final info = await container.inspect();
final logs = await container.logs(tail: 100);
final result = await container.exec(['sh', '-c', 'echo hello; echo error >&2']);
print(result.stdout);
print(result.stderr);
print(result.exitCode);
  • exec() takes an argument array. Nonzero exit codes are returned, not thrown.
  • stop(timeout: ...) stops the container but leaves it in Docker.
  • terminate() force-removes the container and its anonymous volumes. It does not remove named volumes or bind-mounted files. Repeated calls are safe; a failed removal can be retried.
  • If startup or readiness fails after creation, cleanup is attempted. ContainerStartException includes the cause, container ID, recent logs and any cleanup failure.

Live logs #

logs() returns a snapshot of the last 1000 lines by default; use logs(tail: null) for all available history. Use logsStream() to receive output while the container is running:

import 'dart:io';

final subscription = container.logsStream(tail: 100).listen(
  (chunk) {
    final output = chunk.source == DockerLogSource.stdout ? stdout : stderr;
    output.write(chunk.text);
  },
  onError: (Object error) => stderr.writeln(error),
);

try {
  // Run your tests.
} finally {
  await subscription.cancel();
}
  • The request starts on subscription. tail: 100 replays the last 100 lines before following new output; tail: 0 receives only new output.
  • Each DockerLogChunk contains a source and a text fragment, not necessarily a complete line. UTF-8 characters are decoded across incoming chunks.
  • TTY containers combine stdout and stderr; their chunks use DockerLogSource.stdout.
  • Cancelling a subscription closes only that log request. Pausing it pauses reading; silence does not trigger a timeout. The connection/header wait is bounded by DockerConfig.requestTimeout.
  • Docker/network errors end the stream with an error. There is no automatic reconnection. Normal EOF ends it without an error.
  • Closing a provider created by DockerProvider.connect() also aborts its active log requests. With an injected Docker API, the caller owns the client's lifetime.

Sharing a provider #

For several containers, share a DockerProvider and close it when finished:

final provider = await DockerProvider.connect();
try {
  final container = await provider.start(config);
  try {
    // Use the container.
  } finally {
    await container.terminate();
  }
} finally {
  provider.close();
}

With cleanup enabled, provider.close() schedules removal of any remaining containers; it does not wait for that removal. Use terminate() for immediate cleanup. Always close shared providers to allow the Dart process to exit.

Docker connection #

Local Docker is detected automatically. Override connection settings with:

Environment variable Purpose
DOCKER_HOST Docker endpoint, e.g. unix:///var/run/docker.sock or tcp://docker:2375
TESTCONTAINERS_HOST_OVERRIDE Reachable address for published container ports

Without DOCKER_HOST, the package checks $HOME/.docker/run/docker.sock, then /var/run/docker.sock. Docker CLI contexts are not read.

For explicit configuration, pass config to Testcontainers.run() or DockerProvider.connect():

final provider = await DockerProvider.connect(
  config: DockerConfig(
    endpoint: Uri.parse('unix:///path/to/docker.sock'),
    requestTimeout: const Duration(minutes: 3),
  ),
);

Unix sockets, HTTP/TCP and HTTPS with system-trusted server certificates are supported. Docker Engine API versions 1.41–1.55 are supported.

Ports bind to 127.0.0.1 by default. For remote Docker, set ContainerConfig.portBindingHost and RyukConfig.portBindingHost to an appropriate daemon interface, and DockerConfig.host to a reachable address. Binding to 0.0.0.0 exposes ports beyond loopback. Only use trusted networks; Docker TCP and Ryuk's port must not be exposed to untrusted clients.

Automatic cleanup #

Ryuk is enabled by default to remove leftover test containers after the test process crashes. Keep using finally or addTearDown for normal cleanup. Ryuk requires read/write access to the daemon's Docker socket, which grants control over Docker. Cleanup depends on Docker and Ryuk remaining available.

Pass ryuk: const RyukConfig(enabled: false) to Testcontainers.run() or DockerProvider.connect() only when cleanup is handled externally. With Ryuk disabled, closing a provider does not remove containers.

Environment variable Purpose
TESTCONTAINERS_RYUK_DISABLED true disables Ryuk; default false
TESTCONTAINERS_RYUK_CONTAINER_IMAGE Override the Ryuk image
TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE Docker socket path on the daemon's host; default /var/run/docker.sock

An explicit RyukConfig takes precedence over these environment variables. It also accepts image, pullPolicy, socketPath, portBindingHost and startupTimeout. startupTimeout bounds the connection wait; Docker API calls and image pulls use DockerConfig.requestTimeout (default two minutes). If the cleanup connection is lost, containers may be removed and new starts on that provider fail; create a new provider.

Packages and examples #

Package Purpose
testcontainers_dart Disposable containers, readiness checks and cleanup
docker_engine Standalone Docker Engine API client

A runnable example is available in examples/testcontainers. From the repository root, with Docker running:

dart run examples/testcontainers/bin/testcontainers_example.dart

Current limitations #

  • No registry authentication, Docker client-certificate environment settings, SSH, Windows named pipes, Compose, image builds, file copy, network management or container reuse.
  • A readiness timeout does not cancel an already running exec command; startup-failure cleanup removes the container instead.
1
likes
140
points
306
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Disposable Docker containers for Dart integration tests, with readiness checks, logs, exec and cleanup.

Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

docker_engine, http

More

Packages that depend on testcontainers_dart