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 startspostgres:18, waits for it to accept connections, and passes the connection string to your tests throughenv.
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:
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
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_testcreates an empty database calledapp_testwhen the server first starts.POSTGRES_HOST_AUTH_METHOD=trustlets 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:5432publishes the port on your loopback interface only. Never usetrustfor 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.
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:18The 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:
export DATABASE_URL=postgres://postgres@localhost:5432/app_testCheck it worked
Ask the server whether it accepts connections:
docker exec pg-ci-demo pg_isready -U postgres -d app_testIt prints /var/run/postgresql:5432 - accepting connections. Then connect from Node.js the way your tests will:
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.
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()
);
SQLNow 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:
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:
npm run migrate
npm run migrateThe 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:
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);
}
JScreateAccount 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
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.
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;
}
JSNow the tests. Two of them create the same email on purpose: they only both pass because the first one's row is rolled back.
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
BEGINandCOMMITbreaks out of the test transaction. For those functions, have the code useSAVEPOINTwhen it is handed a connection that is already in a transaction, or test them against a database you recreate per run. node --testruns 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:
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:
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
YAMLWhat each part does:
services.postgresis the label for the container.image: postgres:18follows the newest 18.x release; pin a full tag such aspostgres:18.7if you want every run on the same minor version, and update it deliberately.envunder the service is passed to the container, exactly like-ein your localdocker run.trustis 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, setPOSTGRES_PASSWORDfrom a repository secret instead and put it inDATABASE_URLthe same way.ports: 5432:5432publishes the container's port on the runner. The job's steps run on the runner itself, so they reach the database atlocalhost:5432.optionsare extradocker createflags. The--health-*flags give the container a health check that runspg_isreadyevery 2 seconds. The runner waits until the container reports healthy before it starts the steps, sonpm run migratenever 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_URLat 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 migratecomes beforenpm testbecause 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:
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_testService 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.yamlfor 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 (--waitand health checks in the Compose file) and a finaldocker compose downstep. - 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-latestormacos-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):
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:
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; donenpm ci
npm run migrate
npm testnpm 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:
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):
git remote add origin git@github.com:YOUR-USER/YOUR-REPO.git
git push -u origin mainCheck 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:
docker rm -f pg-ci-demoTroubleshooting
ECONNREFUSED 127.0.0.1:5432innpm run migrateon GitHub: the service has noportsmapping, or the job runs in acontainer:and should usepostgresas the host instead oflocalhost.relation "accounts" does not existin the tests: thenpm run migratestep is missing, comes afternpm test, or points at a differentDATABASE_URL.- The job fails in its container set-up with an unhealthy
postgresservice: run the samepg_isreadycommand in your local container. A typo inPOSTGRES_DBmakespg_isready -d app_testfail 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
BEGINandROLLBACKin 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.
Related tutorials
- How to Run Node.js Tests Automatically with GitHub ActionsYou will write tests with Node.js's built-in test runner, run them on every push and pull request with a GitHub Actions workflow that caches npm downloads and tries two Node.js versions, and check the workflow file locally before you push it.
- How to Install PostgreSQL 18 on Ubuntu 26.04 and Create Your First DatabaseYou will install PostgreSQL 18 from the official PostgreSQL apt repository, create a database and a user for your app, and connect to it with a password.
- Understand PostgreSQL transactions and isolation levelsYou will race two psql sessions against each other in PostgreSQL 18 to cause a lost update, a non-repeatable read, write skew and a deadlock, then fix each one with row locks, the right isolation level, a retry loop, savepoints and lock timeouts.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials