Skip to content
Tutorials Center
My learning

Topics

Lesson 101 of 111 ยท Projects

Project: A Node.js API with a Database

Containerize a Node.js API with PostgreSQL: multi-stage Dockerfile, Compose, named volume, healthchecks and SQL migrations run as a one-off container.

In this project you will package a small Node.js API and run it next to a PostgreSQL database with Docker Compose. It is a to-do list service with four routes, and it is built the way a real service should be: a lean image that runs as a non-root user, a database whose data lives on a volume, healthchecks that control startup order, and schema migrations that run as a separate one-off container instead of being hidden inside the app.

Everything here was built and run on Docker 29 with Compose v5 and Node 24. The files are complete. Copy them into an empty folder and follow the steps in order.

TEXT
   curl / browser
        |  127.0.0.1:18151  (published, loopback only)
   +----v-----+
   |   api    |  Node.js, port 3000, user "node"
   +----+-----+
        |  default Compose network, host name "db"
   +----v-----+
   |    db    |  PostgreSQL 17, port 5432 (not published)
   +----+-----+
        |
   volume "pgdata"

The project layout

TEXT
todo-api/
  compose.yaml
  .env
  Dockerfile
  .dockerignore
  package.json
  package-lock.json
  migrations/
    001_create_todos.sql
  src/
    db.js
    migrate.js
    server.js

Step 1: The application

The API uses Node's built-in http module and one dependency, the pg PostgreSQL driver. That keeps the code short enough to read in one sitting. The module settings ("type": "module") let us use import syntax.

JSON
{
  "name": "todo-api",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "start": "node src/server.js",
    "migrate": "node src/migrate.js"
  },
  "dependencies": {
    "pg": "^8.13.0"
  }
}

A shared connection pool reads its address from the DATABASE_URL environment variable. The same image can therefore talk to any database, which is the idea behind Configuring Containers.

JavaScript
// src/db.js
import pg from "pg";

export const pool = new pg.Pool({
  connectionString: process.env.DATABASE_URL,
  max: 5,
});

The server answers GET /health, GET /todos, POST /todos and PATCH /todos/:id (which toggles done). Notice the last lines: the process handles SIGTERM, stops accepting connections, closes the pool and exits. That matters in a container, because docker stop sends exactly that signal (Signals, PID 1 and --init).

JavaScript
// src/server.js
import http from "node:http";
import { pool } from "./db.js";

function send(res, status, payload) {
  const body = JSON.stringify(payload);
  res.writeHead(status, { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) });
  res.end(body);
}

async function readJson(req) {
  let raw = "";
  for await (const chunk of req) {
    raw += chunk;
  }
  return raw ? JSON.parse(raw) : {};
}

const server = http.createServer(async (req, res) => {
  try {
    const url = new URL(req.url, "http://localhost");
    if (req.method === "GET" && url.pathname === "/health") {
      await pool.query("SELECT 1");
      return send(res, 200, { status: "ok" });
    }
    if (req.method === "GET" && url.pathname === "/todos") {
      const { rows } = await pool.query("SELECT id, title, done FROM todos ORDER BY id");
      return send(res, 200, rows);
    }
    if (req.method === "POST" && url.pathname === "/todos") {
      const { title } = await readJson(req);
      if (!title) {
        return send(res, 400, { error: "title is required" });
      }
      const { rows } = await pool.query(
        "INSERT INTO todos (title) VALUES ($1) RETURNING id, title, done",
        [title]
      );
      return send(res, 201, rows[0]);
    }
    const match = url.pathname.match(/^\/todos\/(\d+)$/);
    if (req.method === "PATCH" && match) {
      const { rows } = await pool.query(
        "UPDATE todos SET done = NOT done WHERE id = $1 RETURNING id, title, done",
        [match[1]]
      );
      return rows.length ? send(res, 200, rows[0]) : send(res, 404, { error: "not found" });
    }
    send(res, 404, { error: "not found" });
  } catch (err) {
    console.error("error:", err.message);
    send(res, 500, { error: "internal error" });
  }
});

const port = Number(process.env.PORT ?? 3000);
server.listen(port, "0.0.0.0", () => console.log(`todo-api listening on ${port}`));

