Database DevOps

The database is the part of production that must never be lost. A managed database (run by a cloud provider, such as RDS, Cloud SQL, DigitalOcean) handles…

Throughout this track we have deleted and recreated notes-api's app containers many times without trouble. The database is a different story. If the database is lost, every note the users wrote is lost with it, and no docker compose up brings them back.

Database DevOps is how you run an application's database in production safely: who manages it, how its structure changes during a deploy, how its data is backed up and restored, and how many connections it can serve. Picture a shop's cash book. The cashiers can take turns at any time, and the till can be swapped for a new one. But there is only one cash book: if that book is lost, every sale it recorded is gone. In this picture, the cashiers and the till are notes-api's app containers, which may be deleted and recreated. The cash book is the notes database in Postgres: it is the part that must never be lost.

Managed or self-hosted

Right now notes-api's Postgres runs as a container on web-1 (self-hosted, run by you), with its data in the named volume db-data. The other option is a managed database: Postgres run by a cloud provider (AWS RDS, DigitalOcean Managed Databases, Google Cloud SQL, Supabase, Neon). Your app just connects to its address.

Self-hosted on web-1 Managed
Daily backups you write the script and its cron schedule automatic, usually plus point-in-time recovery (restoring to any minute within the time backups are kept)
A spare server (standby) you set it up a checkbox, with automatic failover (moving to the spare server by itself)
Upgrades and patches you run them scheduled by the provider
When web-1 dies app and database die together the database keeps running elsewhere
Cost nothing extra a monthly fee, more than a container
Control full, every extension (an add-on feature for Postgres) and setting limited to what the provider offers

For an app with real users and a team without a DBA (a person whose job is managing databases), managed is usually the cheapest once you count your time. Self-hosted is still fine, as long as backups, restore drills (practice restores, covered below) and upgrades really get done. The sections below apply to both.

Migrations in the deploy pipeline

A database migration is a schema change (a change to the structure of the tables, such as adding a table or a column) written as a file in the repo. The file is reviewed and version-controlled (kept in the Git history) like code, then applied automatically during a deploy. In notes-api's pipeline, migrations run once, after the new image is pulled and before the new containers start:

docker compose pull app
docker compose run --rm app node migrate.js   # a one-off container with the new image
docker compose up -d                          # only then replace the app containers

In Laravel, the same step is php artisan migrate --force. In production Laravel asks for confirmation first, and a pipeline can't answer, so --force skips that question.

For a few seconds, old code runs on the new schema: the migration has finished, but the old containers haven't been replaced yet. If a migration renames the column content to body in one step, every SELECT content from the old code fails with column "content" does not exist until the new containers are up. That's why production migrations use the expand/contract pattern (first widen, then narrow):

  1. The first deploy only adds: a new body column, and the code writes to both content and body.
  2. A later deploy removes the old column, once no code uses it.

The full steps are in the Schema Migration Patterns lesson, Database track.

In CI, the test database is created fresh on every run: migrations run from zero, then a seeder (a script that fills in data) adds the same sample data every time. Because the data is always the same, a test that passes today also passes tomorrow. The result doesn't depend on what a previous run left behind.

Scheduled backups

This is notes-api's backup script and the cron schedule that runs it, the same as in the Lab:

#!/usr/bin/env bash
set -euo pipefail
cd /srv/notes-api
BACKUP_FILE="/var/backups/notes/notes-$(date +%F).sql.gz"
docker compose exec -T db pg_dump -U notes notes | gzip > "$BACKUP_FILE"
find /var/backups/notes -name 'notes-*.sql.gz' -mtime +7 -delete
# root's crontab: every day at 02:00
0 2 * * * /srv/notes-api/backup.sh >> /var/log/backup-notes.log 2>&1

This is the schedule of the first three backups, in the format the exercise uses:

Backup Time May be deleted after
1 Day 1 02:00 Day 8
2 Day 2 02:00 Day 9
3 Day 3 02:00 Day 10

A backup that only lives on web-1 is lost along with web-1's disk. Copy it somewhere else too, for example an object storage bucket (the Object Storage (S3/R2/GCS) lesson). How often to back up and how fast you must recover (RPO and RTO) is covered in the Backup & Recovery lesson, Database track.

Restore drill

A restore drill is a regular rehearsal of restoring a backup into a practice database, to prove the backup can be used. This is the drill for the latest backup, exactly as in the Lab:

$ docker compose exec -T db createdb -U notes notes_drill
$ gunzip -c /var/backups/notes/notes-2026-10-03.sql.gz | docker compose exec -T db psql -q -U notes -d notes_drill
$ docker compose exec -T db psql -U notes -d notes_drill -c "SELECT count(*) FROM notes;"
 count 
-------
  1358
(1 row)

$ docker compose exec -T db dropdb -U notes notes_drill

The order: createdb creates an empty database notes_drill, the backup is unpacked with gunzip -c and goes into it through psql, then the notes are counted. The result is 1,358 notes, the same as production when the backup was taken: this backup is proven to work. dropdb throws the practice database away again.

