Skip to main content

CI/CD and automation · Intermediate · 17 min

Run integration tests against PostgreSQL in GitHub Actions with service containers

By Padding · Updated 18 Nov 2026
GitHub Actions (ubuntu-latest) · Debian (node:26 image) · Node.js 26.13.1 · PostgreSQL 18 · pg 8.23.1

You will have Node.js integration tests that run against a real PostgreSQL 18 database, locally and in a GitHub Actions job that starts PostgreSQL as a service container, waits for its health check, runs your migrations and rolls back every test.

On this page

Unit tests with a fake database tell you that your code calls query with the SQL you expected. They do not tell you that the SQL works. A unique index, a CHECK constraint, a foreign key or a migration that forgot a column only shows up when a real PostgreSQL server reads it. Integration tests close that gap: they run your code against the same database engine you use in production.

The usual objection is that integration tests are slow and leave a mess behind. This tutorial deals with both. You will build a small wallet module (accounts and prepaid top-ups, in minor units such as kobo or cents) with three parts that make database tests dependable:

  • A migration script, so every run starts from the same schema.
  • A transaction per test that is always rolled back, so tests never see each other's rows and the database stays empty.
  • A GitHub Actions job with a services: block that starts postgres:18, waits for it to accept connections, and passes the connection string to your tests through env.

It builds on /tutorials/run-node-tests-in-github-actions, which covers node:test, npm ci and the basic workflow file.

Step 1 · Create the project

Make a throwaway project folder, turn on ES modules and install the PostgreSQL client for Node.js, pg, at a fixed version:

Bash
mkdir -p ~/pg-ci-demo
cd ~/pg-ci-demo
git init -b main
npm init -y
npm pkg set type=module
npm install --save-exact pg@8.23.1
mkdir migrations scripts src test

--save-exact writes 8.23.1 into package.json rather than ^8.23.1, and npm install creates package-lock.json, which npm ci needs in the workflow.

Check it worked

Bash
npm ls pg
node -p "require('./package.json').type"

npm ls prints pg@8.23.1 under the project name, and the second command prints module.

Step 2 · Start PostgreSQL 18 on your computer

You want the same major version locally as in CI. The quickest way is the official postgres:18 image. Two settings matter here:

  • POSTGRES_DB=app_test creates an empty database called app_test when the server first starts.
  • POSTGRES_HOST_AUTH_METHOD=trust lets any client connect without a password. That is acceptable only for a throwaway test database that nobody else can reach, which is why -p 127.0.0.1:5432:5432 publishes the port on your loopback interface only. Never use trust for a database that holds real data.

If something already listens on port 5432 (a PostgreSQL you installed earlier, for example), change the left-hand number to 5433 here and in the connection string below.

Bash
docker run -d --name pg-ci-demo \
  -e POSTGRES_DB=app_test \
  -e POSTGRES_HOST_AUTH_METHOD=trust \
  -p 127.0.0.1:5432:5432 \
  postgres:18

The first docker run downloads the image, which is large enough to notice on a prepaid mobile bundle. Pull it once on a fixed connection and every later start is local. In CI, GitHub's runner downloads it, not you.

Your code and tests read the connection string from one environment variable, DATABASE_URL. Set it in the terminal you will run the tests from:

Bash
export DATABASE_URL=postgres://postgres@localhost:5432/app_test

Check it worked

Ask the server whether it accepts connections:

Bash
docker exec pg-ci-demo pg_isready -U postgres -d app_test

It prints /var/run/postgresql:5432 - accepting connections. Then connect from Node.js the way your tests will:

Bash
node --input-type=module -e "
import pg from 'pg';
const client = new pg.Client({ connectionString: process.env.DATABASE_URL });
await client.connect();
const { rows } = await client.query('SHOW server_version');
console.log('connected to PostgreSQL', rows[0].server_version);
await client.end();
"

The line starts with connected to PostgreSQL 18.. An error such as ECONNREFUSED means the server is not up yet or the port is different; wait a few seconds and check docker ps.

Step 3 · Write migrations and a migration script

Tests need the schema to exist before they run, and CI must build that schema the same way production does. Keep the schema in numbered SQL files and apply them with a short script that records what it has applied.

Bash
cat > migrations/001_create_accounts.sql <<'SQL'
CREATE TABLE accounts (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email      text NOT NULL UNIQUE,
  created_at timestamptz NOT NULL DEFAULT now()
);
SQL

cat > migrations/002_create_top_ups.sql <<'SQL'
CREATE TABLE top_ups (
  id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  account_id   bigint NOT NULL REFERENCES accounts (id),
  amount_minor integer NOT NULL CHECK (amount_minor > 0),
  created_at   timestamptz NOT NULL DEFAULT now()
);
SQL