function shutdown(signal) {
  console.log(`${signal} received, shutting down`);
  server.close(async () => {
    await pool.end();
    process.exit(0);
  });
}
process.on("SIGTERM", () => shutdown("SIGTERM"));
process.on("SIGINT", () => shutdown("SIGINT"));

The server listens on 0.0.0.0, not 127.0.0.1. Inside a container, 127.0.0.1 means "this container only", so published ports and other containers could never reach it (Publishing Ports).

Step 2: Migrations as plain SQL files

A migration is a numbered SQL file that changes the schema. A tiny runner applies every file that has not been applied yet and records its name in a schema_migrations table, each inside a transaction.

SQL
-- migrations/001_create_todos.sql
CREATE TABLE todos (
  id serial PRIMARY KEY,
  title text NOT NULL,
  done boolean NOT NULL DEFAULT false,
  created_at timestamptz NOT NULL DEFAULT now()
);
JavaScript
// src/migrate.js
import { readdir, readFile } from "node:fs/promises";
import { pool } from "./db.js";

const dir = new URL("../migrations/", import.meta.url);

await pool.query(
  "CREATE TABLE IF NOT EXISTS schema_migrations (name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())"
);

const done = new Set((await pool.query("SELECT name FROM schema_migrations")).rows.map((r) => r.name));
const files = (await readdir(dir)).filter((f) => f.endsWith(".sql")).sort();

for (const file of files) {
  if (done.has(file)) {
    console.log(`skip   ${file}`);
    continue;
  }
  const sql = await readFile(new URL(file, dir), "utf8");
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    await client.query(sql);
    await client.query("INSERT INTO schema_migrations (name) VALUES ($1)", [file]);
    await client.query("COMMIT");
    console.log(`apply  ${file}`);
  } catch (err) {
    await client.query("ROLLBACK");
    console.error(`failed ${file}: ${err.message}`);
    process.exitCode = 1;
    break;
  } finally {
    client.release();
  }
}

await pool.end();

Why a separate script and not "run migrations when the server starts"? With several API replicas, every one would race to migrate. A one-off command runs once, has its own exit code that a deploy script can check, and lets you decide when the schema changes. We will run it with docker compose run.

Step 3: The Dockerfile

The image needs the production dependencies, the source and the migrations, and nothing else. A two-stage build keeps the install step cached and separate. See Multi-Stage Builds and The Build Cache.

DOCKERFILE
FROM node:lts-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev

FROM node:lts-alpine
ENV NODE_ENV=production
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY package.json ./
COPY src ./src
COPY migrations ./migrations
USER node
EXPOSE 3000
CMD ["node", "src/server.js"]

Three details do real work here:

  • Lockfile first. COPY package.json package-lock.json happens before COPY src. Editing your code does not invalidate the npm ci layer, so most rebuilds skip the install entirely.
  • npm ci installs exactly what the lockfile says and fails if it disagrees with package.json. That makes the image reproducible. (Create the lockfile once with npm install.)
  • USER node. The official Node images ship a node user (uid 1000). Running as it means a compromised app does not own the container (Users and Permissions).

The .dockerignore keeps local clutter out of the build context (Build Context and .dockerignore):

TEXT
node_modules
.git
.env
compose.yaml
Dockerfile

Excluding .env is important: otherwise your database password would be copied into the image by a careless COPY . . later.

Step 4: Compose and configuration

Compose reads a .env file next to compose.yaml to fill ${...} placeholders:

INI
# .env  (do not commit; commit a .env.example with fake values)
POSTGRES_PASSWORD=change-me-locally
API_PORT=18151
YAML
# compose.yaml
name: tcd-b15-todo

services:
  api:
    build: .
    ports:
      - "127.0.0.1:${API_PORT:-3000}:3000"
    environment:
      DATABASE_URL: postgresql://todo:${POSTGRES_PASSWORD}@db:5432/todo
    depends_on:
      db:
        condition: service_healthy
    healthcheck:
      test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:3000/health').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"]
      interval: 5s
      timeout: 3s
      retries: 5
      start_period: 5s
    restart: unless-stopped

  db:
    image: postgres:17-alpine
    environment:
      POSTGRES_USER: todo
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: todo
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U todo -d todo"]
      interval: 5s
      timeout: 3s
      retries: 10
    restart: unless-stopped

