Docker Testcontainers
This skill makes an AI agent write integration tests that spin up real databases, caches, and message brokers in disposable Docker containers via the testcontainers Node.js library - instead of mocking them or depending on a shared dev server. Trigger it when tests need a real Postgres, Redis, Kafka, or any service with Docker image, when a repo already imports testcontainers, or when the user complains that mocked repositories keep hiding SQL and serialization bugs.
Core Principles
- Test against the real engine, not a lookalike. SQLite in place of Postgres misses JSONB operators, transaction isolation behavior, and case-sensitivity rules. Run the exact image and major version production uses (
postgres:16-alpine, not latest).
- Always use mapped ports. Containers bind to random free host ports. Read them with
container.getMappedPort(5432) and container.getHost(); hardcoding localhost:5432 collides with local services and parallel CI jobs.
- Wait strategies, not sleeps. A started container is not a ready service. Use
Wait.forLogMessage, Wait.forListeningPorts, Wait.forHttp, or Wait.forHealthCheck so tests begin exactly when the dependency is usable.
- One container per suite, clean state per test. Container startup costs seconds; start in
beforeAll, then reset state between tests with TRUNCATE, FLUSHALL, or transaction rollbacks - not by restarting the container.
- Cleanup must survive failures. Stop containers in
afterAll; Testcontainers' Ryuk sidecar reaps anything left behind if the process dies, so never disable it in CI.
- Pin image tags.
redis:latest changing under you turns a green suite red with zero code changes. Pin to a major-minor tag and upgrade deliberately.
Setup
npm install --save-dev testcontainers @testcontainers/postgresql
# Requires a running Docker daemon (Docker Desktop, Colima, or CI's dockerd)
docker info
Patterns
1. GenericContainer: Redis with a wait strategy
// tests/cache.integration.test.ts
import { GenericContainer, StartedTestContainer, Wait } from 'testcontainers';
import { createClient, RedisClientType } from 'redis';
describe('rate limiter backed by Redis', () => {
let container: StartedTestContainer;
let client: RedisClientType;
beforeAll(async () => {
container = await new GenericContainer('redis:7.4-alpine')
.withExposedPorts(6379)
.withWaitStrategy(Wait.forLogMessage('Ready to accept connections'))
.withStartupTimeout(30_000)
.start();
client = createClient({
url: `redis://${container.getHost()}:${container.getMappedPort(6379)}`,
});
await client.connect();
}, 60_000);
afterEach(async () => {
await client.flushAll();
});
afterAll(async () => {
await client.quit();
await container.stop();
});
it('blocks the 6th request within a window', async () => {
for (let i = 0; i < 5; i++) {
expect(await isAllowed(client, 'user-1')).toBe(true);
}
expect(await isAllowed(client, 'user-1')).toBe(false);
});
});
async function isAllowed(client: RedisClientType, key: string): Promise<boolean> {
const count = await client.incr(`rl:${key}`);
if (count === 1) await client.expire(`rl:${key}`, 60);
return count <= 5;
}
2. Module container: Postgres with real migrations
// tests/orders.repository.integration.test.ts
import { PostgreSqlContainer, StartedPostgreSqlContainer } from '@testcontainers/postgresql';
import { Pool } from 'pg';
import { runMigrations } from '../src/db/migrate';
import { OrdersRepository } from '../src/db/orders-repository';
let pg: StartedPostgreSqlContainer;
let pool: Pool;
let repo: OrdersRepository;
beforeAll(async () => {
pg = await new PostgreSqlContainer('postgres:16-alpine')
.withDatabase('shop_test')
.withUsername('shop')
.withPassword('shop')
.start();
pool = new Pool({ connectionString: pg.getConnectionUri() });
await runMigrations(pool); // the SAME migrations production runs
repo = new OrdersRepository(pool);
}, 90_000);
beforeEach(async () => {
await pool.query('TRUNCATE orders RESTART IDENTITY CASCADE');
});
afterAll(async () => {
await pool.end();
await pg.stop();
});
it('persists JSONB line items and filters with the @> operator', async () => {
await repo.create({ customerId: 'c1', items: [{ sku: 'SKU-1', qty: 2 }] });
await repo.create({ customerId: 'c2', items: [{ sku: 'SKU-9', qty: 1 }] });
const matches = await repo.findByItemSku('SKU-1'); // uses items @> '[{"sku":"SKU-1"}]'
expect(matches).toHaveLength(1);
expect(matches[0].customerId).toBe('c1');
});
3. Docker Compose environment for multi-service tests
// tests/api.e2e.integration.test.ts
import { DockerComposeEnvironment, StartedDockerComposeEnvironment, Wait } from 'testcontainers';
let environment: StartedDockerComposeEnvironment;
let apiBaseUrl: string;
beforeAll(async () => {
environment = await new DockerComposeEnvironment('.', 'docker-compose.test.yml')
.withWaitStrategy('api-1', Wait.forHttp('/health', 3000).forStatusCode(200))
.withWaitStrategy('postgres-1', Wait.forListeningPorts())
.up(['api', 'postgres']);
const api = environment.getContainer('api-1');
apiBaseUrl = `http://${api.getHost()}:${api.getMappedPort(3000)}`;
}, 120_000);
afterAll(async () => {
await environment.down({ timeout: 10_000 });
});
it('serves orders through the full stack', async () => {
const created = await fetch(`${apiBaseUrl}/orders`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ sku: 'SKU-1', qty: 1 }),
});
expect(created.status).toBe(201);
const list = await fetch(`${apiBaseUrl}/orders`);
const orders = (await list.json()) as Array<{ sku: string }>;
expect(orders.map((o) => o.sku)).toContain('SKU-1');
});
4. Faster local loops: container reuse and env wiring
// Opt-in reuse keeps the container alive between test runs locally.
// Requires testcontainers.reuse.enable=true in ~/.testcontainers.properties
const pg = await new PostgreSqlContainer('postgres:16-alpine')
.withDatabase('shop_test')
.withReuse()
.start();
// Hand the dynamic URL to the code under test the same way prod config does
process.env.DATABASE_URL = pg.getConnectionUri();
// Copying fixtures and running one-off commands inside a container
const container = await new GenericContainer('postgres:16-alpine')
.withEnvironment({ POSTGRES_PASSWORD: 'shop' })
.withCopyFilesToContainer([
{ source: './tests/fixtures/seed.sql', target: '/docker-entrypoint-initdb.d/seed.sql' },
])
.withExposedPorts(5432)
.start();
const { exitCode, output } = await container.exec(['psql', '-U', 'postgres', '-c', 'SELECT 1']);
expect(exitCode).toBe(0);
expect(output).toContain('1 row');
Best Practices
- Raise the test framework timeout for
beforeAll hooks that pull images (60-120 seconds); the first CI run downloads layers.
- Use module packages (
@testcontainers/postgresql, @testcontainers/kafka, @testcontainers/elasticsearch) before reaching for GenericContainer; they encode correct wait strategies and credentials.
- In CI, pre-pull hot images (
docker pull postgres:16-alpine) in a cached step to cut suite time.
- Keep integration tests in a separate script (
"test:integration": "vitest run --config vitest.integration.config.ts") so unit tests stay Docker-free and fast.
- Pass connection details via the same env vars production reads (
DATABASE_URL, REDIS_URL); never add test-only config paths to the app.
- Log container output on failure with
container.logs() streamed to the test reporter when diagnosing startup issues.
Anti-Patterns
await sleep(3000) after start() instead of a wait strategy - slow on good days, flaky on loaded CI runners.
- One shared, long-lived "test database" server that every developer and CI job mutates; state leaks make failures non-reproducible.
- Restarting the container between tests for isolation; truncate tables or roll back transactions instead and save minutes per suite.
- Mocking the repository layer in "integration" tests - the SQL is exactly the thing that needs testing.
- Using
:latest tags or a different database engine than production.
- Disabling Ryuk (
TESTCONTAINERS_RYUK_DISABLED=true) in CI to "fix" a permissions issue, then leaking containers until the runner dies; fix the Docker socket permissions instead.
When to Trigger This Skill
- The user asks for integration tests against a real Postgres, MySQL, MongoDB, Redis, Kafka, RabbitMQ, Elasticsearch, or LocalStack instance.
- A repository imports
testcontainers or @testcontainers/*, or contains a docker-compose.test.yml.
- Mock-heavy tests keep missing SQL syntax errors, migration drift, or serialization bugs that only a real engine catches.
- CI needs hermetic, parallel-safe integration tests without a provisioned shared database.
- Repository, DAO, or ORM code (Drizzle, Prisma, Knex, TypeORM) needs verification against the production database engine and real migrations.
1---2name: docker-testcontainers3description: Integration testing with real dependencies in throwaway Docker containers using the Testcontainers Node.js API - GenericContainer, exposed ports, wait strategies, module containers, Docker Compose environments, and reliable cleanup.4version: 1.0.05author: thetestingacademy6license: MIT7tags: [testcontainers, docker, integration-testing, postgres, redis, containers, ci, node]8testingTypes: [integration, database]9frameworks: [jest, vitest]10languages: [typescript]11domains: [api, devops]12agents: [claude-code, cursor, github-copilot, windsurf, codex, aider, continue, cline, zed, bolt, gemini-cli, amp]13metadata:14 source: https://skillmd.com/skills/pramoddutta/docker-testcontainers15---1617# Docker Testcontainers1819This skill makes an AI agent write integration tests that spin up real databases, caches, and message brokers in disposable Docker containers via the `testcontainers` Node.js library - instead of mocking them or depending on a shared dev server. Trigger it when tests need a real Postgres, Redis, Kafka, or any service with Docker image, when a repo already imports `testcontainers`, or when the user complains that mocked repositories keep hiding SQL and serialization bugs.2021## Core Principles22231. **Test against the real engine, not a lookalike.** SQLite in place of Postgres misses JSONB operators, transaction isolation behavior, and case-sensitivity rules. Run the exact image and major version production uses (`postgres:16-alpine`, not `latest`).242. **Always use mapped ports.** Containers bind to random free host ports. Read them with `container.getMappedPort(5432)` and `container.getHost()`; hardcoding `localhost:5432` collides with local services and parallel CI jobs.253. **Wait strategies, not sleeps.** A started container is not a ready service. Use `Wait.forLogMessage`, `Wait.forListeningPorts`, `Wait.forHttp`, or `Wait.forHealthCheck` so tests begin exactly when the dependency is usable.264. **One container per suite, clean state per test.** Container startup costs seconds; start in `beforeAll`, then reset state between tests with `TRUNCATE`, `FLUSHALL`, or transaction rollbacks - not by restarting the container.275. **Cleanup must survive failures.** Stop containers in `afterAll`; Testcontainers' Ryuk sidecar reaps anything left behind if the process dies, so never disable it in CI.286. **Pin image tags.** `redis:latest` changing under you turns a green suite red with zero code changes. Pin to a major-minor tag and upgrade deliberately.2930## Setup3132```bash33npm install --save-dev testcontainers @testcontainers/postgresql34# Requires a running Docker daemon (Docker Desktop, Colima, or CI's dockerd)35docker info36```3738## Patterns3940### 1. GenericContainer: Redis with a wait strategy4142```ts43// tests/cache.integration.test.ts44import { GenericContainer, StartedTestContainer, Wait } from 'testcontainers';45import { createClient, RedisClientType } from 'redis';4647describe('rate limiter backed by Redis', () => {48 let container: StartedTestContainer;49 let client: RedisClientType;5051 beforeAll(async () => {52 container = await new GenericContainer('redis:7.4-alpine')53 .withExposedPorts(6379)54 .withWaitStrategy(Wait.forLogMessage('Ready to accept connections'))55 .withStartupTimeout(30_000)56 .start();5758 client = createClient({59 url: `redis://${container.getHost()}:${container.getMappedPort(6379)}`,60 });61 await client.connect();62 }, 60_000);6364 afterEach(async () => {65 await client.flushAll();66 });6768 afterAll(async () => {69 await client.quit();70 await container.stop();71 });7273 it('blocks the 6th request within a window', async () => {74 for (let i = 0; i < 5; i++) {75 expect(await isAllowed(client, 'user-1')).toBe(true);76 }77 expect(await isAllowed(client, 'user-1')).toBe(false);78 });79});8081async function isAllowed(client: RedisClientType, key: string): Promise<boolean> {82 const count = await client.incr(`rl:${key}`);83 if (count === 1) await client.expire(`rl:${key}`, 60);84 return count <= 5;85}86```8788### 2. Module container: Postgres with real migrations8990```ts91// tests/orders.repository.integration.test.ts92import { PostgreSqlContainer, StartedPostgreSqlContainer } from '@testcontainers/postgresql';93import { Pool } from 'pg';94import { runMigrations } from '../src/db/migrate';95import { OrdersRepository } from '../src/db/orders-repository';9697let pg: StartedPostgreSqlContainer;98let pool: Pool;99let repo: OrdersRepository;100101beforeAll(async () => {102 pg = await new PostgreSqlContainer('postgres:16-alpine')103 .withDatabase('shop_test')104 .withUsername('shop')105 .withPassword('shop')106 .start();107108 pool = new Pool({ connectionString: pg.getConnectionUri() });109 await runMigrations(pool); // the SAME migrations production runs110 repo = new OrdersRepository(pool);111}, 90_000);112113beforeEach(async () => {114 await pool.query('TRUNCATE orders RESTART IDENTITY CASCADE');115});116117afterAll(async () => {118 await pool.end();119 await pg.stop();120});121122it('persists JSONB line items and filters with the @> operator', async () => {123 await repo.create({ customerId: 'c1', items: [{ sku: 'SKU-1', qty: 2 }] });124 await repo.create({ customerId: 'c2', items: [{ sku: 'SKU-9', qty: 1 }] });125126 const matches = await repo.findByItemSku('SKU-1'); // uses items @> '[{"sku":"SKU-1"}]'127 expect(matches).toHaveLength(1);128 expect(matches[0].customerId).toBe('c1');129});130```131132### 3. Docker Compose environment for multi-service tests133134```ts135// tests/api.e2e.integration.test.ts136import { DockerComposeEnvironment, StartedDockerComposeEnvironment, Wait } from 'testcontainers';137138let environment: StartedDockerComposeEnvironment;139let apiBaseUrl: string;140141beforeAll(async () => {142 environment = await new DockerComposeEnvironment('.', 'docker-compose.test.yml')143 .withWaitStrategy('api-1', Wait.forHttp('/health', 3000).forStatusCode(200))144 .withWaitStrategy('postgres-1', Wait.forListeningPorts())145 .up(['api', 'postgres']);146147 const api = environment.getContainer('api-1');148 apiBaseUrl = `http://${api.getHost()}:${api.getMappedPort(3000)}`;149}, 120_000);150151afterAll(async () => {152 await environment.down({ timeout: 10_000 });153});154155it('serves orders through the full stack', async () => {156 const created = await fetch(`${apiBaseUrl}/orders`, {157 method: 'POST',158 headers: { 'content-type': 'application/json' },159 body: JSON.stringify({ sku: 'SKU-1', qty: 1 }),160 });161 expect(created.status).toBe(201);162163 const list = await fetch(`${apiBaseUrl}/orders`);164 const orders = (await list.json()) as Array<{ sku: string }>;165 expect(orders.map((o) => o.sku)).toContain('SKU-1');166});167```168169### 4. Faster local loops: container reuse and env wiring170171```ts172// Opt-in reuse keeps the container alive between test runs locally.173// Requires testcontainers.reuse.enable=true in ~/.testcontainers.properties174const pg = await new PostgreSqlContainer('postgres:16-alpine')175 .withDatabase('shop_test')176 .withReuse()177 .start();178179// Hand the dynamic URL to the code under test the same way prod config does180process.env.DATABASE_URL = pg.getConnectionUri();181```182183```ts184// Copying fixtures and running one-off commands inside a container185const container = await new GenericContainer('postgres:16-alpine')186 .withEnvironment({ POSTGRES_PASSWORD: 'shop' })187 .withCopyFilesToContainer([188 { source: './tests/fixtures/seed.sql', target: '/docker-entrypoint-initdb.d/seed.sql' },189 ])190 .withExposedPorts(5432)191 .start();192193const { exitCode, output } = await container.exec(['psql', '-U', 'postgres', '-c', 'SELECT 1']);194expect(exitCode).toBe(0);195expect(output).toContain('1 row');196```197198## Best Practices199200- Raise the test framework timeout for `beforeAll` hooks that pull images (60-120 seconds); the first CI run downloads layers.201- Use module packages (`@testcontainers/postgresql`, `@testcontainers/kafka`, `@testcontainers/elasticsearch`) before reaching for `GenericContainer`; they encode correct wait strategies and credentials.202- In CI, pre-pull hot images (`docker pull postgres:16-alpine`) in a cached step to cut suite time.203- Keep integration tests in a separate script (`"test:integration": "vitest run --config vitest.integration.config.ts"`) so unit tests stay Docker-free and fast.204- Pass connection details via the same env vars production reads (`DATABASE_URL`, `REDIS_URL`); never add test-only config paths to the app.205- Log container output on failure with `container.logs()` streamed to the test reporter when diagnosing startup issues.206207## Anti-Patterns208209- `await sleep(3000)` after `start()` instead of a wait strategy - slow on good days, flaky on loaded CI runners.210- One shared, long-lived "test database" server that every developer and CI job mutates; state leaks make failures non-reproducible.211- Restarting the container between tests for isolation; truncate tables or roll back transactions instead and save minutes per suite.212- Mocking the repository layer in "integration" tests - the SQL is exactly the thing that needs testing.213- Using `:latest` tags or a different database engine than production.214- Disabling Ryuk (`TESTCONTAINERS_RYUK_DISABLED=true`) in CI to "fix" a permissions issue, then leaking containers until the runner dies; fix the Docker socket permissions instead.215216## When to Trigger This Skill217218- The user asks for integration tests against a real Postgres, MySQL, MongoDB, Redis, Kafka, RabbitMQ, Elasticsearch, or LocalStack instance.219- A repository imports `testcontainers` or `@testcontainers/*`, or contains a `docker-compose.test.yml`.220- Mock-heavy tests keep missing SQL syntax errors, migration drift, or serialization bugs that only a real engine catches.221- CI needs hermetic, parallel-safe integration tests without a provisioned shared database.222- Repository, DAO, or ORM code (Drizzle, Prisma, Knex, TypeORM) needs verification against the production database engine and real migrations.