Now the runner. It applies each file that is not yet listed in schema_migrations, in name order, inside its own transaction, so a broken migration leaves nothing half-applied:

Bash
cat > scripts/migrate.mjs <<'JS'
import { readdir, readFile } from 'node:fs/promises';
import pg from 'pg';

if (!process.env.DATABASE_URL) {
  throw new Error('Set DATABASE_URL before running migrations');
}

const dir = new URL('../migrations/', import.meta.url);
const client = new pg.Client({ connectionString: process.env.DATABASE_URL });
await client.connect();

try {
  await client.query(`CREATE TABLE IF NOT EXISTS schema_migrations (
    name       text PRIMARY KEY,
    applied_at timestamptz NOT NULL DEFAULT now()
  )`);
  const { rows } = await client.query('SELECT name FROM schema_migrations');
  const done = new Set(rows.map((row) => row.name));
  const files = (await readdir(dir)).filter((f) => f.endsWith('.sql')).sort();

  let applied = 0;
  for (const file of files) {
    if (done.has(file)) continue;
    const sql = await readFile(new URL(file, dir), 'utf8');
    await client.query('BEGIN');
    try {
      await client.query(sql);
      await client.query('INSERT INTO schema_migrations (name) VALUES ($1)', [file]);
      await client.query('COMMIT');
    } catch (err) {
      await client.query('ROLLBACK');
      throw new Error(`${file} failed: ${err.message}`);
    }
    console.log(`applied ${file}`);
    applied += 1;
  }
  console.log(applied ? `${applied} migration(s) applied` : 'database is up to date');
} finally {
  await client.end();
}
JS

npm pkg set scripts.migrate="node scripts/migrate.mjs"

PostgreSQL can run CREATE TABLE inside a transaction, which is what makes the BEGIN and ROLLBACK around each file useful. If you already use a migration tool (node-pg-migrate, Prisma, Flyway, Atlas), keep it and call it from the migrate script instead. The workflow only needs one command that brings an empty database up to date.

Check it worked

Run it twice:

Bash
npm run migrate
npm run migrate

The first run prints applied 001_create_accounts.sql, applied 002_create_top_ups.sql and 2 migration(s) applied. The second prints database is up to date, because both names are now in schema_migrations. That second result is what you want in CI too: the script is safe to run on every job.

Step 4 · Write the code under test

The wallet functions take the database connection as their first argument instead of creating their own. That one choice is what lets each test hand in a connection that sits inside a transaction:

Bash
cat > src/wallet.mjs <<'JS'
// db is anything with a pg-style query(text, values) method:
// a Pool in the app, a single client inside a transaction in tests.

export async function createAccount(db, email) {
  const { rows } = await db.query(
    'INSERT INTO accounts (email) VALUES (lower($1)) RETURNING id, email',
    [email],
  );
  return rows[0];
}

export async function topUp(db, accountId, amountMinor) {
  await db.query(
    'INSERT INTO top_ups (account_id, amount_minor) VALUES ($1, $2)',
    [accountId, amountMinor],
  );
}

export async function balance(db, accountId) {
  const { rows } = await db.query(
    'SELECT COALESCE(SUM(amount_minor), 0)::bigint AS total FROM top_ups WHERE account_id = $1',
    [accountId],
  );
  // pg returns bigint as a string so large values are not rounded.
  return Number(rows[0].total);
}
JS

createAccount lower-cases the email in SQL, so the UNIQUE constraint on email also catches Ada@Example.com against ada@example.com. amount_minor keeps money as whole numbers (250000 kobo is 2,500 naira), which avoids rounding errors in floating point.

Check it worked

Bash
node --check src/wallet.mjs && echo "wallet.mjs parses"

It prints wallet.mjs parses. The real check is the tests in the next step.

Step 5 · Give every test its own transaction

Here is the isolation trick. Before each test, take one connection from a pool and run BEGIN. The test does whatever it likes through that connection. After the test, run ROLLBACK and give the connection back. Nothing a test writes is ever committed, so the next test starts from the same empty tables, and you never write cleanup code.

Bash
cat > test/db.mjs <<'JS'
import { beforeEach, afterEach, after } from 'node:test';
import pg from 'pg';

// Call once at the top of a test file. Each test then gets ctx.db,
// a connection inside a transaction that is rolled back afterwards.
export function useTestTransaction() {
  const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 2 });
  const ctx = {};

  beforeEach(async () => {
    ctx.db = await pool.connect();
    await ctx.db.query('BEGIN');
  });

  afterEach(async () => {
    await ctx.db.query('ROLLBACK');
    ctx.db.release();
  });

  after(() => pool.end());

  return ctx;
}
JS

Now the tests. Two of them create the same email on purpose: they only both pass because the first one's row is rolled back.

