Skip to content

reservix/docker-await-postgres

Repository files navigation

docker-await-postgres

buid buid version MIT License

Start postgres docker container and wait until it is truly ready.

This module is heavily inspired by ava-fixture-docker-db. But unlike the mentioned module, it is

  • test runner agnostic
  • will wait until postges is "truly" ready to accepts connections.

Especially, the later will help when writing integration tests.

Why

The official postgres container loads and executes SQL scripts to create an initial table layout when the container is started, followed by a reboot of the postgres server. This is a welcome feature and a best practice when using docker to host your database. Sadly, it makes it harder to use the image when writing integration tests for your database.

Usually, tests run fast and don't wait the µ-seconds until the postgres server has rebooted. This causes tests to randomly break and connection errors, because the postgres server will just kill all connections when it is rebooting.

Using the Docker API (via dockerode or similar) will only tell you if the container is ready, but not if services inside the container are ready (you can read more about this here: docker-library/postgres/#146).

docker-await-postgres will read the server logs and long poll until the postgres server is trulry ready. So that tests only run when the server is trurly ready to accept connections. Start postgres docker container and wait until it is truly ready.

Usage

import { Client } from 'pg';
import { startPostgresContainer } from 'docker-await-postgres';

// Start the container
const config = {
  user: 'admin',
  password: '12345',
  database: 'database',
  image: 'postgres',
};
const { stop, port } = await startPostgresContainer(config);

// Connect to the container
const client = new Client({
  host: 'localhost',
  port,
  ...config,
});
await client.connect();
const { rows } = await client.query('SELECT NOW()');
await client.end();

// Stop the container
await stop();

About

🐋 wait until postgres container is ready ... for real

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 3

  •  
  •  
  •