Testcontainers Docker PostgreSQL Integration
Spin up disposable PostgreSQL containers for integration tests with Testcontainers, waiting for readiness and reusing one container per suite.
Code
import { PostgreSqlContainer } from '@testcontainers/postgresql';
import { Pool } from 'pg';
import { afterAll, beforeAll, test } from 'vitest';
let container;
let pool: Pool;
beforeAll(async () => {
container = await new PostgreSqlContainer('postgres:16-alpine')
.withDatabase('app_test')
.withUsername('tester')
.withPassword('secret')
.withCommand(['postgres', '-c', 'fsync=off'])
.start();
pool = new Pool({ connectionString: container.getConnectionUri() });
await pool.query(`
CREATE TABLE invoices (
id SERIAL PRIMARY KEY,
total_cents INTEGER NOT NULL CHECK (total_cents >= 0)
)
`);
}, 120_000);
test('insert and read back within a real postgres engine', async () => {
const inserted = await pool.query(
'INSERT INTO invoices (total_cents) VALUES ($1) RETURNING id, total_cents',
[1999],
);
expect(inserted.rows[0].total_cents).toBe(1999);
const read = await pool.query('SELECT count(*)::int AS n FROM invoices');
expect(read.rows[0].n).toBe(1);
});
afterAll(async () => {
await pool?.end();
await container?.stop();
});How the snippet works
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. PostgreSqlContainer, Pool, afterAll, beforeAll, test are the only symbols borrowed from @testcontainers/postgresql — the coupling is explicit and narrow.
Caveats
@testcontainers/postgresql,pgandvitestmust be installed first — the snippet imports them directly.
Statements that matter
await container?.stop();
await pool?.end();
const read = await pool.query('SELECT count(*)::int AS n FROM invoices');
Interactive Tools for This Topic
Docker Run to Compose ConverterTransform docker run CLI commands with ports, environment variables, volumes, networks, and resource limits into clean compose.yaml service definitions.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.
FAQ
- Do I need to install anything before running this?
- Yes: `@testcontainers/postgresql`, `pg` and `vitest` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.