Bash
cat > test/wallet.test.mjs <<'JS'
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { useTestTransaction } from './db.mjs';
import { createAccount, topUp, balance } from '../src/wallet.mjs';

const ctx = useTestTransaction();

test('each test starts with no accounts', async () => {
  const { rows } = await ctx.db.query('SELECT count(*)::int AS n FROM accounts');
  assert.equal(rows[0].n, 0);
});

test('adds up the top-ups for one account', async () => {
  const account = await createAccount(ctx.db, 'Ada@Example.com');
  await topUp(ctx.db, account.id, 50000);
  await topUp(ctx.db, account.id, 200000);
  assert.equal(account.email, 'ada@example.com');
  assert.equal(await balance(ctx.db, account.id), 250000);
});

test('refuses a second account with the same email in another case', async () => {
  await createAccount(ctx.db, 'ada@example.com');
  // 23505 is PostgreSQL's unique_violation
  await assert.rejects(createAccount(ctx.db, 'ADA@example.com'), { code: '23505' });
});

test('refuses a top-up of zero', async () => {
  const account = await createAccount(ctx.db, 'ada@example.com');
  // 23514 is PostgreSQL's check_violation
  await assert.rejects(topUp(ctx.db, account.id, 0), { code: '23514' });
});
JS

npm pkg set scripts.test="node --test test/*.test.mjs"

The test script names the test files explicitly. Without arguments, node --test also treats every file in a test folder as a test file, which would include the db.mjs helper.

The last two tests are the ones a mocked database cannot give you: they prove that the constraints in your migrations exist and behave as you expect. Checking code rather than the message keeps them stable across PostgreSQL versions and languages.

Two limits of this pattern are worth knowing:

  • Code that runs its own BEGIN and COMMIT breaks out of the test transaction. For those functions, have the code use SAVEPOINT when it is handed a connection that is already in a transaction, or test them against a database you recreate per run.
  • node --test runs separate test files in parallel. Two open transactions inserting the same unique value make the second one wait until the first rolls back, so use different sample data in different files to keep them from queuing.

Check it worked

Run the suite twice in a row, then count what is left in the table:

Bash
npm test
npm test
node --input-type=module -e "
import pg from 'pg';
const client = new pg.Client({ connectionString: process.env.DATABASE_URL });
await client.connect();
const { rows } = await client.query('SELECT count(*)::int AS n FROM accounts');
console.log('accounts left behind:', rows[0].n);
await client.end();
"

Both runs end with tests 4, pass 4 and fail 0, and the last line reads accounts left behind: 0. Change 50000 to 5000 in the test file and run npm test again to see a failure that names the expected and actual balance, then change it back.

Step 6 · Add a PostgreSQL service container to the workflow

A service container is a Docker container that GitHub Actions starts for one job, before the first step, and removes when the job ends. You describe it under services:; the runner handles pulling, starting, networking and clean-up.

Create .github/workflows/integration.yml:

Bash
mkdir -p .github/workflows
cat > .github/workflows/integration.yml <<'YAML'
name: Integration tests

on:
  push:
    branches: [main]
  pull_request:

permissions:
  contents: read

concurrency:
  group: integration-${{ github.ref }}
  cancel-in-progress: true

jobs:
  integration:
    # Service containers need a Linux runner.
    runs-on: ubuntu-latest
    timeout-minutes: 10

    services:
      postgres:
        image: postgres:18
        env:
          POSTGRES_DB: app_test
          POSTGRES_HOST_AUTH_METHOD: trust
        ports:
          - 5432:5432
        options: >-
          --health-cmd "pg_isready -U postgres -d app_test"
          --health-interval 2s
          --health-timeout 5s
          --health-retries 30

    env:
      DATABASE_URL: postgres://postgres@localhost:5432/app_test

    steps:
      - uses: actions/checkout@v7

      - uses: actions/setup-node@v7
        with:
          node-version: 26
          cache: npm

      - run: npm ci
      - run: npm run migrate
      - run: npm test
YAML

What each part does:

  • services.postgres is the label for the container. image: postgres:18 follows the newest 18.x release; pin a full tag such as postgres:18.7 if you want every run on the same minor version, and update it deliberately.
  • env under the service is passed to the container, exactly like -e in your local docker run. trust is safe here because the database only lives for this job and nothing outside the runner can reach it. On a self-hosted runner that other people or jobs share, set POSTGRES_PASSWORD from a repository secret instead and put it in DATABASE_URL the same way.
  • ports: 5432:5432 publishes the container's port on the runner. The job's steps run on the runner itself, so they reach the database at localhost:5432.
  • options are extra docker create flags. The --health-* flags give the container a health check that runs pg_isready every 2 seconds. The runner waits until the container reports healthy before it starts the steps, so npm run migrate never races a database that is still starting. Without a health check, the first step can run before PostgreSQL accepts connections and fail at random.
  • env.DATABASE_URL at job level is visible to every step, so the migration script and the tests read the same value they read on your computer. Nothing in the code changes between local and CI.
  • npm run migrate comes before npm test because the service starts with an empty database every time.