volumes:
  pgdata:

Points worth understanding:

  • The host name in DATABASE_URL is db, the service name. Compose's default network gives every service a DNS name (Containers Talking to Each Other).
  • The database publishes no port. Only the API is reachable from your machine, and only on loopback.
  • The API's healthcheck uses Node itself, because the Alpine image has no curl (HEALTHCHECK). depends_on with service_healthy makes the API wait until pg_isready succeeds (Startup Order and Health).
  • pgdata is a named volume, so the data outlives the container (Volumes).

Step 5: Start the stack

Validate first, then build and start:

CONSOLE
$ docker compose config --quiet; echo "exit code: $?"
exit code: 0
$ docker compose up -d --build
 Image tcd-b15-todo-api Built
 Network tcd-b15-todo_default Created
 Volume tcd-b15-todo_pgdata Created
 Container tcd-b15-todo-db-1 Created
 Container tcd-b15-todo-api-1 Created
 Container tcd-b15-todo-db-1 Started
 Container tcd-b15-todo-db-1 Healthy
 Container tcd-b15-todo-api-1 Started

The database became healthy first, and only then did the API start. After a few seconds both report healthy:

CONSOLE
$ docker compose ps
NAME                 IMAGE                COMMAND                  SERVICE   CREATED          STATUS                    PORTS
tcd-b15-todo-api-1   tcd-b15-todo-api     "docker-entrypoint.sโ€ฆ"   api       18 seconds ago   Up 10 seconds (healthy)   127.0.0.1:18151->3000/tcp
tcd-b15-todo-db-1    postgres:17-alpine   "docker-entrypoint.sโ€ฆ"   db        19 seconds ago   Up 17 seconds (healthy)   5432/tcp

Step 6: The database has no tables yet

The stack is healthy, but we have not migrated. Ask for the list of to-dos:

CONSOLE
$ curl -s -w ' (status %{http_code})\n' http://127.0.0.1:18151/todos
{"error":"internal error"} (status 500)
$ docker compose logs --no-log-prefix api
todo-api listening on 3000
error: relation "todos" does not exist

This is a useful lesson in itself. The healthcheck passed because SELECT 1 works on an empty database, yet the application cannot do its job. A healthcheck proves a process is alive and can reach its dependency, not that the schema is right. The logs tell the real story (Logs and exec).

Step 7: Run the migrations

docker compose run --rm starts a new, temporary container from the api service definition, with the same image, environment and network, but a different command:

CONSOLE
$ docker compose run --rm api node src/migrate.js
apply  001_create_todos.sql
$ docker compose run --rm api node src/migrate.js
skip   001_create_todos.sql

Running it twice is safe: the second run finds the file in schema_migrations and skips it. Now the API works:

CONSOLE
$ curl -s -X POST -d '{"title":"learn Docker"}' http://127.0.0.1:18151/todos
{"id":1,"title":"learn Docker","done":false}
$ curl -s -X POST -d '{"title":"ship it"}' http://127.0.0.1:18151/todos
{"id":2,"title":"ship it","done":false}
$ curl -s -X PATCH http://127.0.0.1:18151/todos/1
{"id":1,"title":"learn Docker","done":true}
$ curl -s http://127.0.0.1:18151/todos
[{"id":1,"title":"learn Docker","done":true},{"id":2,"title":"ship it","done":false}]

The bookkeeping table is plain SQL, so you can look at it directly:

CONSOLE
$ docker compose exec db psql -U todo -c 'SELECT name FROM schema_migrations'
         name
----------------------
 001_create_todos.sql
(1 row)

Step 8: Ship a schema change

Add a second migration file:

SQL
-- migrations/002_add_priority.sql
ALTER TABLE todos ADD COLUMN priority integer NOT NULL DEFAULT 0;

The migration files are copied into the image, so rebuild and replace the API container, then run the runner:

CONSOLE
$ docker compose up -d --build api
$ docker compose run --rm api node src/migrate.js
skip   001_create_todos.sql
apply  002_add_priority.sql
$ docker compose exec db psql -U todo -c '\d todos'
                                       Table "public.todos"
   Column   |           Type           | Collation | Nullable |              Default
