Module 2 · Persistence and the relational data model
2.1 PostgreSQL with Docker Compose
Describe a database server in compose.yaml, start it, connect with psql, and learn where the data actually lives.
Starting point
The app keeps issues in an array, and Lesson 1.5 showed that the data disappears on restart and leaks between tests. Docker works on your machine (lesson 0.2).
Outcome
caretaker/├── compose.yaml└── db/ └── init/ └── 01-create-test-database.sqlOne command starts PostgreSQL 18 with two databases: caretaker for development and caretaker_test for automated tests. You can open a SQL prompt (psql) inside the container, and you know why the data survives restarts.
The problem
We need a database server. Installing PostgreSQL directly on your machine works, but then everyone's version, settings and passwords differ, and removing it cleanly is awkward. We want a database that is described in a file in the repository, starts with one command, and is identical for every learner and every test run.
Build it
1. Describe the database in compose.yaml
Docker Compose reads a YAML file that lists services (containers) and how to run them. Create compose.yaml in the project folder:
services: db: image: postgres:18.7-alpine environment: POSTGRES_USER: caretaker POSTGRES_PASSWORD: caretaker_dev_password POSTGRES_DB: caretaker ports: - "5433:5432" volumes: - pgdata:/var/lib/postgresql - ./db/init:/docker-entrypoint-initdb.d:ro healthcheck: test: ["CMD-SHELL", "pg_isready -U caretaker -d caretaker"] interval: 2s timeout: 3s retries: 15 volumes: pgdata:Line by line:
dbis the service name. Other commands refer to it (docker compose exec db ...).image: postgres:18.7-alpineis the official PostgreSQL image, version 18.7, built on the small Alpine Linux base. Pinning the exact version means everyone runs the same server.- The three
POSTGRES_*variables are read by the image the first time it starts with an empty data folder. It creates the usercaretakerwith that password and an empty databasecaretaker. This password protects a local learning database only; never reuse it anywhere real. ports: "5433:5432"publishes the container's port 5432 (PostgreSQL's default) as port 5433 on your machine. We avoid 5432 on the host because many developers already run a PostgreSQL there.pgdata:/var/lib/postgresqlmounts a named volume into the container. The volume is storage that Docker manages outside the container, so the data survives when the container is removed and recreated. (PostgreSQL 18 images keep their data under/var/lib/postgresql; older guides mount/var/lib/postgresql/data, which is wrong for version 18.)./db/init:/docker-entrypoint-initdb.d:romounts ourdb/initfolder read-only. On the very first start, the image runs every.sqlfile in that folder.healthcheckrunspg_isreadyevery 2 seconds. Docker then knows when the server actually accepts connections, not just when the container process started.
2. Create the test database on first start
-- Runs once, when the data volume is empty.-- The development database "caretaker" is created from POSTGRES_DB.-- Automated tests use their own database so they can delete data freely.CREATE DATABASE caretaker_test;3. Start it
docker compose up -d --wait
Volume caretaker_pgdata Creating
Volume caretaker_pgdata Creating
Network caretaker_default Creating
Network caretaker_default Creating
Volume caretaker_pgdata Created
Volume caretaker_pgdata Created
Network caretaker_default Created
Network caretaker_default Created
Container caretaker-db-1 Creating
Container caretaker-db-1 Created
Container caretaker-db-1 Starting
Container caretaker-db-1 Started
Container caretaker-db-1 Waiting
Container caretaker-db-1 Healthy
upcreates and starts the services.-d("detached") runs them in the background and gives you the terminal back.--waitwaits until the health check reports healthy.
The first run downloads the image, so it can take a minute.
Run and inspect
List the running services:
docker compose ps
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
caretaker-db-1 postgres:18.7-alpine "docker-entrypoint.s…" db 2 seconds ago Up 2 seconds (healthy) 0.0.0.0:5433->5432/tcp, [::]:5433->5432/tcp
0.0.0.0:5433->5432/tcp confirms the port mapping. Read the server's log to see what happened on first start:
docker compose logs db | grep -E "initdb|CREATE DATABASE|ready to accept"
db-1 | initdb: warning: enabling "trust" authentication for local connections
db-1 | initdb: hint: You can change this by editing pg_hba.conf or using the option -A, or --auth-local and --auth-host, the next time you run initdb.
db-1 | 2026-11-28 14:39:16.880 UTC [46] LOG: database system is ready to accept connections
db-1 | CREATE DATABASE
db-1 | /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/01-create-test-database.sql
db-1 | CREATE DATABASE
db-1 | 2026-11-28 14:39:17.178 UTC [1] LOG: database system is ready to accept connections
The image ran our init script (CREATE DATABASE) and then reported it is ready.
Open a SQL prompt
psql is PostgreSQL's command-line client. It is already installed inside the container, so we run it there with docker compose exec:
docker compose exec db psql -U caretaker -d caretaker
You get a prompt like caretaker=#. Lines that start with a backslash are psql commands; everything else is SQL that you end with ;. Type \q to quit. In this course, SQL blocks labelled In psql are meant to be typed or pasted at this prompt. Try one:
docker compose exec db psql -U caretaker caretaker, then paste the SQL.SELECT version();
version
-----------------------------------------------------------------------------------------------
PostgreSQL 18.7 on aarch64-unknown-linux-musl, compiled by gcc (Alpine 15.2.0) 15.2.0, 64-bit
(1 row)List the databases with \l (we add -c here to run a single command without opening the prompt):
docker compose exec db psql -U caretaker -d caretaker -c '\l'
List of databases
Name | Owner | Encoding | Locale Provider | Collate | Ctype | Locale | ICU Rules | Access privileges
----------------+-----------+----------+-----------------+------------+------------+--------+-----------+-------------------------
caretaker | caretaker | UTF8 | libc | en_US.utf8 | en_US.utf8 | | |
caretaker_test | caretaker | UTF8 | libc | en_US.utf8 | en_US.utf8 | | |
postgres | caretaker | UTF8 | libc | en_US.utf8 | en_US.utf8 | | |
template0 | caretaker | UTF8 | libc | en_US.utf8 | en_US.utf8 | | | =c/caretaker +
| | | | | | | | caretaker=CTc/caretaker
template1 | caretaker | UTF8 | libc | en_US.utf8 | en_US.utf8 | | | =c/caretaker +
| | | | | | | | caretaker=CTc/caretaker
(5 rows)
Both databases exist. The postgres, template0 and template1 databases belong to PostgreSQL itself.
Experiment
Where does the data live? Create a small table, then destroy the container and start a new one.
docker compose exec db psql -U caretaker caretaker, then paste the SQL.CREATE TABLE scratch_note (body text);INSERT INTO scratch_note VALUES ('still here?');
CREATE TABLE
INSERT 0 1docker compose down stops and removes the container:
docker compose down
Container caretaker-db-1 Stopping
Container caretaker-db-1 Stopped
Container caretaker-db-1 Removing
Container caretaker-db-1 Removed
Network caretaker_default Removing
Network caretaker_default Removed
docker compose up creates a brand new container, will scratch_note still exist?docker compose up -d --wait
Network caretaker_default Creating
Network caretaker_default Creating
Network caretaker_default Created
Network caretaker_default Created
Container caretaker-db-1 Creating
Container caretaker-db-1 Created
Container caretaker-db-1 Starting
Container caretaker-db-1 Started
Container caretaker-db-1 Waiting
Container caretaker-db-1 Healthy
docker compose exec db psql -U caretaker caretaker, then paste the SQL.SELECT * FROM scratch_note;
body
-------------
still here?
(1 row)Reveal Why it survived
The container is disposable, but the data folder is the pgdata volume, which down does not touch. docker compose down -v also deletes volumes; we use that later when we want a truly fresh database. The init script did not run again, because the volume was not empty.
Clean up the experiment:
docker compose exec db psql -U caretaker caretaker, then paste the SQL.DROP TABLE scratch_note;
DROP TABLECheckpoint
docker compose ps
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
caretaker-db-1 postgres:18.7-alpine "docker-entrypoint.s…" db 3 seconds ago Up 2 seconds (healthy) 0.0.0.0:5433->5432/tcp, [::]:5433->5432/tcp
Commit the new files:
git add -A
git commit -m "Run PostgreSQL with Docker Compose"
[main d229092] Run PostgreSQL with Docker Compose
2 files changed, 24 insertions(+)
create mode 100644 compose.yaml
create mode 100644 db/init/01-create-test-database.sql
Symptom Bind for 0.0.0.0:5433 failed: port is already allocated
Something else listens on 5433. Find it with lsof -i :5433. Either stop it or change the left-hand side of the port mapping (for example "5434:5432") and use that port everywhere the course says 5433.
Symptom caretaker_test is missing from \l
The init script only runs when the volume is empty. If you started the database before creating db/init/01-create-test-database.sql, recreate the volume: docker compose down -v (this deletes all data in it), then docker compose up -d --wait.
Symptom Cannot connect to the Docker daemon
Docker Desktop is not running. Start it and wait for the whale icon to settle.
Recap and next step
compose.yaml describes the database server: image version, credentials, port and storage. The container is disposable; the named volume holds the data. The init folder creates the test database once. docker compose exec db psql gives you a SQL prompt inside the container.
The database is empty. Next we design its first tables, and let PostgreSQL enforce the rules that our JavaScript validation only hoped for.
Open the checkpoint files for lesson 2.1 (separate page; only files from this lesson and earlier)