Run the job inside a container instead

If your job already runs in a container (container: node:26), the steps and the service share a Docker network. You then drop ports and connect by the service label as the host name:

YAML
jobs:
  integration:
    runs-on: ubuntu-latest
    container: node:26
    services:
      postgres:
        image: postgres:18
        env:
          POSTGRES_DB: app_test
          POSTGRES_HOST_AUTH_METHOD: trust
        options: >-
          --health-cmd "pg_isready -U postgres -d app_test"
          --health-interval 2s
          --health-timeout 5s
          --health-retries 30
    env:
      DATABASE_URL: postgres://postgres@postgres:5432/app_test

Service containers or Docker Compose

You can also run docker compose up --wait in a step. --wait blocks until the Compose services are running and healthy. Choose between the two like this:

  • Use services: when your dependencies are prebuilt images (PostgreSQL, Redis, a mail catcher). The runner starts them before your steps, waits on health checks, shows their logs in the job and removes them afterwards, with no extra steps.
  • Use Compose when you already maintain a compose.yaml for local development and want CI to use the same file, or when a dependency must be built from a Dockerfile in your repository or needs config files mounted from the checkout. You then own the waiting (--wait and health checks in the Compose file) and a final docker compose down step.
  • Either way the job needs Docker, which in practice means a Linux runner. GitHub-hosted service containers only work on Ubuntu runners, not on windows-latest or macos-latest, and a self-hosted runner must be Linux with Docker installed. Service containers also cannot be declared inside a composite action; put them in the workflow job.

Check it worked

Check the workflow file with actionlint (download a release as shown in /tutorials/github-actions-first-workflow):

Bash
actionlint
echo "actionlint exit code: $?"

No findings and exit code 0 mean the syntax, the services keys and the expressions are valid. Then run the exact sequence the job will run, against a fresh, empty database, so you know CI starts from nothing:

Bash
docker rm -f pg-ci-demo
docker run -d --name pg-ci-demo -e POSTGRES_DB=app_test -e POSTGRES_HOST_AUTH_METHOD=trust -p 127.0.0.1:5432:5432 postgres:18
until docker exec pg-ci-demo pg_isready -U postgres -d app_test; do sleep 1; done
Bash
npm ci
npm run migrate
npm test

npm ci reinstalls from the lock file, the migration prints 2 migration(s) applied, and the tests pass. If this works on an empty database, the job on GitHub has everything it needs.

Step 7 · Push and read the job log

Commit the project. Keep node_modules out of the repository:

Bash
printf 'node_modules\n' > .gitignore
git add .
git commit -m "Add wallet module, PostgreSQL integration tests and CI workflow"

Push it to your repository (replace the remote with your own):

Bash
git remote add origin git@github.com:YOUR-USER/YOUR-REPO.git
git push -u origin main

Check it worked

Open the repository's Actions tab and the Integration tests run. The job log starts with a section named something like Initialize containers, where the runner pulls postgres:18, starts it and waits for it to become healthy. Then come your steps: checkout, setup Node, npm ci, npm run migrate printing 2 migration(s) applied, and npm test with pass 4. At the end, a matching Stop containers section removes the database. With the GitHub CLI, gh run watch shows the same progress in the terminal.

When you are done with the local database, remove it:

Bash
docker rm -f pg-ci-demo

Troubleshooting

  • ECONNREFUSED 127.0.0.1:5432 in npm run migrate on GitHub: the service has no ports mapping, or the job runs in a container: and should use postgres as the host instead of localhost.
  • relation "accounts" does not exist in the tests: the npm run migrate step is missing, comes after npm test, or points at a different DATABASE_URL.
  • The job fails in its container set-up with an unhealthy postgres service: run the same pg_isready command in your local container. A typo in POSTGRES_DB makes pg_isready -d app_test fail forever.
  • The tests pass locally and fail in CI with a version-specific error: check that your local container and the service use the same tag (postgres:18), and pin a full tag in both if the minor version matters.

Next steps

  • Make the workflow faster by caching more than npm downloads: /tutorials/cache-dependencies-and-build-outputs-in-github-actions.
  • Learn what the BEGIN and ROLLBACK in your tests are doing, and what isolation levels change: /tutorials/understand-postgresql-transactions-and-isolation-levels.
  • Grow the migration habit into a full schema-change process: /tutorials/change-the-clinic-schema-safely-with-versioned-migrations.
  • Run PostgreSQL 18 on a server rather than in Docker: /tutorials/install-postgresql-18-on-ubuntu-26-04.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.