------------+--------------------------+-----------+----------+-----------------------------------
 id         | integer                  |           | not null | nextval('todos_id_seq'::regclass)
 title      | text                     |           | not null |
 done       | boolean                  |           | not null | false
 created_at | timestamp with time zone |           | not null | now()
 priority   | integer                  |           | not null | 0
Indexes:
    "todos_pkey" PRIMARY KEY, btree (id)

Only the new file was applied, and existing rows kept their data (they received the default 0). In a real deployment the order is: build the new image, run the migration container, then restart the app. Keep migrations backward compatible (add a column before the code uses it, remove it only after the code stops using it) so old and new versions can run side by side during the switch.

Step 9: Check the image and the process

CONSOLE
$ docker compose exec api id
uid=1000(node) gid=1000(node) groups=1000(node)
$ docker image ls tcd-b15-todo-api --format '{{.Repository}} {{.Size}}'
tcd-b15-todo-api 245MB

The process is not root. The image is about 245 MB, almost all of it the Node runtime and Alpine base; the pg driver and your code are tiny. Because the app handles SIGTERM, stopping is fast and clean:

CONSOLE
$ time docker compose stop api
 Container tcd-b15-todo-api-1 Stopping
 Container tcd-b15-todo-api-1 Stopped

real	0m1.5s
$ docker compose logs --no-log-prefix --tail 2 api
todo-api listening on 3000
SIGTERM received, shutting down

A program that ignores SIGTERM would be killed after the default 10-second grace period. Seeing your own "shutting down" message is the proof that signals reach your process.

Step 10: Prove the data survives

CONSOLE
$ docker compose down
$ docker compose up -d
$ curl -s http://127.0.0.1:18151/todos
[{"id":1,"title":"learn Docker","done":true},{"id":2,"title":"ship it","done":false}]

down removed both containers and the network, but the pgdata volume stayed, so the new database container found the old files. The schema_migrations table is in that data too, so no migration runs again. Wait for healthy in docker compose ps before sending requests, or add --wait to up.

docker compose down -v deletes the volume and all your data. Use it only when you want a fresh start, like the clean-up step below.

Clean up

CONSOLE
$ docker compose down -v --rmi local
 Volume tcd-b15-todo_pgdata Removed
 Image tcd-b15-todo-api:latest Removed
 Network tcd-b15-todo_default Removed

Where to take it next

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the Dockerfile copy package.json and package-lock.json before the src folder?

    Layers are cached in order. The dependency layer depends only on the two package files, so editing code later leaves it untouched and rebuilds are fast.
  2. 2. The API container is healthy, yet GET /todos returns a 500 error with relation "todos" does not exist. What happened?

    A healthcheck proves the process runs and reaches the database, not that the schema exists. The fix is to run the migration step, here with docker compose run --rm api node src/migrate.js.
  3. 3. What does docker compose run --rm api node src/migrate.js do?

    run creates a new container with the service's image, environment and networks. --rm deletes it when the command exits. (exec is the one that uses an existing container.)
  4. 4. Which statement about the pgdata volume is correct?

    Named volumes are independent of containers. down removes containers and networks but keeps volumes unless you add -v.
  5. 5. Why does the server listen on 0.0.0.0 instead of 127.0.0.1?

    Traffic from Docker's port forwarding or from another container arrives on the container's network interface, not on its loopback. Binding to all interfaces accepts it; the 127.0.0.1 in the Compose ports entry is what limits exposure on the host.

Summary

  • A multi-stage Dockerfile with the lockfile copied first gives reproducible, cache-friendly builds; USER node avoids running as root.
  • Compose wires the API and PostgreSQL together by service name, and depends_on with service_healthy controls the startup order.
  • Keep the database on a named volume and publish only the API, bound to 127.0.0.1.
  • Run schema migrations as a one-off container (docker compose run --rm), not inside the app's startup, and make them idempotent.
  • A passing healthcheck does not prove the application is correct; read the logs.
  • Handle SIGTERM so that docker stop finishes in a second instead of waiting for a kill.

Next: Project: A Python App with Redis