Now take the night of Day 4, at 02:00, when the db container is down for an upgrade. Imagine the backup script was written with only set -eu, without pipefail. Later that morning, that night's backup file is in its folder. Guess first: how big is it, and what was the script's exit code?

Without pipefail, a pipe's status is the status of its last command (the Shell Scripting Basics lesson). docker compose exec fails with service "db" is not running, but gzip still compresses the empty input without a problem. So the script continues and exits with exit code 0. The file is there, and it is 20 bytes. Nobody suspects anything, until the drill runs:

$ docker compose exec -T db psql -U notes -d notes_drill -c "SELECT count(*) FROM notes;"
ERROR:  relation "notes" does not exist
LINE 1: SELECT count(*) FROM notes;
                             ^

The restore "succeeded" without any message, because the backup was empty: no table was created, so the error only appears when the notes are counted. With set -euo pipefail, the script stops with exit code 1, the error message is written to the backup log, and monitoring can tell you. But only a drill proves the backup can really be restored.

Connection limits

Postgres limits the number of connections with max_connections, 100 by default. Each notes-api container has a pool (a set of connections used in turn), and node-postgres' Pool (node-postgres is the Postgres library for Node) opens up to 10 connections. The arithmetic is simple:

App containers Pool per container App connections + psql, backup, migration Total
1 10 10 3 13
3 10 30 3 33
10 10 100 3 103: over the limit

The notes user may use all 100 connections, because the official Postgres image creates POSTGRES_USER as a superuser (a user with full permissions). The 101st connection is refused, and the app logs Database connection failed: sorry, too many clients already. When you add replicas (more app containers), do the sum again: replicas × pool + other connections must stay under max_connections. If it doesn't fit, shrink the pool per container, or add PgBouncer (the Connection Pooling lesson, Database track). Some small managed databases have a limit far below 100, so check the number in the provider's dashboard.

The backup schedule in numbers

In the exercise, you calculate the schedule table above. generateBackupSchedule(config) takes { dbName, frequency, retention, startHour } and returns the first 3 backups. Each item looks like { database, time, deleteAfter }:

⚠️ What loses data or breaks a deploy

TL;DR: The database is the part of production that must never be lost. A managed database (run by a cloud provider, such as RDS, Cloud SQL, DigitalOcean) handles backups, a standby (a spare server) and upgrades for a monthly fee. Self-hosted (run by you) is free, but all of that becomes your job. A migration is a version-controlled schema change (a change to the table structure) applied automatically during a deploy, once, before the new containers start (node migrate.js, or php artisan migrate --force in Laravel). Use expand/contract (add the new part first, remove the old one in a later deploy), because old code briefly runs on the new schema. Seeding (filling in sample data) in CI gives tests the same data every time. Cron (the task scheduler) runs a daily backup at 02:00 (0 2 * * *) with pg_dump | gzip (write out the database, then compress it). The retention (how long backups are kept), here 7 days, is set with find -mtime +7 -delete. Write the script with set -euo pipefail (so it stops when a command fails, even inside a pipe), and keep a copy off the server. A restore drill (a practice restore) proves the backup: an empty backup (a 20-byte file) only shows up when you restore it. Connections = replicas (app containers) × pool (connections per container) + other connections, and must stay under max_connections (100 by default).

⚡ A cash book that must never be lost

Meaning: A database is like a shop's cash book: the cashiers and the till (the app containers) may change, but there is only one cash book (the database). App containers can be deleted and recreated at any time, the database can't. A managed database (run by a cloud provider, such as RDS, Cloud SQL, DigitalOcean) handles backups, a standby (a spare server) and upgrades for a monthly fee. Self-hosted (run by you) is free, but all of that becomes your job.

⚡ Migrations run once, before the new containers

Write:

docker compose pull app
docker compose run --rm app node migrate.js   # a one-off container with the new image
docker compose up -d                          # only then replace the app containers

Meaning: A migration is a version-controlled schema change (a change to the table structure) applied automatically during a deploy. Here it runs once, in a one-off container with the new image, before the app containers are replaced. Old code briefly runs on the new schema, so use expand/contract: add the new column first, remove the old one in a later deploy.

⚡ Scheduled backups

Write:

BACKUP_FILE="/var/backups/notes/notes-$(date +%F).sql.gz"
docker compose exec -T db pg_dump -U notes notes | gzip > "$BACKUP_FILE"
0 2 * * * /srv/notes-api/backup.sh >> /var/log/backup-notes.log 2>&1

Meaning: Every day at 02:00, cron (the task scheduler on Linux) runs backup.sh. pg_dump writes the database's contents as SQL, and gzip compresses it. backup.sh also runs find -mtime +7 -delete, which throws away backups older than 7 days. Keep a copy off web-1.

⚡ A restore drill proves the backup

Guess first: this backup script is written without pipefail (a bash setting that makes a pipe fail when one of its commands fails), and the db container is down at 02:00. How big is the backup file, and what is the script's exit code?

20 bytes, and exit code 0. pg_dump fails, but gzip still compresses the empty input, and a pipe's status is the status of its last command.

Meaning: A restore drill is practice: restoring a backup into a practice database. A file being there doesn't mean its contents are. Only restoring into a practice database proves the backup can be used.

What you will learn