
testcontainers
Testcontainers skills for writing reliable integration tests with Docker containers across multiple languages (Go, .NET, Python, and more)
- version
- 1.0.0
- GitHub stars
- 20
Install
/plugin install testcontainers@testcontainers-claude-skillsRun it inside Claude Code after adding the marketplace with /plugin marketplace add testcontainers/claude-skills.
Contents
Discovered from sourceSkills 2
Testcontainers for .NET Integration Testing
A comprehensive guide for using Testcontainers for .NET (4.10.0+) to write reliable integration tests with Docker containers in .NET projects.
Description
This skill helps you write integration tests using Testcontainers for .NET, a .NET library that provides lightweight, throwaway instances of common databases, message queues, web browsers, or anything that can run in a Docker container.
Key capabilities:
- Use 65+ pre-configured modules for common services (databases, message queues, cloud services, etc.)
- Set up and manage Docker containers in .NET tests (xUnit, NUnit, MSTest)
- Configure networking, volumes, and environment variables
- Implement proper cleanup and resource management
- Debug and troubleshoot container issues
When to Use This Skill
Use this skill when you need to:
- Write integration tests that require real services (databases, message queues, etc.)
- Test against multiple versions or configurations of dependencies
- Create reproducible test environments
- Avoid mocking external dependencies in integration tests
- Set up ephemeral test infrastructure
Decision Rule (Recommended)
- If a pre-configured module exists for your service, use the module.
- If no module exists, use a generic container with
ContainerBuilderand always define an explicit wait strategy.
Prerequisites
- Docker or Podman installed and running
- .NET 8.0+ (check project requirements; library supports .NET and .NET Standard)
- Docker socket accessible at standard locations (Docker Desktop on macOS/Windows,
/var/run/docker.sockon Linux) - Test framework: xUnit, NUnit, or MSTest
Instructions
Quick Start (Framework-Agnostic)
Use this when you want a minimal, reliable integration test setup without committing to xUnit/NUnit/MSTest patterns up front.
- Create (or choose) a test project using your preferred test framework.
- Add the Testcontainers module for your service (prefer modules over generic containers).
- Add the client library for the service you will connect to.
- Write a single test that:
- starts the container
- connects to the service and performs a small smoke operation
- disposes the container (for example, via
await using)
- Run the test project.
# Example: PostgreSQL (module + client library)
dotnet add package Testcontainers.PostgreSql
dotnet add package Npgsql
# Run your tests (command varies by runner, but this works for most)
dotnet test
// NuGet dependencies:
// - dotnet add package Npgsql
// - dotnet add package Testcontainers.PostgreSql
// - dotnet add package xunit.v3
using System;
using System.Threading;
using System.Threading.Tasks;
using Npgsql;
using Testcontainers.PostgreSql;
public sealed class PostgresSmokeTest
{
// Note: Add your framework's test attribute (e.g., [Fact]/[Test]/[TestMethod]).
public async Task CanQueryPostgres()
{
await using var postgres = new PostgreSqlBuilder("postgres:16-alpine").Build();
await postgres.StartAsync(CancellationToken.None);
await using var connection = new NpgsqlConnection(postgres.GetConnectionString());
await connection.OpenAsync(CancellationToken.None);
await using var command = new NpgsqlCommand("SELECT 1", connection);
var result = await command.ExecuteScalarAsync(CancellationToken.None);
if (!Equals(result, 1))
{
throw new InvalidOperationException($"Expected SELECT 1 to return 1. Actual: {result}");
}
}
}
What I Need From You (Checklist)
When you ask for help, include these details so the generated test code matches your environment:
- Test framework: xUnit / NUnit / MSTest (and version if relevant)
- .NET version: e.g., net8.0
- Container runtime: Docker Desktop / Docker Engine / Podman (and OS)
- Service under test: PostgreSQL / Redis / SQL Server / Kafka / ...
- Image + tag: e.g.,
postgres:16-alpine(pin versions for CI stability) - How the test should connect: host port mapping vs container-to-container network
- Readiness signal: HTTP endpoint, log line, command (if you know it)
- Data setup: schema/init scripts, seed data, migrations (and where they live)
- Lifecycle: per-test container vs shared fixture (performance vs isolation)
- Parallelism/CI: Will tests run in parallel? Any CI constraints/timeouts?
If you do not know an item, say so (the default recommendation is: module + explicit wait strategy + random host ports + dispose in teardown).
1. Installation & Setup
Add Testcontainers for .NET to your test project:
# Core library (required)
# For modules, the core library will be resolved through transitive dependencies.
dotnet add package Testcontainers
# For pre-configured modules (recommended)
# PostgreSQL
dotnet add package Testcontainers.PostgreSql
# SQL Server
dotnet add package Testcontainers.MsSql
# MySQL
dotnet add package Testcontainers.MySql
# MongoDB
dotnet add package Testcontainers.MongoDB
# Redis
dotnet add package Testcontainers.Redis
# Kafka
dotnet add package Testcontainers.Kafka
# RabbitMQ
dotnet add package Testcontainers.RabbitMq
# Elasticsearch
dotnet add package Testcontainers.Elasticsearch
# And many more...
Verify Docker availability:
Note: Testcontainers usually fails (throws) when creating/starting containers or other resources if no container runtime is reachable. The snippet below is a lightweight sanity check that helps you see what configuration Testcontainers resolves on the current machine.
using DotNet.Testcontainers.Configurations;
using Xunit;
[Fact]
public void DockerIsAvailable()
{
var testcontainersConfiguration = TestcontainersSettings.OS;
Assert.NotNull(testcontainersConfiguration);
}
2. Using Pre-Configured Modules (Recommended Approach)
Testcontainers for .NET provides 65+ pre-configured modules that offer production-ready configurations, sensible defaults, and helper methods. Always prefer modules over generic containers when available.
Why Use Modules?
- Sensible defaults: Pre-configured ports, environment variables, and wait strategies
- Connection helpers: Built-in properties like
GetConnectionString(),GetBootstrapAddress() - Specialized features: Module-specific functionality (e.g., running scripts inside the container)
- Automatic credentials: Secure credential generation and management
- Battle-tested: Used in production by thousands of projects
Available Module Categories
Databases (15+ modules):
Testcontainers.CassandraTestcontainers.ClickHouseTestcontainers.CosmosDbTestcontainers.CouchDbTestcontainers.Db2Testcontainers.DynamoDbTestcontainers.InfluxDbTestcontainers.MariaDbTestcontainers.MongoDBTestcontainers.MsSqlTestcontainers.MySqlTestcontainers.OracleTestcontainers.PostgreSqlTestcontainers.Redis
Message Queues (5+ modules):
Testcontainers.KafkaTestcontainers.NATSTestcontainers.PulsarTestcontainers.RabbitMqTestcontainers.Redpanda
Search & Storage (5+ modules):
Testcontainers.AzuriteTestcontainers.ElasticsearchTestcontainers.LocalStackTestcontainers.MinioTestcontainers.Qdrant
Cloud & Infrastructure (5+ modules):
Testcontainers.Azurite(Azure Storage)Testcontainers.GCloud(Google Cloud)Testcontainers.LocalStack(AWS services)Testcontainers.ConsulTestcontainers.Vault
Development Tools (10+ modules):
Testcontainers.WebDriver(Selenium)Testcontainers.GrafanaTestcontainers.KeycloakTestcontainers.MockServerTestcontainers.Neo4j
Basic Module Usage Pattern
// NuGet dependencies:
// - dotnet add package Npgsql
// - dotnet add package Testcontainers.PostgreSql
// - dotnet add package xunit.v3
using Npgsql;
using Testcontainers.PostgreSql;
using Xunit;
public sealed class DatabaseTests : IAsyncLifetime
{
private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder("postgres:16-alpine").Build();
public async ValueTask InitializeAsync()
{
await _postgres.StartAsync();
}
public async ValueTask DisposeAsync()
{
await _postgres.DisposeAsync();
}
[Fact]
public async Task ConnectionTest()
{
// Includes mapped port and generated credentials.
var connectionString = _postgres.GetConnectionString();
await using var connection = new NpgsqlConnection(connectionString);
await connection.OpenAsync(TestContext.Current.CancellationToken);
await using var command = new NpgsqlCommand("SELECT 1", connection);
var result = await command.ExecuteScalarAsync(TestContext.Current.CancellationToken);
Assert.Equal(1, result);
}
}
Module Configuration with Builder Pattern
Modules use a fluent builder API for configuration:
Level 1: Basic Configuration
var postgres = new PostgreSqlBuilder("postgres:16-alpine")
.WithDatabase("myapp_test")
.WithUsername("custom_user")
.WithPassword("custom_pass")
.Build();
Level 2: Advanced Configuration
// PostgreSQL with init scripts
var postgres = new PostgreSqlBuilder("postgres:16-alpine")
.WithDatabase("myapp_test")
.WithResourceMapping("./init.sql", "/docker-entrypoint-initdb.d/init.sql")
.Build();
// Redis with custom configuration
var redis = new RedisBuilder("redis:7-alpine")
.WithCommand("redis-server", "--maxmemory", "256mb")
.Build();
// Kafka with custom configuration
var kafka = new KafkaBuilder("confluentinc/cp-kafka:7.5.12")
.WithKRaft()
.Build();
Level 3: Network and Environment Configuration
var postgres = new PostgreSqlBuilder("postgres:16-alpine")
.WithEnvironment("POSTGRES_INITDB_ARGS", "-E UTF8")
.WithLabel("environment", "test")
.WithTmpfsMount("/tmp")
.WithBindMount("/host/path", "/container/path") // Optional: mount directory or file (not recommended)
.WithPortBinding(5432, 5432) // Optional: fixed port (not recommended)
.Build();
Module-Specific Helper Methods
Most modules provide convenience methods:
// PostgreSQL
await using var postgres = new PostgreSqlBuilder("postgres:16-alpine").Build();
await postgres.StartAsync();
var postgresConnectionString = postgres.GetConnectionString();
// SQL Server
await using var mssql = new MsSqlBuilder("mcr.microsoft.com/mssql/server:2022-CU14-ubuntu-22.04").Build();
await mssql.StartAsync();
var mssqlConnectionString = mssql.GetConnectionString();
// MongoDB
await using var mongo = new MongoDbBuilder("mongo:6.0").Build();
await mongo.StartAsync();
var mongoConnectionString = mongo.GetConnectionString();
// Redis
await using var redis = new RedisBuilder("redis:7-alpine").Build();
await redis.StartAsync();
var redisConnectionString = redis.GetConnectionString();
// Kafka
await using var kafka = new KafkaBuilder("confluentinc/cp-kafka:7.5.12").Build();
await kafka.StartAsync();
var kafkaBootstrapAddress = kafka.GetBootstrapAddress();
// Elasticsearch
await using var elasticsearch = new ElasticsearchBuilder("elasticsearch:8.7.0").Build();
await elasticsearch.StartAsync();
var elasticsearchConnectionString = elasticsearch.GetConnectionString();
Finding the Right Module
- Browse available modules: https://testcontainers.com/modules/?language=dotnet (complete, up-to-date list)
- Browse NuGet packages: Search for "Testcontainers" on NuGet.org
- Official documentation: https://dotnet.testcontainers.org/
- GitHub repository: https://github.com/testcontainers/testcontainers-dotnet
- Module examples: Each module has examples/tests in the repository
Module naming pattern:
Testcontainers.<ServiceName>
3. Using Generic Containers (Fallback)
When no pre-configured module exists, use generic containers with ContainerBuilder.
Important: Always add a wait strategy to ensure the container is ready before tests run. This is critical for reliability, especially in CI environments.
// NuGet dependencies:
// - dotnet add package Testcontainers
// - dotnet add package xunit.v3
using DotNet.Testcontainers.Builders;
using DotNet.Testcontainers.Containers;
using Xunit;
public sealed class CustomContainerTests : IAsyncLifetime
{
private readonly IContainer _container = new ContainerBuilder("custom-image:latest")
.WithPortBinding(8080, true) // Random host port (recommended)
.WithEnvironment("APP_ENV", "test")
.WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(r => r.ForPort(8080).ForPath("/")))
.Build();
public async ValueTask InitializeAsync()
{
await _container.StartAsync();
}
public async ValueTask DisposeAsync()
{
await _container.DisposeAsync();
}
[Fact]
public void GetEndpoint()
{
// Use mapped host port + resolved hostname.
var port = _container.GetMappedPublicPort(8080);
var hostname = _container.Hostname;
// Prefer Hostname over hard-coding localhost (works across runtimes/CI).
var endpoint = $"http://{hostname}:{port}";
Assert.True(port > 0, $"Port value must be greater than 0. Actual value: '{port}'.");
}
}
Common generic container options:
var container = new ContainerBuilder("image:tag")
// Ports
.WithPortBinding(80, true) // Random host port
.WithPortBinding(443, 8443) // Fixed port (not recommended)
.WithExposedPort(80) // Expose without binding
// Environment
.WithEnvironment("KEY", "value")
.WithEnvironment(new Dictionary<string, string>
{
["DATABASE_URL"] = "postgres://localhost/db",
["LOG_LEVEL"] = "debug"
})
// Files and Mounts
.WithResourceMapping("./config.yml", "/app/config.yml")
// Bind mounts are not recommended; prefer WithResourceMapping.
.WithBindMount("/host/path", "/container/path")
.WithBindMount("/host/path", "/container/path", AccessMode.ReadOnly)
.WithTmpfsMount("/tmp")
// Wait strategies (REQUIRED for reliability)
.WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(r => r.ForPort(80).ForPath("/")))
// Or: .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(r => r.ForPort(80)))
// Or: .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("ready"))
// Commands
.WithCommand("arg1", "arg2")
.WithEntrypoint("/bin/sh", "-c")
// Labels
.WithLabel("app", "myapp")
.WithLabel("environment", "test")
// Cleanup
.WithCleanUp(true) // Auto-cleanup (default: true)
.Build();
4. Writing Integration Tests
Test Framework Integration
Note: The xUnit.net examples in this document use xUnit.net v3 (for example TestContext.Current.CancellationToken). The overall patterns are framework-agnostic: the same container setup/teardown concepts apply to NUnit and MSTest, and you can adapt cancellation-token usage to your test framework/version.
xUnit (Recommended Pattern with IAsyncLifetime)
// NuGet dependencies:
// - dotnet add package Npgsql
// - dotnet add package Testcontainers.PostgreSql
// - dotnet add package xunit.v3
using Npgsql;
using Testcontainers.PostgreSql;
using Xunit;
public sealed class DatabaseTests : IAsyncLifetime
{
private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder("postgres:16-alpine").Build();
public async ValueTask InitializeAsync()
{
await _postgres.StartAsync();
}
public async ValueTask DisposeAsync()
{
await _postgres.DisposeAsync();
}
[Fact]
public async Task CanConnectToDatabase()
{
var connectionString = _postgres.GetConnectionString();
await using var connection = new NpgsqlConnection(connectionString);
await connection.OpenAsync(TestContext.Current.CancellationToken);
Assert.NotNull(connection);
}
}
xUnit with Class Fixture (Shared Container)
// NuGet dependencies:
// - dotnet add package Testcontainers.PostgreSql
// - dotnet add package xunit.v3
using Testcontainers.PostgreSql;
using Xunit;
// Fixture: Container shared across multiple tests in the class
public sealed class DatabaseFixture : IAsyncLifetime
{
public PostgreSqlContainer Postgres { get; } = new PostgreSqlBuilder("postgres:16-alpine").Build();
public async ValueTask InitializeAsync()
{
await Postgres.StartAsync();
}
public async ValueTask DisposeAsync()
{
await Postgres.DisposeAsync();
}
}
// Test class using the fixture
public sealed class DatabaseTests : IClassFixture<DatabaseFixture>
{
private readonly DatabaseFixture _fixture;
public DatabaseTests(DatabaseFixture fixture)
{
_fixture = fixture;
}
[Fact]
public void CanGetConnectionString()
{
var connectionString = _fixture.Postgres.GetConnectionString();
Assert.NotEmpty(connectionString);
}
}
NUnit
// NuGet dependencies:
// - dotnet add package Npgsql
// - dotnet add package NUnit
// - dotnet add package Testcontainers.PostgreSql
using Npgsql;
using Testcontainers.PostgreSql;
using NUnit.Framework;
[TestFixture]
public sealed class DatabaseTests
{
private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder("postgres:16-alpine").Build();
[OneTimeSetUp]
public async Task OneTimeSetUp()
{
await _postgres.StartAsync();
}
[OneTimeTearDown]
public async Task OneTimeTearDown()
{
await _postgres.DisposeAsync();
}
[Test]
public async Task CanConnectToDatabase()
{
var connectionString = _postgres.GetConnectionString();
await using var connection = new NpgsqlConnection(connectionString);
await connection.OpenAsync();
Assert.That(connection, Is.Not.Null);
}
}
MSTest
// NuGet dependencies:
// - dotnet add package MSTest.TestFramework
// - dotnet add package Npgsql
// - dotnet add package Testcontainers.PostgreSql
using Npgsql;
using Testcontainers.PostgreSql;
[TestClass]
public sealed class DatabaseTests
{
private static readonly PostgreSqlContainer Postgres = new PostgreSqlBuilder("postgres:16-alpine").Build();
[ClassInitialize]
public static async Task ClassInitialize(TestContext context)
{
await Postgres.StartAsync();
}
[ClassCleanup]
public static async Task ClassCleanup()
{
await Postgres.DisposeAsync();
}
[TestMethod]
public async Task CanConnectToDatabase()
{
var connectionString = Postgres.GetConnectionString();
await using var connection = new NpgsqlConnection(connectionString);
await connection.OpenAsync();
Assert.IsNotNull(connection);
}
}
Theory/Parameterized Tests
xUnit Theory:
// NuGet dependencies:
// - dotnet add package Npgsql
// - dotnet add package Testcontainers.PostgreSql
// - dotnet add package xunit.v3
using Npgsql;
using Testcontainers.PostgreSql;
using Xunit;
public sealed class VersionTests
{
[Theory]
[InlineData("postgres:14-alpine")]
[InlineData("postgres:15-alpine")]
[InlineData("postgres:16-alpine")]
public async Task TestMultipleVersions(string image)
{
await using var postgres = new PostgreSqlBuilder(image).Build();
await postgres.StartAsync(TestContext.Current.CancellationToken);
var connectionString = postgres.GetConnectionString();
await using var connection = new NpgsqlConnection(connectionString);
await connection.OpenAsync(TestContext.Current.CancellationToken);
Assert.NotNull(connection);
}
}
5. Container Networking
Connecting Multiple Containers
// NuGet dependencies:
// - dotnet add package Testcontainers.PostgreSql
// - dotnet add package xunit.v3
using DotNet.Testcontainers.Builders;
using DotNet.Testcontainers.Containers;
using DotNet.Testcontainers.Networks;
using Testcontainers.PostgreSql;
using Xunit;
public sealed class MultiContainerTests : IAsyncLifetime
{
private INetwork _network;
private PostgreSqlContainer _postgres;
private IContainer _app;
public async ValueTask InitializeAsync()
{
// Create custom network
_network = new NetworkBuilder()
.Build();
// Start database on network
_postgres = new PostgreSqlBuilder("postgres:16-alpine")
.WithNetwork(_network)
.WithNetworkAliases("database")
.Build();
// Start app on network
_app = new ContainerBuilder("custom-image:latest")
.WithNetwork(_network)
.WithNetworkAliases("app")
.WithEnvironment("DB_HOST", "database") // Use network alias to connect to the DB
.WithEnvironment("DB_PORT", "5432") // Use internal DB port
.WithPortBinding(8080, true)
.WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(r => r.ForPort(8080).ForPath("/")))
.Build();
await _network.CreateAsync();
await _postgres.StartAsync();
await _app.StartAsync();
}
public async ValueTask DisposeAsync()
{
await _app.DisposeAsync();
await _postgres.DisposeAsync();
await _network.DeleteAsync();
}
[Fact]
public void AppCanCommunicateWithDatabase()
{
var endpoint = $"http://{_app.Hostname}:{_app.GetMappedPublicPort(8080)}";
Assert.NotEmpty(endpoint);
}
}
Accessing Container Services
[Fact]
public void GetServiceInformation()
{
// Method 1: Get mapped public port
var publicPort = _container.GetMappedPublicPort(80);
// publicPort = 49153 (random port assigned by Docker)
// Method 2: Get hostname
var hostname = _container.Hostname;
// hostname = "localhost" (or Docker host)
// Method 3: Build full endpoint
var endpoint = $"http://{_container.Hostname}:{_container.GetMappedPublicPort(80)}";
// endpoint = "http://localhost:49153"
}
6. Resource Management & Cleanup
Cleanup Patterns
Goal: Start containers only for the time you need them, and ensure cleanup runs reliably even when tests fail.
Pattern 1: IAsyncLifetime (xUnit - Recommended)
public sealed class DatabaseTests : IAsyncLifetime
{
private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder("postgres:16-alpine").Build();
public async ValueTask InitializeAsync()
{
await _postgres.StartAsync();
}
public async ValueTask DisposeAsync()
{
// Ryuk cleans up automatically, but disposing early is still best practice.
await _postgres.DisposeAsync();
}
}
Pattern 2: IAsyncDisposable
[Fact]
public async Task TestWithDisposable()
{
await using var postgres = new PostgreSqlBuilder("postgres:16-alpine").Build();
await postgres.StartAsync();
// Use container...
// Automatically disposed at end of scope
}
Pattern 3: Explicit Cleanup
[Fact]
public async Task TestWithExplicitCleanup()
{
var postgres = new PostgreSqlBuilder("postgres:16-alpine").Build();
try
{
await postgres.StartAsync();
// Use container...
}
finally
{
await postgres.DisposeAsync();
}
}
Automatic Cleanup with Ryuk
Testcontainers for .NET uses Ryuk, a garbage collector that automatically cleans up containers even if tests crash or timeout:
- Runs as a sidecar container (e.g.,
testcontainers/ryuk:0.14.0) - Monitors test session lifecycle
- Cleans up containers when session ends
- Handles parallel test execution
Control Ryuk behavior:
// Disable Ryuk (not recommended)
Environment.SetEnvironmentVariable("TESTCONTAINERS_RYUK_DISABLED", "true");
// Custom Ryuk image
Environment.SetEnvironmentVariable("TESTCONTAINERS_RYUK_CONTAINER_IMAGE", "testcontainers/ryuk:0.14.0");
Cleanup options:
var container = new ContainerBuilder("nginx:alpine")
.WithCleanUp(true) // Enable auto-cleanup (default: true)
.Build();
7. Configuration Patterns
Environment Variables
var container = new ContainerBuilder("custom-image:latest")
.WithEnvironment("DATABASE_URL", "postgres://localhost/db")
.WithEnvironment("LOG_LEVEL", "debug")
.Build();
// Same idea, using a dictionary
var containerWithDictionary = new ContainerBuilder("custom-image:latest")
.WithEnvironment(new Dictionary<string, string>
{
["DATABASE_URL"] = "postgres://localhost/db",
["LOG_LEVEL"] = "debug"
})
.Build();
Executing Commands in Containers
[Fact]
public async Task ExecuteCommandInContainer()
{
await using var container = new ContainerBuilder("alpine:3.23")
.WithCommand("tail", "-f", "/dev/null") // Keep container running
.Build();
await container.StartAsync();
var execResult = await container.ExecAsync(new[] { "echo", "Hello, World!" });
Assert.Equal(0, execResult.ExitCode);
Assert.Contains("Hello, World!", execResult.Stdout);
}
Reading Logs
[Fact]
public async Task ReadContainerLogs()
{
await using var container = new ContainerBuilder("nginx:alpine")
.WithPortBinding(80, true)
.WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(r => r.ForPort(80).ForPath("/")))
.Build();
await container.StartAsync();
var (stdout, stderr) = await container.GetLogsAsync();
Assert.NotEmpty(stdout);
}
Files and Directories
// Copy a local file into the container
var nginx = new ContainerBuilder("nginx:alpine")
.WithResourceMapping("./nginx.conf", "/etc/nginx/nginx.conf")
.Build();
// Copy multiple files
var appWithFiles = new ContainerBuilder("custom-image:latest")
.WithResourceMapping("./config.yml", "/app/config.yml")
.WithResourceMapping("./secrets.json", "/app/secrets.json")
.Build();
// Bind mount (not recommended for hermetic tests)
var postgresWithBindMount = new ContainerBuilder("postgres:16")
.WithBindMount("/host/data", "/var/lib/postgresql/data")
.Build();
// Read-only bind mount
var appWithReadOnlyMount = new ContainerBuilder("custom-image:latest")
.WithBindMount("/host/config", "/app/config", AccessMode.ReadOnly)
.Build();
// Read a file from a running container
await nginx.StartAsync();
var nginxConf = await nginx.ReadFileAsync("/etc/nginx/nginx.conf");
Volume Mounts
public sealed class VolumeTests : IAsyncLifetime
{
private IVolume _volume;
private IContainer _container;
public async ValueTask InitializeAsync()
{
// Create volume
_volume = new VolumeBuilder()
.Build();
// Use volume in container
_container = new ContainerBuilder("postgres:16-alpine")
.WithVolumeMount(_volume, "/var/lib/postgresql/data")
.Build();
await _volume.CreateAsync();
await _container.StartAsync();
}
public async ValueTask DisposeAsync()
{
await _container.DisposeAsync();
await _volume.DeleteAsync();
}
}
Temporary Filesystems
var container = new ContainerBuilder("custom-image:latest")
.WithTmpfsMount("/tmp")
.WithTmpfsMount("/app/temp")
.Build();
8. Wait Strategies
Wait strategies are critical for reliable tests. They ensure containers are fully ready before tests run, which is especially important in CI environments where timing can vary.
Best Practices:
- ✅ Always use wait strategies for services - Ensures reliability
- ✅ Choose appropriate wait strategies based on your service
- ❌ Never use
Task.Delay()orThread.Sleep()as a readiness mechanism - This is an anti-pattern that leads to flaky tests - ✅ Set reasonable timeouts to handle slow CI environments
Common pitfall: A Task.Delay(...) can be fine inside a test (for example, waiting for an expiration to happen). The anti-pattern is using fixed sleeps/delays to decide when a containerized service is ready. For readiness, always prefer explicit wait strategies.
HTTP-Based Waiting (Recommended for Web Services)
using System.Net;
var container = new ContainerBuilder("nginx:alpine")
.WithPortBinding(80, true)
.WithWaitStrategy(Wait.ForUnixContainer()
.UntilHttpRequestIsSucceeded(r => r.ForPort(80).ForPath("/")))
.Build();
// Wait for a specific path and expected status code
var healthCheckContainer = new ContainerBuilder("custom-image:latest")
.WithPortBinding(8080, true)
.WithWaitStrategy(Wait.ForUnixContainer()
.UntilHttpRequestIsSucceeded(request => request
.ForPort(8080)
.ForPath("/health")
.ForStatusCode(HttpStatusCode.OK)))
.Build();
Log-Based Waiting
var container = new ContainerBuilder("elasticsearch:8.7.0")
.WithWaitStrategy(Wait.ForUnixContainer()
.UntilMessageIsLogged("started"))
.Build();
// Wait for specific log message with timeout
var containerWithTimeout = new ContainerBuilder("elasticsearch:8.7.0")
.WithWaitStrategy(Wait.ForUnixContainer()
.UntilMessageIsLogged("started", o => o.WithTimeout(TimeSpan.FromMinutes(5))))
.Build();
Command-Based Waiting
var container = new ContainerBuilder("postgres:16-alpine")
.WithWaitStrategy(Wait.ForUnixContainer()
.UntilCommandIsCompleted("pg_isready"))
.Build();
Multiple Wait Strategies
var container = new ContainerBuilder("custom-image:latest")
.WithPortBinding(8080, true)
.WithWaitStrategy(Wait.ForUnixContainer()
.UntilHttpRequestIsSucceeded(r => r.ForPort(8080).ForPath("/"))
.UntilMessageIsLogged("Application started")
.UntilHttpRequestIsSucceeded(r => r.ForPort(8080).ForPath("/health")))
.Build();
Custom Wait Strategies
var container = new ContainerBuilder("custom-image:latest")
.WithWaitStrategy(Wait.ForUnixContainer()
.AddCustomWaitStrategy(new MyCustomWaitStrategy()))
.Build();
public sealed class MyCustomWaitStrategy : IWaitUntil
{
public async Task<bool> UntilAsync(IContainer container)
{
// Custom wait logic
return true;
}
}
9. Troubleshooting
Verify Docker Availability
[Fact]
public void CheckDockerConnection()
{
var dockerEndpoint = TestcontainersSettings.OS.DockerEndpointAuthConfig;
Assert.NotNull(dockerEndpoint);
}
Debug Container Logs
Note: In xUnit, _output typically comes from ITestOutputHelper injected into the test class constructor. If you are using NUnit/MSTest (or you prefer a quick local repro), you can replace _output.WriteLine(...) with your framework's logging mechanism or Console.WriteLine(...).
[Fact]
public async Task DebugWithLogging()
{
await using var container = new ContainerBuilder("custom-image:latest")
.WithPortBinding(8080, true)
.WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(r => r.ForPort(8080).ForPath("/")))
.Build();
await container.StartAsync();
var (stdout, stderr) = await container.GetLogsAsync();
_output.WriteLine($"STDOUT:\n{stdout}");
_output.WriteLine($"STDERR:\n{stderr}");
_output.WriteLine($"Container ID: {container.Id}");
}
Common Issues
Issue: Container startup timeout
var container = new ContainerBuilder("slow-starting-app:latest")
.WithWaitStrategy(Wait.ForUnixContainer()
.UntilHttpRequestIsSucceeded(r => r.ForPort(8080).ForPath("/"), o => o.WithTimeout(TimeSpan.FromMinutes(5))))
.Build();
Issue: Port already in use
- Testcontainers auto-assigns random ports when using
.WithPortBinding(port, true) - Avoid fixed port bindings unless necessary
- Check for leaked containers:
docker ps -a
Issue: Image pull failures
# Pull manually first to verify
docker pull postgres:16-alpine
# For private registries, login first
docker login registry.example.com
# Testcontainers will use credentials from Docker config
Issue: Container not cleaning up
// Verify cleanup is enabled
var container = new ContainerBuilder("nginx:alpine3.23")
.WithCleanUp(true) // Ensure auto-cleanup is enabled (default: true)
.Build();
// Check Ryuk is running
// docker ps | grep ryuk
// Windows PowerShell: docker ps | Select-String ryuk
// Windows CMD: docker ps | findstr ryuk
Environment Variables for Configuration
// Custom Docker host
Environment.SetEnvironmentVariable("DOCKER_HOST", "tcp://localhost:2375");
// Disable Ryuk (not recommended)
Environment.SetEnvironmentVariable("TESTCONTAINERS_RYUK_DISABLED", "true");
// Custom Ryuk image
Environment.SetEnvironmentVariable("TESTCONTAINERS_RYUK_CONTAINER_IMAGE", "testcontainers/ryuk:0.14.0");
// Hub image name prefix (for private registries)
Environment.SetEnvironmentVariable("TESTCONTAINERS_HUB_IMAGE_NAME_PREFIX", "my.registry.com/");
Examples
Example 1: PostgreSQL Integration Test
// NuGet dependencies:
// - dotnet add package Npgsql
// - dotnet add package Testcontainers.PostgreSql
// - dotnet add package xunit.v3
using Npgsql;
using Testcontainers.PostgreSql;
using Xunit;
public sealed class UserRepositoryTests : IAsyncLifetime
{
private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder("postgres:16-alpine")
.WithDatabase("testdb")
.WithUsername("testuser")
.WithPassword("testpass")
.Build();
public async ValueTask InitializeAsync()
{
await _postgres.StartAsync();
// Initialize schema
await using var connection = new NpgsqlConnection(_postgres.GetConnectionString());
await connection.OpenAsync();
await using var command = new NpgsqlCommand(@"
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)", connection);
await command.ExecuteNonQueryAsync();
}
public async ValueTask DisposeAsync()
{
await _postgres.DisposeAsync();
}
[Fact]
public async Task CreateUser_ShouldInsertUser()
{
await using var connection = new NpgsqlConnection(_postgres.GetConnectionString());
await connection.OpenAsync(TestContext.Current.CancellationToken);
await using var command = new NpgsqlCommand(
"INSERT INTO users (name, email) VALUES (@name, @email) RETURNING id",
connection);
command.Parameters.AddWithValue("name", "Alice");
command.Parameters.AddWithValue("email", "alice@example.com");
var userId = await command.ExecuteScalarAsync(TestContext.Current.CancellationToken);
Assert.NotNull(userId);
}
[Fact]
public async Task GetUser_ShouldReturnUser()
{
await using var connection = new NpgsqlConnection(_postgres.GetConnectionString());
await connection.OpenAsync(TestContext.Current.CancellationToken);
await using var insertCmd = new NpgsqlCommand(
"INSERT INTO users (name, email) VALUES (@name, @email)",
connection);
insertCmd.Parameters.AddWithValue("name", "Bob");
insertCmd.Parameters.AddWithValue("email", "bob@example.com");
await insertCmd.ExecuteNonQueryAsync(TestContext.Current.CancellationToken);
await using var selectCmd = new NpgsqlCommand(
"SELECT name, email FROM users WHERE email = @email",
connection);
selectCmd.Parameters.AddWithValue("email", "bob@example.com");
await using var reader = await selectCmd.ExecuteReaderAsync(TestContext.Current.CancellationToken);
await reader.ReadAsync(TestContext.Current.CancellationToken);
var name = reader.GetString(0);
var email = reader.GetString(1);
Assert.Equal("Bob", name);
Assert.Equal("bob@example.com", email);
}
}
Example 2: Redis Cache Test
// NuGet dependencies:
// - dotnet add package StackExchange.Redis
// - dotnet add package Testcontainers.Redis
// - dotnet add package xunit.v3
using StackExchange.Redis;
using Testcontainers.Redis;
using Xunit;
public sealed class RedisCacheTests : IAsyncLifetime
{
private readonly RedisContainer _redis = new RedisBuilder("redis:7-alpine").Build();
private IConnectionMultiplexer _connection;
private IDatabase _db;
public async ValueTask InitializeAsync()
{
await _redis.StartAsync();
_connection = await ConnectionMultiplexer.ConnectAsync(_redis.GetConnectionString());
_db = _connection.GetDatabase();
}
public async ValueTask DisposeAsync()
{
_connection.Dispose();
await _redis.DisposeAsync();
}
[Fact]
public async Task SetAndGet_ShouldStoreAndRetrieveValue()
{
await _db.StringSetAsync("key1", "value1");
var value = await _db.StringGetAsync("key1");
Assert.Equal("value1", value);
}
[Fact]
public async Task SetWithExpiration_ShouldExpireKey()
{
await _db.StringSetAsync("key2", "value2", TimeSpan.FromSeconds(1));
var valueBefore = await _db.StringGetAsync("key2");
await Task.Delay(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken);
var valueAfter = await _db.StringGetAsync("key2");
Assert.Equal("value2", valueBefore);
Assert.True(valueAfter.IsNull);
}
}
Example 3: SQL Server with Entity Framework Core (SqlServer)
// NuGet dependencies:
// - dotnet add package Microsoft.EntityFrameworkCore
// - dotnet add package Testcontainers.Mssql
// - dotnet add package xunit.v3
using Microsoft.EntityFrameworkCore;
using Testcontainers.MsSql;
using Xunit;
public sealed class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<User> Users { get; set; }
}
public sealed class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
public sealed class EntityFrameworkTests : IAsyncLifetime
{
private readonly MsSqlContainer _mssql = new MsSqlBuilder("mcr.microsoft.com/mssql/server:2022-CU14-ubuntu-22.04").Build();
private ApplicationDbContext _dbContext;
public async ValueTask InitializeAsync()
{
await _mssql.StartAsync();
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseSqlServer(_mssql.GetConnectionString())
.Options;
_dbContext = new ApplicationDbContext(options);
await _dbContext.Database.EnsureCreatedAsync();
}
public async ValueTask DisposeAsync()
{
await _dbContext.DisposeAsync();
await _mssql.DisposeAsync();
}
[Fact]
public async Task AddUser_ShouldPersistToDatabase()
{
var user = new User
{
Name = "Alice",
Email = "alice@example.com"
};
_dbContext.Users.Add(user);
await _dbContext.SaveChangesAsync(TestContext.Current.CancellationToken);
var savedUser = await _dbContext.Users.FirstOrDefaultAsync(u => u.Email == "alice@example.com", cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(savedUser);
Assert.Equal("Alice", savedUser.Name);
}
}
Example 4: Kafka Producer/Consumer Test
// NuGet dependencies:
// - dotnet add package Confluent.Kafka
// - dotnet add package Testcontainers.Kafka
// - dotnet add package xunit.v3
using Confluent.Kafka;
using Testcontainers.Kafka;
using Xunit;
public sealed class KafkaTests : IAsyncLifetime
{
private readonly KafkaContainer _kafka = new KafkaBuilder("confluentinc/confluent-local:7.5.0").Build();
public async ValueTask InitializeAsync()
{
await _kafka.StartAsync();
}
public async ValueTask DisposeAsync()
{
await _kafka.DisposeAsync();
}
[Fact]
public async Task ProduceAndConsume_ShouldTransferMessage()
{
const string topic = "test-topic";
var bootstrapServers = _kafka.GetBootstrapAddress();
var producerConfig = new ProducerConfig
{
BootstrapServers = bootstrapServers
};
using var producer = new ProducerBuilder<string, string>(producerConfig).Build();
var consumerConfig = new ConsumerConfig
{
BootstrapServers = bootstrapServers,
GroupId = "test-group",
AutoOffsetReset = AutoOffsetReset.Earliest
};
using var consumer = new ConsumerBuilder<string, string>(consumerConfig).Build();
consumer.Subscribe(topic);
await producer.ProduceAsync(topic, new Message<string, string>
{
Key = "key1",
Value = "Hello, Kafka!"
}, TestContext.Current.CancellationToken);
var consumeResult = consumer.Consume(TimeSpan.FromSeconds(10));
Assert.NotNull(consumeResult);
Assert.Equal("Hello, Kafka!", consumeResult.Message.Value);
}
}
Example 5: ASP.NET Core WebApplicationFactory Integration
// NuGet dependencies:
// - dotnet add package Microsoft.AspNetCore.Mvc.Testing
// - dotnet add package Testcontainers.PostgreSql
// - dotnet add package xunit.v3
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Testcontainers.PostgreSql;
using Xunit;
public sealed class ApiTests : IAsyncLifetime
{
private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder("postgres:16-alpine").Build();
public async ValueTask InitializeAsync()
{
await _postgres.StartAsync();
}
public async ValueTask DisposeAsync()
{
await _postgres.DisposeAsync();
}
public sealed class WebAppTests : WebApplicationFactory<Program>, IClassFixture<ApiTests>
{
private readonly string _connectionString;
public WebAppTests(ApiTests fixture)
{
_connectionString = fixture._postgres.GetConnectionString();
}
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
// Uses the .NET configuration system's connection-string support (ConnectionStrings:<Name>).
builder.UseSetting("ConnectionStrings:Database", _connectionString);
}
[Fact]
public async Task HealthCheck_ReturnsOk()
{
using var client = CreateClient();
var response = await client.GetAsync("/health");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
Example 6: Multi-Container Application Stack
// NuGet dependencies:
// - dotnet add package Testcontainers.PostgreSql
// - dotnet add package Testcontainers.Redis
// - dotnet add package xunit.v3
using System.Net;
using DotNet.Testcontainers.Builders;
using DotNet.Testcontainers.Containers;
using DotNet.Testcontainers.Networks;
using Testcontainers.PostgreSql;
using Testcontainers.Redis;
using Xunit;
public sealed class FullStackTests : IAsyncLifetime
{
private INetwork _network;
private PostgreSqlContainer _postgres;
private RedisContainer _redis;
private IContainer _app;
public async ValueTask InitializeAsync()
{
// Create network
_network = new NetworkBuilder().Build();
// Start PostgreSQL
_postgres = new PostgreSqlBuilder("postgres:16-alpine")
.WithNetwork(_network)
.WithNetworkAliases("database")
.Build();
// Start Redis
_redis = new RedisBuilder("redis:7-alpine")
.WithNetwork(_network)
.WithNetworkAliases("cache")
.Build();
_app = new ContainerBuilder("custom-image:latest")
.WithNetwork(_network)
.WithNetworkAliases("app")
.WithEnvironment("DB_HOST", "database")
.WithEnvironment("DB_PORT", "5432")
.WithEnvironment("REDIS_HOST", "cache")
.WithEnvironment("REDIS_PORT", "6379")
.WithPortBinding(8080, true)
.WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(r => r.ForPort(8080).ForPath("/")))
.Build();
await _network.CreateAsync();
await _postgres.StartAsync();
await _redis.StartAsync();
await _app.StartAsync();
}
public async ValueTask DisposeAsync()
{
await _app.DisposeAsync();
await _redis.DisposeAsync();
await _postgres.DisposeAsync();
await _network.DeleteAsync();
}
[Fact]
public async Task HealthCheck_ShouldReturnOk()
{
var endpoint = $"http://{_app.Hostname}:{_app.GetMappedPublicPort(8080)}";
using var httpClient = new HttpClient();
var response = await httpClient.GetAsync($"{endpoint}/health", TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
Best Practices
- Always use pre-configured modules when available - They provide sensible defaults and helper methods.
- Use async lifecycle management - Proper async initialization and cleanup (
IAsyncLifetimein xUnit,[OneTimeSetUp]/[OneTimeTearDown]in NUnit,[ClassInitialize]/[ClassCleanup]in MSTest). - Always add wait strategies - Ensures containers are ready before tests run; never use
Task.Delay()/Thread.Sleep()as a readiness mechanism. - Use randomly assigned host ports - Do not rely on fixed ports.
- Copy configuration files into the container - Do not rely on mounting files or directories.
- Choose appropriate wait strategies - Use HTTP for health endpoints, logs for startup messages, or commands for readiness.
- Test against multiple configurations - Use parameterized tests to validate versions/configurations (
Theory/InlineDatain xUnit,TestCasein NUnit,DataRowin MSTest). - Use custom networks - For multi-container communication.
- Keep containers ephemeral - Do not rely on state between tests.
- Share containers when appropriate - Use fixtures or setup methods to share containers across tests for better performance.
- Use module helper methods - e.g.,
GetConnectionString(),GetBootstrapAddress(). - Debug with logs - Use
GetLogsAsync()when troubleshooting. - Use the builder pattern - Fluent API for clear, maintainable configuration.
Additional Resources
- Official Documentation: https://dotnet.testcontainers.org/
- NuGet Packages: https://www.nuget.org/packages?q=testcontainers
- GitHub Repository: https://github.com/testcontainers/testcontainers-dotnet
- Examples: https://github.com/testcontainers/testcontainers-dotnet/tree/develop/examples
- Community Slack: testcontainers.slack.com
Testcontainers for Go Integration Testing
You are an expert Go developer specializing in integration testing with Testcontainers. When this skill is active, you should:
- Always prefer pre-configured modules over generic containers when a module exists
- Follow the cleanup-before-error-check pattern in every test you write
- Use proper wait strategies instead of
time.Sleep()— never suggesttime.Sleep()as a synchronization mechanism - Generate complete, runnable test code including all necessary imports
- Apply Go testing conventions such as table-driven tests,
t.Parallel(), build tags, and subtests
Description
This skill helps you write integration tests using Testcontainers for Go, a Go library that provides lightweight, throwaway instances of common databases, message queues, web browsers, or anything that can run in a Docker container.
Key capabilities:
- Use 62+ pre-configured modules for common services (databases, message queues, cloud services, etc.)
- Set up and manage Docker containers in Go tests
- Configure networking, volumes, and environment variables
- Implement proper cleanup and resource management
- Debug and troubleshoot container issues
When to Use This Skill
Trigger keywords: integration test, testcontainers, docker test, container test, database test, test with postgres, test with redis, test with kafka, real database test, end-to-end test infrastructure, test environment setup, test cleanup, test isolation.
Use this skill when you need to:
- Write integration tests that require real services (databases, message queues, etc.)
- Test against multiple versions or configurations of dependencies
- Create reproducible test environments
- Avoid mocking external dependencies in integration tests
- Set up ephemeral test infrastructure
- Run integration tests in CI/CD pipelines (GitHub Actions, GitLab CI, etc.)
- Share container setup across multiple tests in a package
Prerequisites
- Docker or Podman installed and running
- Go 1.24+ (check
go.modfor project-specific requirements) - Docker socket accessible at standard locations (Docker Desktop on macOS/Windows,
/var/run/docker.sockon Linux)
Decision Guide
Use this decision tree to choose the right approach:
Need a container for testing?
├── Is there a pre-configured module? (check module list below)
│ ├── YES → Use the module (Section 2)
│ └── NO → Use a generic container (Section 3)
│
├── Need multiple containers to communicate?
│ └── YES → Create a custom network (Section 5)
│
├── Need shared setup across tests in a package?
│ └── YES → Use TestMain pattern (Section 10)
│
├── Need to separate integration tests from unit tests?
│ └── YES → Use build tags (Section 10)
│
└── Running in CI/CD?
└── YES → See CI/CD Integration (Section 11)
Instructions
1. Installation & Setup
Add testcontainers-go to your project:
go get github.com/testcontainers/testcontainers-go
For pre-configured modules (recommended):
# Example: PostgreSQL module
go get github.com/testcontainers/testcontainers-go/modules/postgres
# Example: Kafka module
go get github.com/testcontainers/testcontainers-go/modules/kafka
# Example: Redis module
go get github.com/testcontainers/testcontainers-go/modules/redis
Verify Docker availability:
func TestDockerAvailable(t *testing.T) {
testcontainers.SkipIfProviderIsNotHealthy(t)
// Test will skip if Docker is not running
}
2. Using Pre-Configured Modules (Recommended Approach)
Testcontainers for Go provides 62+ pre-configured modules that offer production-ready configurations, sensible defaults, and helper methods. Always prefer modules over generic containers when available.
Why Use Modules?
- Sensible defaults: Pre-configured ports, environment variables, and wait strategies
- Connection helpers: Built-in methods like
ConnectionString(),Endpoint() - Specialized features: Module-specific functionality (e.g., Postgres snapshots, Kafka topic management)
- Automatic credentials: Secure credential generation and management
- Battle-tested: Used in production by thousands of projects
Available Module Categories
Databases (17 modules):
postgres,mysql,mariadb,mongodb,redis,valkeycockroachdb,clickhouse,memcached,influxdbarangodb,cassandra,scylladb,dynamodbdolt,databend,surrealdb
Message Queues (6 modules):
kafka,rabbitmq,nats,pulsar,redpanda,solace
Search & Vector Databases (9 modules):
elasticsearch,opensearch,meilisearchweaviate,qdrant,chroma,milvus,vearch,pinecone
Cloud & Infrastructure (6 modules):
gcloud,azure,azurite,localstack,dind,k3s
Services & Tools (13 modules):
consul,etcd,neo4j,couchbase,vault,openldapartemis,inbucket,mockserver,nebulagraph,miniotoxiproxy,aerospike
Development (10 modules):
compose,registry,k6,ollama,grafana-lgtmdockermodelrunner,dockermcpgateway,socat,mssql
Basic Module Usage Pattern
package myapp_test
import (
"context"
"testing"
"github.com/stretchr/testify/require"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/postgres"
)
func TestWithPostgres(t *testing.T) {
ctx := context.Background()
// Start PostgreSQL container with sensible defaults
pgContainer, err := postgres.Run(ctx, "postgres:16-alpine")
testcontainers.CleanupContainer(t, pgContainer)
require.NoError(t, err)
// Get connection string - credentials auto-generated
connStr, err := pgContainer.ConnectionString(ctx)
require.NoError(t, err)
// connStr: "postgres://postgres:password@localhost:49153/postgres?sslmode=disable"
// Use connection string with your database driver
db, err := sql.Open("postgres", connStr)
require.NoError(t, err)
defer db.Close()
// Run your tests...
}
Module Configuration with Options
Modules support three levels of customization:
Level 1: Simple Options (via testcontainers.CustomizeRequestOption)
pgContainer, err := postgres.Run(
ctx,
"postgres:16-alpine",
testcontainers.WithEnv(map[string]string{
"POSTGRES_DB": "myapp_test",
}),
testcontainers.WithLabels(map[string]string{
"env": "test",
}),
)
Level 2: Module-Specific Options
// PostgreSQL with init scripts
pgContainer, err := postgres.Run(
ctx,
"postgres:16-alpine",
postgres.WithInitScripts("./testdata/init.sql"),
postgres.WithDatabase("myapp_test"),
postgres.WithUsername("custom_user"),
postgres.WithPassword("custom_pass"),
)
// Redis with configuration
redisContainer, err := redis.Run(
ctx,
"redis:7-alpine",
redis.WithSnapshotting(10, 1),
redis.WithLogLevel(redis.LogLevelVerbose),
)
// Kafka with custom config
kafkaContainer, err := kafka.Run(
ctx,
"confluentinc/confluent-local:7.5.0",
kafka.WithClusterID("test-cluster"),
)
Level 3: Advanced Configuration with Lifecycle Hooks
// PostgreSQL with custom initialization
pgContainer, err := postgres.Run(
ctx,
"postgres:16-alpine",
postgres.WithDatabase("myapp"),
testcontainers.WithLifecycleHooks(
testcontainers.ContainerLifecycleHooks{
PostStarts: []testcontainers.ContainerHook{
func(ctx context.Context, c testcontainers.Container) error {
// Custom initialization after container starts
return nil
},
},
},
),
)
Module-Specific Helper Methods
Most modules provide convenience methods beyond ConnectionString():
// PostgreSQL: Snapshot & Restore for test isolation
func TestDatabaseIsolation(t *testing.T) {
ctx := context.Background()
pgContainer, err := postgres.Run(ctx, "postgres:16-alpine")
testcontainers.CleanupContainer(t, pgContainer)
require.NoError(t, err)
connStr, _ := pgContainer.ConnectionString(ctx)
db, _ := sql.Open("postgres", connStr)
// Create initial data
db.Exec("CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT)")
db.Exec("INSERT INTO users (name) VALUES ('Alice')")
// Close connection before snapshot (PostgreSQL can't snapshot with active connections)
db.Close()
// Take snapshot
err = pgContainer.Snapshot(ctx, postgres.WithSnapshotName("initial"))
require.NoError(t, err)
// Reconnect and make changes
db, _ = sql.Open("postgres", connStr)
db.Exec("INSERT INTO users (name) VALUES ('Bob')")
// Close connection before restore
db.Close()
// Restore to snapshot
err = pgContainer.Restore(ctx, postgres.WithSnapshotName("initial"))
require.NoError(t, err)
// Reconnect — Bob is gone, only Alice remains
db, _ = sql.Open("postgres", connStr)
defer db.Close()
}
// Kafka: Get bootstrap servers
kafkaContainer, _ := kafka.Run(ctx, "confluentinc/confluent-local:7.5.0")
brokers, _ := kafkaContainer.Brokers(ctx)
Finding the Right Module
- Browse available modules: https://testcontainers.com/modules/?language=go (complete, up-to-date list)
- Check the modules directory:
/modules/in the testcontainers-go GitHub repository - Module documentation: https://golang.testcontainers.org/modules/ (online docs for each module)
- Browse by category (see lists above)
- Search for examples: Each module has
examples_test.goin its directory
Module location pattern:
github.com/testcontainers/testcontainers-go/modules/<module-name>
3. Using Generic Containers (Fallback)
When no pre-configured module exists, use generic containers.
IMPORTANT: Always add a wait strategy when exposing ports to ensure the container is ready before tests run. This is critical for reliability, especially in CI environments. Never use time.Sleep as a substitute - it's an anti-pattern that leads to flaky tests.
func TestCustomContainer(t *testing.T) {
ctx := context.Background()
ctr, err := testcontainers.Run(
ctx,
"custom-image:latest",
testcontainers.WithExposedPorts("8080/tcp"),
testcontainers.WithEnv(map[string]string{
"APP_ENV": "test",
}),
// CRITICAL: Always add wait strategy for exposed ports
testcontainers.WithWaitStrategy(
wait.ForListeningPort("8080/tcp").WithStartupTimeout(time.Second*30),
),
)
testcontainers.CleanupContainer(t, ctr)
require.NoError(t, err)
// Get endpoint
endpoint, err := ctr.Endpoint(ctx, "http")
require.NoError(t, err)
}
Common generic container options:
testcontainers.Run(
ctx,
"image:tag",
// Ports
testcontainers.WithExposedPorts("80/tcp", "443/tcp"),
// Environment
testcontainers.WithEnv(map[string]string{
"KEY": "value",
}),
// Files
testcontainers.WithFiles(testcontainers.ContainerFile{
Reader: strings.NewReader("content"),
ContainerFilePath: "/app/config.yml",
FileMode: 0o644,
}),
// Volumes
testcontainers.WithHostConfigModifier(func(hc *container.HostConfig) {
hc.Binds = []string{"/host/path:/container/path"}
}),
// Wait strategies (REQUIRED when using WithExposedPorts)
// Use wait.ForListeningPort for reliability - never use time.Sleep!
testcontainers.WithWaitStrategy(
wait.ForListeningPort("80/tcp"),
// Or use other strategies: wait.ForLog(), wait.ForHTTP(), etc.
),
// Commands
testcontainers.WithAfterReadyCommand(
testcontainers.NewRawCommand([]string{"echo", "initialized"}),
),
// Labels
testcontainers.WithLabels(map[string]string{
"app": "myapp",
}),
)
4. Writing Integration Tests
Test Structure Best Practices
package myapp_test
import (
"context"
"testing"
"github.com/stretchr/testify/require"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/postgres"
)
func TestDatabaseOperations(t *testing.T) {
// 1. Setup: Create context
ctx := context.Background()
// 2. Start container
pgContainer, err := postgres.Run(ctx, "postgres:16-alpine")
// 3. CRITICAL: Register cleanup BEFORE error check
testcontainers.CleanupContainer(t, pgContainer)
// 4. Check for errors
require.NoError(t, err)
// 5. Get connection details
connStr, err := pgContainer.ConnectionString(ctx)
require.NoError(t, err)
// 6. Connect to service
db, err := sql.Open("postgres", connStr)
require.NoError(t, err)
defer db.Close()
// 7. Run your tests
err = db.Ping()
require.NoError(t, err)
// Test your application logic here...
}
Critical pattern: Cleanup BEFORE error checking
// CORRECT:
ctr, err := testcontainers.Run(ctx, "nginx:alpine")
testcontainers.CleanupContainer(t, ctr) // Register cleanup immediately
require.NoError(t, err) // Then check error
// WRONG: Creates resource leaks
ctr, err := testcontainers.Run(ctx, "nginx:alpine")
require.NoError(t, err) // If this fails...
testcontainers.CleanupContainer(t, ctr) // ...cleanup never registers
Table-Driven Tests with Containers
func TestMultipleVersions(t *testing.T) {
ctx := context.Background()
versions := []struct {
name string
image string
}{
{"Postgres 14", "postgres:14-alpine"},
{"Postgres 15", "postgres:15-alpine"},
{"Postgres 16", "postgres:16-alpine"},
}
for _, tc := range versions {
t.Run(tc.name, func(t *testing.T) {
pgContainer, err := postgres.Run(ctx, tc.image)
testcontainers.CleanupContainer(t, pgContainer)
require.NoError(t, err)
// Run tests against this version...
})
}
}
Parallel Test Execution
func TestParallelContainers(t *testing.T) {
t.Parallel() // Enable parallel execution
ctx := context.Background()
pgContainer, err := postgres.Run(ctx, "postgres:16-alpine")
testcontainers.CleanupContainer(t, pgContainer)
require.NoError(t, err)
// Each parallel test gets its own container
}
5. Container Networking
Connecting Multiple Containers
import "github.com/testcontainers/testcontainers-go/network"
func TestMultipleServices(t *testing.T) {
ctx := context.Background()
// Create custom network
nw, err := network.New(ctx)
testcontainers.CleanupNetwork(t, nw)
require.NoError(t, err)
// Start database on network
pgContainer, err := postgres.Run(
ctx,
"postgres:16-alpine",
network.WithNetwork([]string{"database"}, nw),
)
testcontainers.CleanupContainer(t, pgContainer)
require.NoError(t, err)
// Start application on same network
appContainer, err := testcontainers.Run(
ctx,
"myapp:latest",
testcontainers.WithEnv(map[string]string{
"DB_HOST": "database", // Can reach via network alias
"DB_PORT": "5432", // Use internal port, not mapped port
}),
network.WithNetwork([]string{"app"}, nw),
)
testcontainers.CleanupContainer(t, appContainer)
require.NoError(t, err)
// Test application can communicate with database...
}
Accessing Container Ports
func TestPortAccess(t *testing.T) {
ctx := context.Background()
ctr, err := testcontainers.Run(
ctx,
"nginx:alpine",
testcontainers.WithExposedPorts("80/tcp"),
)
testcontainers.CleanupContainer(t, ctr)
require.NoError(t, err)
// Method 1: Get full endpoint (recommended)
endpoint, err := ctr.Endpoint(ctx, "http")
require.NoError(t, err)
// endpoint = "http://localhost:49153"
// Method 2: Get mapped port only
port, err := ctr.MappedPort(ctx, "80/tcp")
require.NoError(t, err)
portNum := port.Int() // e.g., 49153
// Method 3: Get host and port separately
host, err := ctr.Host(ctx)
require.NoError(t, err)
// host = "localhost" (or docker host IP)
}
6. Resource Management & Cleanup
Cleanup Methods
Method 1: testcontainers.CleanupContainer() (Recommended)
func TestRecommendedCleanup(t *testing.T) {
ctx := context.Background()
ctr, err := testcontainers.Run(ctx, "nginx:alpine")
testcontainers.CleanupContainer(t, ctr) // Registers with t.Cleanup
require.NoError(t, err)
// Container automatically cleaned up when test ends
}
Method 2: t.Cleanup() (Manual)
func TestManualCleanup(t *testing.T) {
ctx := context.Background()
ctr, err := testcontainers.Run(ctx, "nginx:alpine")
require.NoError(t, err)
t.Cleanup(func() {
err := testcontainers.TerminateContainer(ctr)
require.NoError(t, err)
})
}
Method 3: defer (Legacy)
func TestDeferCleanup(t *testing.T) {
ctx := context.Background()
ctr, err := testcontainers.Run(ctx, "nginx:alpine")
require.NoError(t, err)
defer func() {
err := testcontainers.TerminateContainer(ctr)
require.NoError(t, err)
}()
}
Cleanup Options
// Cleanup with custom timeout
testcontainers.CleanupContainer(t, ctr,
testcontainers.StopTimeout(10*time.Second),
)
// Cleanup and remove volumes
testcontainers.CleanupContainer(t, ctr,
testcontainers.RemoveVolumes("volume1", "volume2"),
)
// Combine options
testcontainers.CleanupContainer(t, ctr,
testcontainers.StopTimeout(5*time.Second),
testcontainers.RemoveVolumes("data"),
)
Automatic Cleanup with Ryuk
Testcontainers for Go uses Ryuk, a garbage collector that automatically cleans up containers even if tests crash or timeout:
- Runs as a sidecar container (
testcontainers/ryuk:0.13.0) - Monitors test session lifecycle
- Cleans up containers when session ends
- Handles parallel test execution
Control Ryuk behavior:
// Disable Ryuk (not recommended)
os.Setenv("TESTCONTAINERS_RYUK_DISABLED", "true")
// Enable verbose logging
os.Setenv("RYUK_VERBOSE", "true")
// Adjust timeouts
os.Setenv("RYUK_CONNECTION_TIMEOUT", "2m")
os.Setenv("RYUK_RECONNECTION_TIMEOUT", "30s")
7. Configuration Patterns
Environment Variables
testcontainers.Run(
ctx,
"myapp:latest",
testcontainers.WithEnv(map[string]string{
"DATABASE_URL": "postgres://localhost/db",
"LOG_LEVEL": "debug",
"API_KEY": "test-key",
}),
)
Executing Commands in Containers
When executing commands with Exec(), it's recommended to use exec.Multiplexed() to properly handle Docker's output format:
import "github.com/testcontainers/testcontainers-go/exec"
// Execute command with Multiplexed option
exitCode, reader, err := ctr.Exec(ctx, []string{"sh", "-c", "echo 'hello'"}, exec.Multiplexed())
require.NoError(t, err)
require.Equal(t, 0, exitCode)
// Read the output
output, err := io.ReadAll(reader)
require.NoError(t, err)
fmt.Println(string(output))
Why use exec.Multiplexed()?
- Removes Docker's multiplexing headers from the output
- Combines stdout and stderr into a single clean stream
- Makes the output easier to read and parse
Without exec.Multiplexed(), you'll get Docker's raw multiplexed stream which includes header bytes that are difficult to parse.
Files and Directories
// Copy single file
testcontainers.Run(
ctx,
"nginx:alpine",
testcontainers.WithFiles(testcontainers.ContainerFile{
Reader: strings.NewReader("server { listen 80; }"),
ContainerFilePath: "/etc/nginx/conf.d/default.conf",
FileMode: 0o644,
}),
)
// Copy multiple files
testcontainers.Run(
ctx,
"myapp:latest",
testcontainers.WithFiles(
testcontainers.ContainerFile{...}, // config.yml
testcontainers.ContainerFile{...}, // secrets.json
),
)
// Copy from container after start
ctr, _ := testcontainers.Run(ctx, "nginx:alpine")
reader, err := ctr.CopyFileFromContainer(ctx, "/etc/nginx/nginx.conf")
content, _ := io.ReadAll(reader)
Volume Mounts
testcontainers.Run(
ctx,
"postgres:16",
testcontainers.WithHostConfigModifier(func(hc *container.HostConfig) {
// Bind mount
hc.Binds = []string{
"/host/data:/var/lib/postgresql/data",
}
// Named volume
hc.Mounts = []mount.Mount{
{
Type: mount.TypeVolume,
Source: "pgdata",
Target: "/var/lib/postgresql/data",
},
}
}),
)
Temporary Filesystems
testcontainers.Run(
ctx,
"myapp:latest",
testcontainers.WithTmpfs(map[string]string{
"/tmp": "rw",
"/app/temp": "rw,size=100m,mode=1777",
}),
)
8. Wait Strategies
Wait strategies are critical for reliable tests. They ensure containers are fully ready before tests run, which is especially important in CI environments where timing can vary.
Best Practices:
- ✅ Always use
wait.ForListeningPort()when exposing ports - This is the most reliable approach - ✅ Choose appropriate wait strategies based on your service (HTTP health checks, log patterns, etc.)
- ❌ Never use
time.Sleep()- This is an anti-pattern that leads to flaky tests - ✅ Set reasonable timeouts to handle slow CI environments
Port-Based Waiting (Recommended for Exposed Ports)
import "github.com/testcontainers/testcontainers-go/wait"
testcontainers.Run(
ctx,
"postgres:16",
testcontainers.WithWaitStrategy(
wait.ForListeningPort("5432/tcp").
WithStartupTimeout(30*time.Second).
WithPollInterval(1*time.Second),
),
)
Log-Based Waiting
testcontainers.Run(
ctx,
"elasticsearch:8.7.0",
testcontainers.WithWaitStrategy(
wait.ForLog("started").
WithStartupTimeout(60*time.Second).
WithOccurrence(1),
),
)
HTTP-Based Waiting
testcontainers.Run(
ctx,
"myapp:latest",
testcontainers.WithWaitStrategy(
wait.ForHTTP("/health").
WithPort("8080/tcp").
WithStatusCodeMatcher(func(status int) bool {
return status == 200
}).
WithStartupTimeout(30*time.Second),
),
)
SQL-Based Waiting
testcontainers.Run(
ctx,
"postgres:16",
testcontainers.WithWaitStrategy(
wait.ForSQL("5432/tcp", "postgres", func(host string, port nat.Port) string {
return fmt.Sprintf("postgres://user:pass@%s:%s/db?sslmode=disable",
host, port.Port())
}).WithStartupTimeout(30*time.Second),
),
)
Multiple Wait Strategies
testcontainers.Run(
ctx,
"myapp:latest",
testcontainers.WithWaitStrategy(
wait.ForAll(
wait.ForListeningPort("8080/tcp"),
wait.ForLog("Application started"),
wait.ForHTTP("/health"),
),
),
)
9. Troubleshooting
Check Docker Availability
func TestDockerConnection(t *testing.T) {
testcontainers.SkipIfProviderIsNotHealthy(t)
ctx := context.Background()
cli, err := testcontainers.NewDockerClientWithOpts(ctx)
require.NoError(t, err)
info, err := cli.Info(ctx)
require.NoError(t, err)
t.Logf("Docker version: %s", info.ServerVersion)
t.Logf("OS: %s", info.OperatingSystem)
}
Debug Container Logs
func TestWithLogging(t *testing.T) {
ctx := context.Background()
// Method 1: Stream to stdout
ctr, _ := testcontainers.Run(
ctx,
"myapp:latest",
testcontainers.WithLogConsumers(
&testcontainers.StdoutLogConsumer{},
),
)
testcontainers.CleanupContainer(t, ctr)
// Method 2: Read logs manually
rc, _ := ctr.Logs(ctx)
defer rc.Close()
logs, _ := io.ReadAll(rc)
t.Logf("Container logs:\n%s", string(logs))
// Method 3: Inspect container
info, _ := ctr.Inspect(ctx)
t.Logf("Container state: %+v", info.State)
}
Common Issues
Issue: Container startup timeout
// Increase wait timeout
testcontainers.WithWaitStrategy(
wait.ForListeningPort("5432/tcp").
WithStartupTimeout(60*time.Second), // Increase from default
)
// Check logs to see what's happening
testcontainers.WithLogConsumers(&testcontainers.StdoutLogConsumer{})
Issue: Port already in use
- Testcontainers auto-assigns random ports
- Don't manually specify host ports unless necessary
- Check for leaked containers:
docker ps -a
Issue: Image pull failures
# Pull manually first to verify
docker pull postgres:16
# For private registries, login first
docker login registry.example.com
# Testcontainers will use credentials from ~/.docker/config.json
Issue: Container not cleaning up
// Verify Ryuk is running
docker ps | grep ryuk
// Check cleanup is registered correctly
testcontainers.CleanupContainer(t, ctr) // Before error check!
Environment Variables for Debugging
# Enable Ryuk verbose logging
export RYUK_VERBOSE=true
# Adjust timeouts
export RYUK_CONNECTION_TIMEOUT=2m
export RYUK_RECONNECTION_TIMEOUT=30s
# Custom Docker socket
export DOCKER_HOST=unix:///var/run/docker.sock
# Registry prefix for private registry
export TESTCONTAINERS_HUB_IMAGE_NAME_PREFIX=private.registry.com
10. Shared Setup & Build Tags
Build Tags for Integration Tests
Separate integration tests from unit tests using Go build tags. This prevents integration tests from running during go test ./... unless explicitly opted in.
//go:build integration
package myapp_test
import (
"context"
"testing"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/postgres"
)
func TestIntegrationWithPostgres(t *testing.T) {
ctx := context.Background()
pgContainer, err := postgres.Run(ctx, "postgres:16-alpine")
testcontainers.CleanupContainer(t, pgContainer)
require.NoError(t, err)
// Integration test logic...
}
Run integration tests explicitly:
# Run only integration tests
go test -tags=integration ./...
# Run only unit tests (default, no tag needed)
go test ./...
TestMain for Shared Container Setup
When multiple tests in a package need the same container, use TestMain to start the container once and share it across all tests. This drastically reduces test execution time.
package myapp_test
import (
"context"
"database/sql"
"fmt"
"os"
"testing"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/postgres"
)
var testDB *sql.DB
func TestMain(m *testing.M) {
ctx := context.Background()
pgContainer, err := postgres.Run(ctx, "postgres:16-alpine",
postgres.WithDatabase("testdb"),
)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to start postgres: %s\n", err)
os.Exit(1)
}
connStr, err := pgContainer.ConnectionString(ctx, "sslmode=disable")
if err != nil {
fmt.Fprintf(os.Stderr, "failed to get connection string: %s\n", err)
os.Exit(1)
}
testDB, err = sql.Open("postgres", connStr)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to open db: %s\n", err)
os.Exit(1)
}
// Run tests
code := m.Run()
// Cleanup
testDB.Close()
testcontainers.TerminateContainer(pgContainer)
os.Exit(code)
}
func TestCreateUser(t *testing.T) {
// testDB is shared across all tests — no container startup delay
_, err := testDB.Exec("INSERT INTO users (name) VALUES ($1)", "Alice")
require.NoError(t, err)
}
func TestGetUser(t *testing.T) {
var name string
err := testDB.QueryRow("SELECT name FROM users LIMIT 1").Scan(&name)
require.NoError(t, err)
}
When to use TestMain vs per-test containers:
- TestMain: All tests in a package need the same service, test speed is important
- Per-test containers: Tests need different configurations, or test isolation is critical
11. CI/CD Integration
GitHub Actions
name: Integration Tests
on: [push, pull_request]
jobs:
integration-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.24'
- name: Run integration tests
run: go test -tags=integration -v -timeout 10m ./...
Key CI considerations:
- Docker is pre-installed on GitHub Actions Ubuntu runners
- Increase test timeout (
-timeout 10m) for container startup in CI - Use
-count=1to disable test caching when debugging - Consider
-raceflag for race condition detection
Environment Configuration for CI
// Detect CI environment and adjust timeouts
func getStartupTimeout() time.Duration {
if os.Getenv("CI") != "" {
return 120 * time.Second // Longer timeout in CI
}
return 30 * time.Second
}
// Use in wait strategy
testcontainers.WithWaitStrategy(
wait.ForListeningPort("5432/tcp").
WithStartupTimeout(getStartupTimeout()),
)
Anti-Patterns
Avoid these common mistakes when writing tests with Testcontainers.
❌ Using time.Sleep() for Synchronization
// WRONG: Flaky, slow, unreliable
ctr, err := testcontainers.Run(ctx, "postgres:16",
testcontainers.WithExposedPorts("5432/tcp"),
)
time.Sleep(5 * time.Second) // DON'T DO THIS
// CORRECT: Use wait strategies
ctr, err := testcontainers.Run(ctx, "postgres:16",
testcontainers.WithExposedPorts("5432/tcp"),
testcontainers.WithWaitStrategy(
wait.ForListeningPort("5432/tcp").
WithStartupTimeout(30*time.Second),
),
)
❌ Checking Errors Before Registering Cleanup
// WRONG: Resource leak if Run succeeds but error is non-nil
ctr, err := testcontainers.Run(ctx, "nginx:alpine")
require.NoError(t, err) // If this panics...
testcontainers.CleanupContainer(t, ctr) // ...cleanup never runs
// CORRECT: Always register cleanup first
ctr, err := testcontainers.Run(ctx, "nginx:alpine")
testcontainers.CleanupContainer(t, ctr) // Register cleanup immediately
require.NoError(t, err) // Then check error
❌ Using Generic Containers When a Module Exists
// WRONG: Reinventing the wheel
ctr, err := testcontainers.Run(ctx, "postgres:16-alpine",
testcontainers.WithExposedPorts("5432/tcp"),
testcontainers.WithEnv(map[string]string{
"POSTGRES_USER": "user",
"POSTGRES_PASSWORD": "pass",
"POSTGRES_DB": "mydb",
}),
testcontainers.WithWaitStrategy(
wait.ForLog("database system is ready to accept connections").
WithOccurrence(2),
),
)
// CORRECT: Use the PostgreSQL module
pgContainer, err := postgres.Run(ctx, "postgres:16-alpine",
postgres.WithDatabase("mydb"),
postgres.WithUsername("user"),
postgres.WithPassword("pass"),
)
❌ Hardcoding Ports
// WRONG: Port conflicts, breaks in CI
host, _ := ctr.Host(ctx)
url := fmt.Sprintf("http://%s:8080/api", host) // Hardcoded port!
// CORRECT: Use mapped ports
endpoint, err := ctr.Endpoint(ctx, "http")
url := fmt.Sprintf("%s/api", endpoint) // Uses dynamically assigned port
❌ Missing Wait Strategy for Exposed Ports
// WRONG: Container may not be ready when tests start
ctr, err := testcontainers.Run(ctx, "myapp:latest",
testcontainers.WithExposedPorts("8080/tcp"),
// No wait strategy!
)
// CORRECT: Always add a wait strategy when exposing ports
ctr, err := testcontainers.Run(ctx, "myapp:latest",
testcontainers.WithExposedPorts("8080/tcp"),
testcontainers.WithWaitStrategy(
wait.ForListeningPort("8080/tcp").
WithStartupTimeout(30*time.Second),
),
)
Validation Checklist
After writing a test with Testcontainers, verify these items:
- Cleanup registered before error check —
CleanupContainer(t, ctr)appears beforerequire.NoError(t, err) - Module used when available — Not using generic container for a service that has a module
- Wait strategy present — Every
WithExposedPorts()has a correspondingWithWaitStrategy()(or the module provides one) - No
time.Sleep()for synchronization — Wait strategies used instead - No hardcoded ports — Using
MappedPort()orEndpoint()for dynamically assigned ports - Proper imports — All required packages imported (module, wait, network, etc.)
- Context passed —
context.Background()created and passed to container operations - Resources closed — Database connections, Redis clients, etc. are closed with
defer - Build tags used (optional) —
//go:build integrationtag for integration test files - Test compiles — Run
go vet ./...andgo build ./...to catch issues early
Examples
Example 1: PostgreSQL Integration Test
package myapp_test
import (
"context"
"database/sql"
"testing"
_ "github.com/lib/pq"
"github.com/stretchr/testify/require"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/postgres"
)
func TestUserRepository(t *testing.T) {
ctx := context.Background()
// Start PostgreSQL container
pgContainer, err := postgres.Run(
ctx,
"postgres:16-alpine",
postgres.WithDatabase("testdb"),
postgres.WithUsername("testuser"),
postgres.WithPassword("testpass"),
postgres.WithInitScripts("./testdata/schema.sql"),
)
testcontainers.CleanupContainer(t, pgContainer)
require.NoError(t, err)
// Get connection string
connStr, err := pgContainer.ConnectionString(ctx, "sslmode=disable")
require.NoError(t, err)
// Connect to database
db, err := sql.Open("postgres", connStr)
require.NoError(t, err)
defer db.Close()
// Test your repository
repo := NewUserRepository(db)
t.Run("CreateUser", func(t *testing.T) {
user := &User{Name: "Alice", Email: "alice@example.com"}
err := repo.Create(user)
require.NoError(t, err)
require.NotZero(t, user.ID)
})
t.Run("GetUser", func(t *testing.T) {
user, err := repo.GetByEmail("alice@example.com")
require.NoError(t, err)
require.Equal(t, "Alice", user.Name)
})
}
Example 2: Redis Cache Test
package cache_test
import (
"context"
"testing"
"time"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/require"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/redis"
)
func TestRedisCache(t *testing.T) {
ctx := context.Background()
// Start Redis container
redisContainer, err := redis.Run(
ctx,
"redis:7-alpine",
redis.WithSnapshotting(10, 1),
redis.WithLogLevel(redis.LogLevelVerbose),
)
testcontainers.CleanupContainer(t, redisContainer)
require.NoError(t, err)
// Get connection string
connStr, err := redisContainer.ConnectionString(ctx)
require.NoError(t, err)
// Connect to Redis
opt, err := redis.ParseURL(connStr)
require.NoError(t, err)
client := redis.NewClient(opt)
defer client.Close()
// Test cache operations
t.Run("SetAndGet", func(t *testing.T) {
err := client.Set(ctx, "key1", "value1", time.Minute).Err()
require.NoError(t, err)
val, err := client.Get(ctx, "key1").Result()
require.NoError(t, err)
require.Equal(t, "value1", val)
})
t.Run("Expiration", func(t *testing.T) {
err := client.Set(ctx, "key2", "value2", time.Second).Err()
require.NoError(t, err)
time.Sleep(2 * time.Second)
_, err = client.Get(ctx, "key2").Result()
require.Equal(t, redis.Nil, err)
})
}
Example 3: Kafka Producer/Consumer Test
package messaging_test
import (
"context"
"testing"
"time"
"github.com/segmentio/kafka-go"
"github.com/stretchr/testify/require"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/kafka"
)
func TestKafkaMessaging(t *testing.T) {
ctx := context.Background()
// Start Kafka container
kafkaContainer, err := kafka.Run(
ctx,
"confluentinc/confluent-local:7.5.0",
kafka.WithClusterID("test-cluster"),
)
testcontainers.CleanupContainer(t, kafkaContainer)
require.NoError(t, err)
// Get bootstrap servers
brokers, err := kafkaContainer.Brokers(ctx)
require.NoError(t, err)
topic := "test-topic"
// Create producer
writer := kafka.NewWriter(kafka.WriterConfig{
Brokers: brokers,
Topic: topic,
})
defer writer.Close()
// Create consumer
reader := kafka.NewReader(kafka.ReaderConfig{
Brokers: brokers,
Topic: topic,
GroupID: "test-group",
})
defer reader.Close()
// Test message flow
t.Run("ProduceAndConsume", func(t *testing.T) {
// Produce message
err := writer.WriteMessages(ctx, kafka.Message{
Key: []byte("key1"),
Value: []byte("Hello, Kafka!"),
})
require.NoError(t, err)
// Consume message
msg, err := reader.ReadMessage(ctx)
require.NoError(t, err)
require.Equal(t, "Hello, Kafka!", string(msg.Value))
})
}
Example 4: Multi-Container Application Stack
package integration_test
import (
"context"
"net/http"
"testing"
"github.com/stretchr/testify/require"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/postgres"
"github.com/testcontainers/testcontainers-go/modules/redis"
"github.com/testcontainers/testcontainers-go/network"
)
func TestFullStack(t *testing.T) {
ctx := context.Background()
// Create custom network
nw, err := network.New(ctx)
testcontainers.CleanupNetwork(t, nw)
require.NoError(t, err)
// Start PostgreSQL
pgContainer, err := postgres.Run(
ctx,
"postgres:16-alpine",
network.WithNetwork([]string{"database"}, nw),
)
testcontainers.CleanupContainer(t, pgContainer)
require.NoError(t, err)
// Start Redis
redisContainer, err := redis.Run(
ctx,
"redis:7-alpine",
network.WithNetwork([]string{"cache"}, nw),
)
testcontainers.CleanupContainer(t, redisContainer)
require.NoError(t, err)
// Start application
appContainer, err := testcontainers.Run(
ctx,
"myapp:latest",
testcontainers.WithEnv(map[string]string{
"DB_HOST": "database",
"DB_PORT": "5432",
"REDIS_HOST": "cache",
"REDIS_PORT": "6379",
}),
testcontainers.WithExposedPorts("8080/tcp"),
network.WithNetwork([]string{"app"}, nw),
)
testcontainers.CleanupContainer(t, appContainer)
require.NoError(t, err)
// Get application endpoint
endpoint, err := appContainer.Endpoint(ctx, "http")
require.NoError(t, err)
// Test application
resp, err := http.Get(endpoint + "/health")
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
}
Example 5: Docker Compose Stack
package compose_test
import (
"context"
"testing"
"github.com/stretchr/testify/require"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/compose"
)
func TestComposeStack(t *testing.T) {
ctx := context.Background()
// Start services from docker-compose.yml
composeStack, err := compose.NewDockerCompose("./docker-compose.yml")
require.NoError(t, err)
t.Cleanup(func() {
if err := composeStack.Down(ctx); err != nil {
t.Fatalf("failed to down compose stack: %v", err)
}
})
err = composeStack.Up(ctx, compose.Wait(true))
require.NoError(t, err)
// Get service container
webContainer, err := composeStack.ServiceContainer(ctx, "web")
require.NoError(t, err)
// Test service
endpoint, err := webContainer.Endpoint(ctx, "http")
require.NoError(t, err)
// Run tests against the stack...
}
Best Practices
- Always use pre-configured modules when available - They provide sensible defaults and helper methods
- Register cleanup immediately - Call
testcontainers.CleanupContainer(t, ctr)before checking errors - Always add wait strategies when exposing ports - Use
wait.ForListeningPort()to ensure reliability, especially in CI. Never usetime.Sleep()- it's an anti-pattern that causes flaky tests - Choose appropriate wait strategies - Use
wait.ForHTTP()for health endpoints,wait.ForLog()for log patterns, orwait.ForListeningPort()for port availability - Leverage table-driven tests - Test against multiple versions or configurations
- Use custom networks - For multi-container communication
- Keep containers ephemeral - Don't rely on state between tests
- Check Docker availability - Use
testcontainers.SkipIfProviderIsNotHealthy(t) - Enable parallel execution - Use
t.Parallel()for faster test suites - Use module helper methods - E.g.,
ConnectionString(),Snapshot(),Restore() - Debug with logs - Use
WithLogConsumers()when troubleshooting
Additional Resources
- Official Documentation: https://golang.testcontainers.org/
- Available Modules: https://testcontainers.com/modules/?language=go (complete, up-to-date list)
- Module Documentation: https://golang.testcontainers.org/modules/ (online docs for each module)
- GitHub Repository: https://github.com/testcontainers/testcontainers-go
- Module Examples: Check
modules/*/examples_test.gofiles in the GitHub repository - Community Slack: testcontainers.slack.com
Sponsors
Details
- Marketplace
- testcontainers/claude-skills
- Source
- plugins/testcontainers
- Author
- Testcontainers
- Category
- Development
- Keywords
- testcontainers, go, dotnet, csharp, python, docker, integration-testing, testing, containers, databases, mongodb, postgres, sqlserver, message-queues, redis, rabbitmq, kafka, mysql, entityframework