DevOps Kit Lessons Lesson 4 of 18

Checking your sign-in…

🔒

This lesson is in Phase 1 — ₹399, one-time

Pay once with UPI, card or netbanking. Keep it forever. Your progress saves, so you can stop and come back.

← Back to all lessons

PostgreSQL Lab — Main Database, Standby, Failover

Phase 1 · The Data Tier

What this is and why it matters

PostgreSQL is the main record book. It is a record store that keeps real records in tables and keeps them safe.

Think of it like a shop's big record book.

  • Each page is a table.
  • Each line on a page is one row: one order, with its number, its item, and its price.
  • The shop writes every new order in the book.
  • If the book is lost, every order is lost.

In real systems, the failure that hurts most is the main record store dying and taking every record with it.

This lab stops that from being the end of the story. You run two copies on your own computer: a main one and a standby copy that follows it live. You write fake orders into the main one, watch them appear on the standby, then kill the main one and promote the standby so work can continue. The last part shows Patroni — a watcher that does the promotion for you, by itself.

One idea per line, in order:

  • A record store keeps records in tables.
  • A table is a grid of rows and columns, like a spreadsheet page.
  • A row is one record in a table. Example: one order.
  • A column is one kind of detail. Example: the item name.
  • The main copy is called the primary. It takes writes.
  • A write is adding or changing a record.
  • The standby copy is called the replica. It takes reads only.
  • A read is asking for a record without changing it.
  • The replica copies every change from the primary, live.
  • Failover is the standby taking over as the new primary.

All data in this lab is fake: made-up orders, made-up names, made-up prices.

Your level in PostgreSQL
✓ Step 1 · Beginner→✓ Step 2 · Intermediate→✓ Step 3 · Advanced ← You are here
After this lesson you can: Recover a PostgreSQL database after killing it on purpose.
You have finished this topic’s ladder.
Advanced challenge: Database will not restart after a crash — remove the stuck lock file (postmaster.pid), start it, check it answers. — try it in PostgreSQL.

Test status

Syntax-checked only (20 November 2026). The compose file, the SQL file and the shell script were checked for correct syntax. This lab was not run end-to-end on this machine, because this machine has no Docker. Follow it on your own machine with Docker, and if a step fails, read the error first — that is the real skill.

v2 (20 November 2026): added the chmod step in Part 1, Step 1. The setup file must be readable by the record store's own user, or the main store fails to start. Still syntax-checked only, not run end to end.

What this lab is

You will run two PostgreSQL record stores on your own machine: a main one (primary) and a standby copy (replica). You will write fake orders into the main one, watch them appear on the standby, then kill the main one and promote the standby so work can continue. The last part shows Patroni — a watcher that does the promotion for you.

What you need first

  • Docker running. Lesson 0 shows how to install it and check it.
  • The files in the folder phase1/postgresql-lab/ — verified on disk: docker-compose.yml, 01-replicator.sql, replica-entrypoint.sh, plus the folder phase1/postgresql-lab/patroni/. The patroni/ folder is used only in the last part. It holds Dockerfile, docker-compose.yml, patroni-1.yml, and patroni-2.yml, all verified on disk.
  • Do Lesson 0 first if you have not. Do the Kafka lab first if you are following the phase order.

Words you need, before you use them

  • PostgreSQL. The record store used in this lab. People often shorten its name to Postgres. The image name is postgres:16-alpine. The 16 is the version number. The word alpine means a small, light version of the recipe.
  • Primary — the main record store. It takes writes (new rows).
  • Replica / standby — a copy that follows the primary. It takes reads only. It becomes the new primary on failover.
  • WAL — short for write-ahead log. A list of every change, written down first, before the real data changes. The replica reads this list to stay in sync. WAL streaming means the replica reads the list live, as changes happen.
  • Replication slot — a bookmark the primary keeps, so it does not throw away WAL entries the replica still needs.
  • Failover — the standby taking over as the new primary.
  • Patroni — a program that watches the record stores and does the failover by itself.
  • etcd — a small notebook service that all the Patroni nodes share. Patroni writes "who is the leader right now" in etcd, so every node agrees. You do not type commands into etcd in this lab. It runs in the background as a third container in the Patroni folder.
  • Leader — the Patroni word for the primary. The leader takes writes. The other node is the replica.
  • Bootstrap — the first-time setup of a Patroni cluster. When Patroni starts for the first time, its bootstrap creates the record store from scratch. That is why the Patroni part uses a record store called postgres (the default name) instead of practice. The bootstrap does not create a store called practice.
  • JSON — short for JavaScript Object Notation. It is a plain-text way of writing structured data, with names in quotes and values after a colon, inside curly brackets. Example: {"name": "patroni-1", "role": "leader"} means the member named patroni-1 has the role leader. You do not need to learn JSON. You only need to find the role line in the cluster output.
  • curl — a small tool that asks a web address for its text and prints the answer in your terminal. If curl is not installed on your machine, open the same address in your browser instead — you see the same text.
  • Service — one running program in a Docker Compose file. Container is the sealed box that runs it. The two names are different, and this lab uses both. Example: the service is called primary, and its container is called pg-primary. The service name is what you use in docker compose stop primary. The container name is what you use in docker exec pg-primary ....
  • Volume — a named place on your machine where Docker keeps a container's data. The data lives in a volume, so it survives a restart. Wiping the volume wipes the data.
  • SQL — the language you use to talk to a record store. SQL commands end with a semicolon ;. CREATE TABLE makes a table. INSERT INTO adds rows. SELECT reads rows.
  • psql — the command-line tool for talking to PostgreSQL. It runs inside the container.
  • pg_basebackup — a PostgreSQL tool that copies all the data from a primary to make a new standby. The replica's start-up script uses it. You do not type it yourself in this lab.
  • pg_rewind — a PostgreSQL tool, mentioned in the "does NOT cover" section, that lets an old primary rejoin faster after a failover. The plain lab in Part 1 does not use it. That is why the old primary must be rebuilt there.
  • Practice logins — all logins in this lab are practice logins on your own machine, for learning only. The login name is learner. The practice password is set in the file phase1/postgresql-lab/docker-compose.yml. Never use these passwords anywhere real. You do not type the password in the commands below, because the commands run inside the container, where the login is already set up.

The two files you never type, but need to understand

phase1/postgresql-lab/01-replicator.sql

What this is: a short SQL file that runs once, when the primary record store is first created. Why it exists: it makes a special user called replicator. The replica uses that user to copy data. That user can read the change log (the WAL) and nothing else. The file sets a practice password for that user. You never open this file. The primary container runs it by itself the first time it starts. If this file is not readable, the primary fails to start. That is why Step 1 runs chmod first.

phase1/postgresql-lab/replica-entrypoint.sh

What this is: the replica's start-up script. A script is a saved list of commands in one file. Why it exists: it tells the replica what to do when it starts. In order, it (1) waits until the primary answers, (2) if the replica has no data yet, copies all data from the primary with pg_basebackup, and prints Copy done., and (3) starts PostgreSQL as a standby. If the replica already has data, step 2 is skipped. You never type this script's commands yourself. The replica container runs it by itself. The log line Copy done. in Step 1 comes from this script.

The doors (ports) in this lab

  • Part 1: the primary answers on door 5432 on your machine. The replica answers on door 5433 on your machine. Inside its own container, the replica still uses door 5432, but from outside you reach it on 5433. That is why two copies can run on one machine without fighting over the same door.
  • Part 2 (Patroni): patroni-1 answers on door 5432 for the record store and door 8008 for its status page. patroni-2 answers on door 5433 for the record store and door 8009 for its status page. The status page is the web address you ask with curl. Door 8008 asks patroni-1's status page. Door 8009 asks patroni-2's status page. Both pages show the same whole cluster, so either one tells you who the leader is.

Part 1 — Primary and replica

Step 1 — Start both record stores

First, move your terminal into the lab folder. The folder is phase1/postgresql-lab/. Type this, then press Enter:

Try it Yourself »Open the practice terminal and run it yourself — nothing installs. Included with Phase 1. Simulation — practice version. Run the real lab with Docker to do it for real.
Command
cd phase1/postgresql-lab
  • cd — short for "change directory". It moves your terminal into a folder.
  • phase1/postgresql-lab — the path to the lab folder, from where your terminal opens.

If your terminal is already inside the phase1 folder, type the shorter version instead:

Command
cd postgresql-lab

Then check you are in the right place. Type ls and press Enter. You should see docker-compose.yml, 01-replicator.sql, and replica-entrypoint.sh in the list. If you do not see them, you are in the wrong folder — move again with cd.

What this step is: two commands. The first makes the setup file readable. The second starts both record stores. Why we run them: the record store runs as its own user, and it cannot read a file that is private to you. The chmod command fixes that. Then Compose starts the primary and the replica together.

Type this first, then press Enter:

Command
chmod -R a+r .

Word by word:

  • chmod — short for "change mode". It changes who can read a file.
  • -R — means do this for every file in this folder, and in every folder inside it.
  • a+r — means everyone can read. The letter a means all users. The letter r means read. The + means add this permission.
  • . — means this folder, the one your terminal is in right now. A single dot is shorthand for "here".

What you should see: nothing. chmod prints nothing when it works. That is normal. Silence means it worked.

If it breaks: No such file or directory means you are in the wrong folder. Run ls and check you are inside the postgresql-lab folder, then try again. ls is a command that lists the files in the folder your terminal is in. You should see docker-compose.yml, 01-replicator.sql, and replica-entrypoint.sh in that list.

Then start both record stores. Type this, then press Enter:

Command
docker compose up -d

Word by word:

  • docker — the Docker tool.
  • compose — the part of Docker that starts several containers together from one file.
  • up — start everything listed in the file.
  • -d — short for detached. It means run in the background and give me my terminal back, instead of filling my screen with logs.

What you should see, line by line:

Command
[+] Running 2/2
 ✔ Container pg-primary  Started
 ✔ Container pg-replica  Started
  • [+] Running 2/2 — 2 out of 2 containers are running.
  • Container pg-primary Started — the primary container started.
  • Container pg-replica Started — the replica container started.
  • How to tell it worked: both lines say Started.

Now check they are both up. What this is: ps lists the containers Compose is running. Why we run it: the start lines scroll past fast, and this check proves both containers are still up right now.

Type this, then press Enter:

Command
docker compose ps

Word by word:

  • docker compose — the Docker Compose tool, as above.
  • ps — short for "process status". It lists the running containers.

What you should see: a table with pg-primary and pg-replica, each with STATUS Up. The real table has more columns than the example below. What matters is both names, each with STATUS Up.

Command
NAME          STATUS
pg-primary    Up
pg-replica    Up

The replica copies all data from the primary the first time it starts, so it takes about a minute. Check its log. What this is: logs shows what a container has printed. Why we run it: the replica's start-up script prints Copy done. when the first copy finishes. That line is the proof the copy finished.

Type this, then press Enter:

Command
docker compose logs replica

Word by word:

  • docker compose — the Docker Compose tool, as above.
  • logs — show the printed output (the log) of a container.
  • replica — the service name of the replica. Service names, not container names, go after logs.

What you should see, near the end of the log:

Command
No data here yet. Copying from the primary...
Copy done.
  • No data here yet. Copying from the primary... — the replica had no data, so it is copying all of it from the primary.
  • Copy done. — the first copy finished. That is the line that matters.

If it breaks: if the replica log shows waiting for the primary for more than two minutes, check the primary is up with docker compose ps. If the primary is up and the replica still waits, read the replica log from the top. The error line is usually about the password or the connection.

Step 2 — Write three fake rows on the primary

What this is: one long command that connects to the primary and runs SQL inside it. Why we run it: it creates a small table and puts three fake orders in it, so the next steps have something to copy and read.

Type this, then press Enter:

Command
docker exec pg-primary psql -U learner -d practice -c "CREATE TABLE orders (id INT, item TEXT, amount INT); INSERT INTO orders VALUES (101, 'notebook', 250), (102, 'pen', 40), (103, 'mug', 350);"

Word by word:

  • docker exec — run a command inside a container that is already running. exec means execute, or run.
  • pg-primary — the container name. This is the primary container. Check the name: pg-primary, not pg-replica.
  • psql — the tool for talking to PostgreSQL. It runs inside the container.
  • -U learner — log in as the user named learner. The -U flag means "user". learner is the practice login name.
  • -d practice — use the record store named practice. The -d flag means "database". practice is the name of the practice store.
  • -c "..." — run the SQL inside the quotes, then stop. The -c flag means "command". Everything inside the double quotes is one SQL command string.
  • Inside the quotes, the SQL itself, in order:
  • CREATE TABLE orders (id INT, item TEXT, amount INT); — make a table called orders. It has three columns. id holds a whole number (INT means integer, a whole number). item holds text (TEXT means text). amount holds a whole number. The semicolon ; ends one SQL command.
  • INSERT INTO orders VALUES (101, 'notebook', 250), (102, 'pen', 40), (103, 'mug', 350); — add three rows to the orders table. Row 101 is a notebook for 250. Row 102 is a pen for 40. Row 103 is a mug for 350. The numbers are fake prices in the lab's made-up units. VALUES means "here are the values to add".

What you should see, line by line:

Command
CREATE TABLE
INSERT 0 3
  • CREATE TABLE — the table was made.
  • INSERT 0 3 — 3 rows went in. The 0 is a counter PostgreSQL prints; the 3 is the number of rows added. That is the number that matters.
  • The data is fake — made up for this lab.

If it breaks: relation already exists means you already made the table. Relation is PostgreSQL's word for a table. Skip the CREATE part and just run the INSERT, or drop the table first with DROP TABLE orders; and start this step again. DROP TABLE means delete the whole table.

Step 3 — Read the same rows from the replica

What this is: the same kind of command, but aimed at the replica instead of the primary. Why we run it: it proves the replica already has the same rows, because it follows the primary live.

Type this, then press Enter:

Command
docker exec pg-replica psql -U learner -d practice -c "SELECT * FROM orders ORDER BY id;"

Word by word:

  • docker exec pg-replica — run a command inside the replica container. Check the name: pg-replica, not pg-primary.
  • psql -U learner -d practice — talk to PostgreSQL as user learner, in the store named practice, as in Step 2.
  • -c "SELECT * FROM orders ORDER BY id;" — run this SQL. SELECT means read. The star * means all columns. FROM orders means from the orders table. ORDER BY id means sort the rows by their id number, smallest first.

What you should see, line by line:

Command
 id  |   item   | amount
-----+----------+--------
 101 | notebook |    250
 102 | pen      |     40
 103 | mug      |    350
(3 rows)
  • The first line is the column names: id, item, amount.
  • The second line is a divider made of dashes and plus signs. It is only decoration.
  • Then the three rows, in id order: 101 notebook 250, 102 pen 40, 103 mug 350.
  • (3 rows) — three rows were returned. That is the number that matters.
  • How to tell it worked: the replica shows the same three rows you wrote on the primary. The copy is live.

If it breaks: if the replica shows 0 rows, wait 10 seconds and try again — the copy takes a moment. If it still shows 0 rows, check the replica is really a replica. Type this, then press Enter:

Command
docker exec pg-replica psql -U learner -d practice -c "SELECT pg_is_in_recovery();"

Word by word: SELECT pg_is_in_recovery(); means "ask: are you in recovery mode?" Recovery mode means "I am a standby, following a primary, not taking writes". You should see t, which means true. If it shows f, which means false, the replica is not following the primary. Stop and start it again with the command below. What this is: restart stops a service and starts it again. Why we run it: a fresh start makes the replica follow the primary again.

Command
docker compose restart replica

Word by word: docker compose restart replica — restart the service named replica.

Step 4 — Try to write on the replica (it must refuse)

What this is: an insert command aimed at the replica. Why we run it: a standby takes reads only. Trying a write and watching it fail is the proof. The error is the expected result. Do not try to fix it.

Type this, then press Enter:

Command
docker exec pg-replica psql -U learner -d practice -c "INSERT INTO orders VALUES (104, 'pen stand', 120);"

Word by word: INSERT INTO orders VALUES (104, 'pen stand', 120); means add one row to the orders table: id 104, item pen stand, amount 120.

What you should see:

Command
ERROR:  cannot execute INSERT in a read-only transaction
  • ERROR: — the command failed.
  • cannot execute INSERT in a read-only transaction — the replica refuses writes because it is read-only. A transaction is one batch of work the record store does together.
  • How to tell it worked: you see this error. The error IS the proof. The replica refuses writes. This is correct and expected.

If it breaks: if you see INSERT 0 1 instead of the error, you ran it on the primary by mistake. Check the container name in the command (pg-replica, not pg-primary) and try again.

Step 5 — Kill the primary and promote the replica

What this is: first stop the primary, then check the replica still answers, then promote the replica to be the new primary. Why we do it: this is failover by hand. It proves the data survived on the replica, and the replica can take over.

First, stop the primary. Type this, then press Enter:

Command
docker compose stop primary

Word by word:

  • docker compose stop — stop a service, but do not delete it. stop is different from down: stop leaves the container in place so you can start it again; down removes the containers.
  • primary — the service name. Use the service name here, not the container name pg-primary.

What you should see:

Command
✔ Container pg-primary  Stopped
  • The tick ✔ means done. Container pg-primary Stopped means the primary container stopped.

If it breaks: No such container means the name is wrong. Run docker compose ps and use the name it shows.

Now check the replica still answers reads. Type this, then press Enter:

Command
docker exec pg-replica psql -U learner -d practice -c "SELECT * FROM orders ORDER BY id;"

This is the same read command as Step 3. What you should see: the same 3 rows, 101, 102, and 103. The data survived — the replica has its own copy.

Now promote the replica to be the new primary. What this is: pg_promote() is a PostgreSQL function that tells a standby "stop following, become the primary". Why we run it: without this command, the replica stays a read-only standby forever. This command is the failover.

Type this, then press Enter:

Command
docker exec pg-replica psql -U learner -d practice -c "SELECT pg_promote();"

Word by word: SELECT pg_promote(); means run the promote function and show its answer.

What you should see:

Command
 pg_promote
------------
 t
  • pg_promote is the name of the answer column.
  • t means true. True means the promotion worked.

Check it is no longer in recovery. Type this, then press Enter:

Command
docker exec pg-replica psql -U learner -d practice -c "SELECT pg_is_in_recovery();"

What you should see:

Command
 pg_is_in_recovery
-------------------
 f
(1 row)
  • f means false. False means it is no longer in recovery. It is now a primary.
  • (1 row) means one answer row was returned.

Prove it takes writes now. Type this, then press Enter:

Command
docker exec pg-replica psql -U learner -d practice -c "INSERT INTO orders VALUES (104, 'pen stand', 120); SELECT * FROM orders ORDER BY id;"

Word by word: this runs two SQL commands in one -c string. First the INSERT adds row 104. Then the SELECT reads all rows in id order.

What you should see, line by line:

Command
INSERT 0 1
 id  |   item    | amount
-----+-----------+--------
 101 | notebook  |    250
 102 | pen       |     40
 103 | mug       |    350
 104 | pen stand |    120
(4 rows)
  • INSERT 0 1 — 1 row went in. The write worked.
  • Then 4 rows, including 104 | pen stand | 120.
  • (4 rows) — four rows returned. That is the number that matters.
  • Failover done — by hand.

If it breaks: if pg_promote() shows f, the replica was already promoted. That happens if you ran this step twice. Check with SELECT pg_is_in_recovery();. If it shows f, you are done.

Step 6 — The honest part: the old primary cannot just rejoin

What this is: a plain explanation, not a command. The old primary still has the old data. It does not know about row 104. It cannot rejoin as a replica by itself. In real work, you rebuild it from the new primary, the same way the replica was first built: copy the data with pg_basebackup, then start it as a standby. The commands are the same as the ones in the file phase1/postgresql-lab/replica-entrypoint.sh, which you read about above. For this lab, the simple way back is to wipe both and start fresh.

Type these two commands, one at a time, pressing Enter after each:

Command
docker compose down -v
docker compose up -d

Word by word:

  • docker compose down — stop the containers and remove them. down is stronger than stop: stop leaves the containers in place, down removes them.
  • -v — also wipe the volumes. A volume is the named place where the data lives. Without -v, the data survives in the volume and comes back. With -v, the data is wiped.
  • docker compose up -d — start everything again in the background, as in Step 1.

What you should see: the containers stop, the data is wiped, then both record stores start fresh with STATUS Up. Check with docker compose ps if you want to see the Up status again.

If it breaks: if up -d fails with port is already allocated, the old containers did not stop yet. Port is already allocated means door 5432 or 5433 is still held by an old container. Wait a few seconds and run docker compose up -d again.

That wipes both record stores and starts fresh. The data was fake, so losing it is fine.

Part 2 — Patroni does the failover for you (advanced)

What Patroni is

In Part 1 you promoted the replica by hand. Patroni is a watcher program that does that job by itself: it watches the main record store, and if it dies, Patroni promotes the standby within seconds. It keeps its notes in etcd — a small notebook service that all the Patroni nodes share. You do not type commands into etcd. It starts by itself as a third container in the Patroni folder.

Do Part 1 first. Part 2 is a separate cluster in a separate folder. Do not run Part 1 and Part 2 at the same time on the same doors, because both want door 5432. Stop Part 1 first with docker compose down from inside the phase1/postgresql-lab/ folder, or the Patroni start will fail with port is already allocated.

Step 1 — Start the Patroni cluster

First, move your terminal into the Patroni folder. The folder is phase1/postgresql-lab/patroni/. From inside phase1/postgresql-lab/, type cd patroni and press Enter.

What this is: start the Patroni cluster and build its image the first time. Why we run it: the cluster is two Patroni nodes plus etcd. The first start builds the Patroni image from the file phase1/postgresql-lab/patroni/Dockerfile, so it takes a few minutes.

Type this, then press Enter:

Command
docker compose up -d --build

Word by word:

  • docker compose up -d — start everything in the background, as in Part 1, Step 1.
  • --build — build the image first, before starting. Build means turn the Dockerfile recipe into a runnable image. Without --build, Compose would reuse an old image. The first start needs the build.

What you should see: the build lines scroll past, then both Patroni nodes start. The first start builds the Patroni image, so it takes a few minutes.

Now check the cluster. What this is: curl asks the status page for its text. Why we run it: the status page tells you who the leader is and who the replica is.

Type this, then press Enter:

Command
curl http://localhost:8008/cluster

Word by word:

  • curl — a small tool that asks a web address for its text and prints the answer.
  • http://localhost:8008/cluster — the address. http:// means a web page. localhost means this machine. 8008 is the door number of patroni-1's status page. /cluster means "show me the cluster".

What you should see: JSON with two members, one with "role": "leader" and one with "role": "replica". JSON is a plain-text way of writing structured data. The real answer is longer than the example below. The two lines that matter are the role lines.

Command
{ "members": [
  {"name": "patroni-1", "role": "leader"},
  {"name": "patroni-2", "role": "replica"} ] }
  • {"name": "patroni-1", "role": "leader"} — patroni-1 is the leader. The leader takes writes.
  • {"name": "patroni-2", "role": "replica"} — patroni-2 is the replica. It follows the leader.
  • How to tell it worked: one member says "role": "leader" and the other says "role": "replica".

If curl is not installed on your machine, open http://localhost:8008/cluster in your browser instead. You see the same text.

If it breaks: if the page does not load, wait a minute. The first node builds the record store from scratch. Check the logs with the command below. What this is: logs shows what a container printed. The service name here is patroni-1.

Command
docker compose logs patroni-1

Step 2 — Write a row, watch it copy

What this is: write one fake row on the leader, then read it from the second node. Why we run it: it proves the second node copies the leader's data.

Type this, then press Enter:

Command
docker exec patroni-1 psql -U learner -d postgres -c "CREATE TABLE orders (id INT, item TEXT); INSERT INTO orders VALUES (201, 'stapler');"

Word by word:

  • docker exec patroni-1 — run a command inside the container named patroni-1. This is the leader.
  • psql -U learner — talk to PostgreSQL as user learner.
  • -d postgres — use the record store named postgres. This is the default store name. Patroni's first-time setup (its bootstrap) does not create a store called practice. That is why the name is different from Part 1, where the store was called practice.
  • -c "CREATE TABLE orders (id INT, item TEXT); INSERT INTO orders VALUES (201, 'stapler');" — make a table called orders with two columns (id, a whole number; item, text), then add one row: id 201, item stapler.

What you should see:

Command
CREATE TABLE
INSERT 0 1
  • CREATE TABLE — the table was made.
  • INSERT 0 1 — 1 row went in.

Now read it from the second node. Type this, then press Enter:

Command
docker exec patroni-2 psql -U learner -d postgres -c "SELECT * FROM orders;"

Word by word: run a command inside the container named patroni-2, and read all rows from the orders table. There is no ORDER BY here because there is only one row.

What you should see:

Command
 id  |  item
-----+---------
 201 | stapler
(1 row)
  • One row: 201, stapler.
  • (1 row) — one row returned.

If it breaks: if the second node shows 0 rows, wait 10 seconds and try again — the copy takes a moment. If it still shows 0 rows, check the cluster with curl http://localhost:8008/cluster and confirm one member is the leader.

Step 3 — Kill the leader and watch Patroni promote the other one

What this is: stop the leader, wait, then check the cluster again on the second node's status page. Why we do it: this is the whole point of Patroni. Nobody promotes the standby by hand. Patroni does it by itself.

Type this, then press Enter:

Command
docker compose stop patroni-1

Word by word: docker compose stop patroni-1 — stop the service named patroni-1. stop leaves the container in place so you can start it again later.

What you should see:

Command
✔ Container patroni-1  Stopped

Wait 30 seconds. Then check the cluster again. Type this, then press Enter:

Command
curl http://localhost:8009/cluster

Word by word: curl asks the status page, as in Step 1. This time the door is 8009, which is patroni-2's status page. You ask patroni-2 because patroni-1 is stopped and cannot answer. Both status pages show the same whole cluster.

What you should see: patroni-2 now has "role": "leader". The real answer is longer. The lines that matter are the role lines.

Command
{ "members": [
  {"name": "patroni-2", "role": "leader"},
  {"name": "patroni-1", "role": "replica"} ] }
  • patroni-2 is now the leader.
  • patroni-1 is listed as a replica. It is stopped, so it is not really following yet. It becomes a real replica again when you start it in Step 4.
  • Patroni promoted it by itself. No command from you did the promotion.

Prove the new leader takes writes. Type this, then press Enter:

Command
docker exec patroni-2 psql -U learner -d postgres -c "INSERT INTO orders VALUES (202, 'ruler'); SELECT * FROM orders;"

Word by word: inside the container named patroni-2, add row 202 (ruler), then read all rows.

What you should see:

Command
INSERT 0 1
 id  |  item
-----+---------
 201 | stapler
 202 | ruler
(2 rows)
  • INSERT 0 1 — 1 row went in.
  • Both rows are there: 201 stapler, 202 ruler.
  • (2 rows) — two rows returned.

If it breaks: if patroni-2 still shows "role": "replica" after a minute, Patroni has not finished the promotion yet. Wait another minute and check again. If it never changes, read the logs with docker compose logs patroni-2.

Step 4 — Bring the old leader back

What this is: start the old leader again and watch it rejoin as a replica. Why we do it: it proves Patroni also handles the return. The old leader does not fight for the top job. It rejoins as a follower and copies the new data.

Type this, then press Enter:

Command
docker compose start patroni-1

Word by word:

  • docker compose start — start a service that was stopped with stop. start is different from up: up creates and starts containers from the file; start only starts containers that already exist and were stopped.
  • patroni-1 — the service name.

What you should see:

Command
✔ Container patroni-1  Started

Wait a minute, then check the cluster. Type this, then press Enter:

Command
curl http://localhost:8008/cluster

What you should see: patroni-1 back, now as a "replica", and patroni-2 still the leader.

Command
{ "members": [
  {"name": "patroni-1", "role": "replica"},
  {"name": "patroni-2", "role": "leader"} ] }
  • patroni-1 rejoined by itself and copied the new data from the leader.
  • That is what Patroni is for.

If it breaks: if patroni-1 does not come back, read its log with docker compose logs patroni-1. The error line names the problem.

Clean up — Part 2

What this is: stop everything and wipe the data. Why we run it: the data was fake, and the next run should start fresh.

Type this, while you are inside the phase1/postgresql-lab/patroni/ folder, then press Enter:

Command
docker compose down -v

Word by word: docker compose down stops the containers and removes them. -v also wipes the volumes, so the data is gone.

What you should see: the Patroni containers stop and the data is wiped.

If it breaks: No such container means the services are already stopped. Nothing to do.

That stops everything and wipes the data. The data was fake.

What you can now say, truthfully

"I ran a PostgreSQL primary and a standby with WAL streaming, proved the standby had the same data, promoted it by hand when the primary died, and ran a Patroni cluster that did the same failover by itself."

What this lab does NOT cover

  • Real clusters run three or more record store nodes, not two. → The Advanced section at the end of this lesson opens the Patroni file and lists what this two-node setup still lacks.
  • pg_rewind (used in the Patroni setup) lets an old primary rejoin faster. The plain lab in Part 1 does not use it. That is why the old primary must be rebuilt there.
  • Backups are a different job from replication. Replication protects you when a machine dies. Backups protect you when data is deleted by mistake. You need both in real work. → The Advanced section at the end of this lesson now teaches backups: read it before you claim them.

Failure drill — Kill the leader, watch Patroni promote

This drill proves Patroni promotes the standby by itself when the leader dies, and no rows are lost. It repeats Part 2, Steps 3 and 4, as a drill with a checklist. Do Part 2 first, up to Step 2, so row 201 is already saved. One warning: if you already ran Clean up — Part 2 above, the cluster is stopped AND the data is wiped (down -v deletes the volumes), so row 201 is gone. Start again from Part 2, Step 1, and save row 201 again in Step 2, then do the drill.

Drill Step 1 — Go into the Patroni folder and stop the leader

Move your terminal into the folder phase1/postgresql-lab/patroni/. Then type this and press Enter:

Command
docker compose stop patroni-1

What you should see:

Command
✔ Container patroni-1  Stopped

Drill Step 2 — Wait 30 seconds, then check the cluster on the second node's port

Type this, then press Enter:

Command
curl http://localhost:8009/cluster

What you should see: patroni-2 now has "role": "leader". The real answer is longer. The lines that matter are the role lines.

Command
{ "members": [
  {"name": "patroni-2", "role": "leader"},
  {"name": "patroni-1", "role": "replica"} ] }

Drill Step 3 — Prove the new leader takes writes

Type this, then press Enter:

Command
docker exec patroni-2 psql -U learner -d postgres -c "INSERT INTO orders VALUES (202, 'ruler'); SELECT * FROM orders;"

What you should see:

Command
INSERT 0 1
 id  |  item
-----+---------
 201 | stapler
 202 | ruler
(2 rows)

Both rows are there. Row 201 survived, and row 202 is new.

Drill Step 4 — Bring the old leader back

Type this, then press Enter:

Command
docker compose start patroni-1

What you should see:

Command
✔ Container patroni-1  Started

Wait a minute, then check the cluster. Type this, then press Enter:

Command
curl http://localhost:8008/cluster

What you should see: patroni-1 back, now as a "replica", and patroni-2 still the leader.

Command
{ "members": [
  {"name": "patroni-1", "role": "replica"},
  {"name": "patroni-2", "role": "leader"} ] }

Checklist — tick each one when you have seen it:

  • ☐ The leader changed: patroni-2 became the leader.
  • ☐ No rows lost: row 201 is still there after the failover.
  • ☐ New row saved: row 202 was written to the new leader.

Save your proof

The proof for this lab is the failover log: the cluster output showing the new leader, and the row count before and after.

Save the cluster output with this command, run from inside the patroni/ folder, after the drill. What this is: two commands joined by a redirect. Why we run it: it saves the cluster output into a file, instead of printing it on the screen.

First, make the proof folder if it does not exist. Type this and press Enter:

Command
mkdir -p ../../portfolio/proof

Word by word:

  • mkdir — short for "make directory". It makes a new folder.
  • -p — make the parent folders too, if they are missing, and do not complain if the folder already exists.
  • ../../portfolio/proof — the path to the folder. Each .. means "go up one folder". You are in phase1/postgresql-lab/patroni/. The first .. takes you up to phase1/postgresql-lab/. The second .. takes you up to phase1/. Then portfolio/proof takes you down into the portfolio folder, then into the proof folder inside it. So the full folder is phase1/portfolio/proof/.

Then save the cluster output. Type this and press Enter:

Command
curl http://localhost:8009/cluster > ../../portfolio/proof/failover-log.txt

Word by word:

  • curl http://localhost:8009/cluster — ask patroni-2's status page for the cluster text, as in the drill.
  • > — redirect. It means "send the output into a file, instead of printing it on the screen". It overwrites the file if the file already exists.
  • ../../portfolio/proof/failover-log.txt — the file to write. It lives in phase1/portfolio/proof/, and its name is failover-log.txt.

What you should see: nothing in the terminal when you run the save command. The cluster output went into the file, not the screen. Silence means it worked.

A note on the template: the folder phase1/portfolio/proof/ also holds a file called failover-log-TEMPLATE.txt, verified on disk. That template is the full format for the proof. Read this carefully: the curl command above already creates a file called failover-log.txt with the raw cluster output. If you copy the template over that same name, it overwrites the saved cluster output. So do one or the other. Either keep the raw saved output as your proof, or copy the template to a new name and fill it in by hand with the cluster output and the row counts. Do not copy the template over the file you just saved unless you have already pasted the cluster output into it.

If it breaks: if the file is empty, the cluster was not up on port 8009 when you ran it. Check the cluster with curl http://localhost:8009/cluster first, then save again.

Reset after the drill

Run this from the phase1 folder to wipe the drill and start fresh. What this is: reset.sh is a helper script in the phase1 folder. Its argument tells it which lab folder to wipe. Why we run it: it stops the cluster and wipes the data, then prints that it is done.

Move your terminal into the phase1 folder first. Then type this and press Enter:

Command
bash reset.sh postgresql-lab/patroni

Word by word:

  • bash — the program that runs script files.
  • reset.sh — the script file. It lives in the phase1 folder. That is why you must be inside phase1 first.
  • postgresql-lab/patroni — the argument. It tells the script which folder to wipe. It is a path from inside phase1: the patroni folder inside the postgresql-lab folder.

What you should see: the script stops the cluster and wipes the data, then prints that it is done.

If it breaks: Permission denied means the script is not marked runnable. Runnable means the file is allowed to run as a program. Fix it with the command below, then try again. What this is: chmod +x adds the run permission to a file. Why we run it: without the run permission, your machine refuses to run the script.

Command
chmod +x reset.sh

Word by word: chmod changes file permissions, as in Part 1, Step 1. +x means add the execute (run) permission. reset.sh is the file.

Or, from inside the patroni folder, the plain way. Type this and press Enter:

Command
docker compose down -v && docker compose up -d

Word by word: docker compose down -v stops the containers, removes them, and wipes the volumes. && means "run the next command only if the first one worked". docker compose up -d starts the cluster fresh in the background. What you should see: the containers stop, the data is wiped, then the cluster starts fresh. That stops everything and wipes the data. The data was fake.

Advanced — Backups, the Patroni file, and what this setup still lacks

This section is for the reader who already did the lab above. It covers the three things the review of this kit flagged as missing for advanced readers: real backups, the Patroni settings file opened and explained, and an honest list of what this two-node setup still lacks. Everything here is checked against the lab's own files and the PostgreSQL docs. The backup commands were not run end to end on this kit — if a step differs on your machine, trust the error line, not this page.

Advanced 1 — Backups: replication is not a backup

What this is: a backup is a saved copy of the data, stored separately from the live database, that you can bring back after the data itself is damaged. Replication is a live copy that follows the main database. Why both: replication protects you when a machine dies. It does NOT protect you when someone deletes a table by mistake — the delete is copied to the standby in seconds, and both copies are then wrong. Only a backup saves you there. That is the sentence the "does NOT cover" section above already says. This section teaches the backup itself.

There are two kinds of backup. A logical backup copies one database as instructions (SQL text, or a compressed file of it). A physical backup copies the database's actual files while it is running. Logical is simple and restores one database. Physical is faster for big databases and restores the whole cluster. Learn logical first.

Advanced 2 — Logical backup and restore, hands on

What this is: pg_dump is the tool that writes a logical backup of one database. pg_restore is the tool that loads it back. Why we run it: this is the backup you will actually use first in real work, and the restore below proves the backup is real — a backup you have never restored is a guess, not a backup.

Do this with the Part 1 lab running (the primary on port 5432, with the orders table from the lab steps). First, take the backup. Type this, then press Enter:

Command
docker exec -e PGPASSWORD=learn1234 pg-primary pg_dump -U learner -d practice -Fc -f /tmp/practice.dump

Word by word:

  • docker exec pg-primary — run a command inside the pg-primary container, as the lab already does.
  • -e PGPASSWORD=learn1234 — hand the password to the command through an environment variable, so it does not ask. The password is learn1234: it is the practice password from the lab's own docker-compose.yml.
  • pg_dump — the backup tool.
  • -U learner — connect as the user learner.
  • -d practice — back up the database named practice.
  • -Fc — write the backup in custom format: compressed, and restorable in pieces. F means format, c means custom.
  • -f /tmp/practice.dump — write the backup to the file /tmp/practice.dump inside the container.

What you should see: nothing, or a short progress note. Silence means it worked. Check the file exists and has a size:

Command
docker exec pg-primary ls -lh /tmp/practice.dump

What you should see: one line with a file size bigger than zero. If it breaks: pg_dump: error: connection to server failed means the primary is not running. Start the lab first. password authentication failed means the password is wrong — it must match the POSTGRES_PASSWORD line in the lab's docker-compose.yml.

Save a copy outside the container, so the backup survives the container:

Command
docker cp pg-primary:/tmp/practice.dump ./practice.dump

Word by word: docker cp copies a file between a container and your machine. pg-primary:/tmp/practice.dump is the file inside the container. ./practice.dump is where it lands on your machine, in the lab folder.

Now prove the backup works: restore it into a scratch database (a throwaway copy, not the live one) and compare the rows. Type these three commands, one at a time:

Command
docker exec -e PGPASSWORD=learn1234 pg-primary psql -U learner -d postgres -c "CREATE DATABASE practice_check;"

Word by word: psql is the PostgreSQL command-line tool, as in the lab. -d postgres connects to the built-in postgres database, because you cannot create a database while connected to the one you are creating. CREATE DATABASE practice_check; makes an empty database to restore into.

Command
docker exec -e PGPASSWORD=learn1234 pg-primary pg_restore -U learner -d practice_check /tmp/practice.dump

Word by word: pg_restore loads a custom-format backup. -d practice_check loads it into the scratch database. The last part is the backup file.

Command
docker exec -e PGPASSWORD=learn1234 pg-primary psql -U learner -d practice_check -c "SELECT count(*) FROM orders;"

What you should see: the same row count as the live database. Check the live count with the same question against practice:

Command
docker exec -e PGPASSWORD=learn1234 pg-primary psql -U learner -d practice -c "SELECT count(*) FROM orders;"

The two numbers must match. If they do, the backup is real. Also check the restored copy is read-write, not a standby:

Command
docker exec -e PGPASSWORD=learn1234 pg-primary psql -U learner -d practice_check -c "SELECT pg_is_in_recovery();"

What you should see: f. pg_is_in_recovery() is the same check the lab already uses. f means false: this copy is not recovering, it takes writes. Then clean up the scratch database:

Command
docker exec -e PGPASSWORD=learn1234 pg-primary psql -U learner -d postgres -c "DROP DATABASE practice_check;"

What to check after ANY restore, every time: (1) the row counts match the source, (2) pg_is_in_recovery() shows f on the restored copy, (3) the app can connect and write one test row, then delete it. A restore that nobody checked is not a restore.

Advanced 3 — Physical backup with pg_basebackup

What this is: pg_basebackup copies the whole data directory of a running cluster, over a replication connection. Why we run it: for a big database, restoring files is much faster than replaying SQL, and it backs up every database in the cluster at once, not just one.

The lab already uses this tool: the replica's start-up script (replica-entrypoint.sh) copies the data from the primary with pg_basebackup before it starts following. So the command below is the same tool, pointed at a backup folder instead of a new replica.

Take the backup. Type this, then press Enter:

Command
docker exec -e PGPASSWORD=RepliPass123 pg-primary pg_basebackup -h localhost -U replicator -D /tmp/pg-backup -Ft -z -Xs -P

Word by word:

  • -e PGPASSWORD=RepliPass123 — the password for the replicator user. It is in the lab's own 01-replicator.sql, which creates that user with REPLICATION LOGIN.
  • pg_basebackup — the physical backup tool.
  • -h localhost — connect to the database on this same container. localhost means "this machine" — inside the container, that is the primary itself.
  • -U replicator — connect as the replicator user. Only a user with the replication right may take a physical backup.
  • -D /tmp/pg-backup — the folder to write the backup into. It must be empty or not exist yet.
  • -Ft — write the backup as tar files. F means format, t means tar.
  • -z — compress the tar files.
  • -Xs — stream the change log (WAL) into the backup as it is taken, so the finished backup is consistent on its own. X means how to handle the change log, s means stream it.
  • -P — show progress while it runs.

What you should see: progress lines, then the command finishes. List what it made:

Command
docker exec pg-primary ls -lh /tmp/pg-backup

What you should see: base.tar.gz (the data files), pg_wal.tar.gz (the change log needed to reach a consistent state), and backup_manifest (a list of every file with a checksum — a fingerprint that proves nothing was altered). Verify the backup against that list:

Command
docker exec pg-primary pg_verifybackup -n /tmp/pg-backup

Word by word: pg_verifybackup checks a backup against its manifest. -n means skip reading the change log while checking (this backup is in tar files, so the check skips that part). What you should see: the line backup successfully verified. That line is the pass — the tool prints it when every file matches its fingerprint. If it prints errors instead, the backup is damaged: take a fresh backup and check again.

Restoring a physical backup, in plain steps (read these before you need them at 2am): stop the server first — you cannot replace a running database's files. Move the old data directory aside, do NOT delete it until the restored server is verified — it may hold the only copy of recent data. Extract base.tar.gz into the empty data directory, extract pg_wal.tar.gz into the pg_wal folder inside it, create an empty file called recovery.signal in the data directory (it tells the server "replay the change log, then start"), and start the server. Then run the same three checks as the logical restore: row counts match, pg_is_in_recovery() shows f, the app can write a test row. Two hard rules: a physical backup restores only onto the same major version of PostgreSQL (16 restores to 16, never to 15 or 17), and a physical backup alone only restores to the moment the backup finished. Restoring to any later moment needs WAL archiving, which is next.

This physical restore was written from the PostgreSQL docs and checked against the lab's files, but it was NOT run end to end on this kit — the data-directory step works differently inside a Docker named volume than on a plain machine. Practise it on a copy of the lab first, never on your only copy.

Advanced 4 — WAL archiving: the missing piece for point-in-time recovery

What this is: WAL archiving means saving every change-log file to a safe place the moment the database finishes writing it, instead of letting the database delete it. Point-in-time recovery means restoring to any moment you choose — for example, "five minutes before someone deleted the table" — instead of only to the last backup. Why it matters: a nightly backup plus archived change logs can rebuild any moment since the backup. A nightly backup alone can only rebuild last night.

This lab has no WAL archiving. The two settings that turn it on are archive_mode = on and archive_command (the command that copies each finished change-log file somewhere safe). They live in the server settings, and they need a safe destination that is NOT on the same machine as the database — a copy on the same disk dies in the same disk failure. Know the names and the idea; setting it up is a real project, not a one-liner.

Advanced 5 — Open the Patroni file, line by line

What this is: the Patroni settings for node 1 live in phase1/postgresql-lab/patroni/patroni-1.yml. Node 2's file is identical except the name and the addresses. The lab never opens this file. Here it is, opened.

  • scope: practice-cluster — the name of this cluster. Every node with the same scope belongs to the same cluster.
  • namespace: /devops-kit/ — a prefix in etcd, so this cluster's notes do not collide with another cluster's notes.
  • name: patroni-1 — this node's own name.
  • restapi: listen: 0.0.0.0:8008 — the status page this node serves. connect_address: patroni-1:8008 is the address other nodes use to reach it. This is the page the lab's curl commands ask.
  • etcd: host: etcd:2379 — where Patroni keeps its notes (who is leader right now). One address, one etcd node — see the gaps below.
  • bootstrap: dcs: ttl: 30 — the leader must renew its claim every 30 seconds, or the others treat it as dead. loop_wait: 10 — Patroni checks the cluster every 10 seconds. retry_timeout: 10 — give up on one try after 10 seconds. maximum_lag_on_failover: 1048576 — a standby that is more than 1,048,576 bytes (1 MB) behind may not be promoted, so a failover does not lose more than about 1 MB of recent writes.
  • postgresql: use_pg_rewind: true — when an old leader comes back, rewind its files to the point where the histories split, instead of rebuilding it from scratch. That is why the drill's old leader rejoins as a replica.
  • parameters: wal_level: replica, hot_standby: "on", max_wal_senders: 5, max_replication_slots: 5 — the same replication settings as the plain lab, written here so Patroni sets them itself.
  • initdb: encoding: UTF8, data-checksums — when the first node builds the cluster from nothing, use UTF8 text and turn on data checksums (fingerprints that catch disk corruption).
  • pg_hba: — the two access rules: the replicator user may connect for replication, and any user may connect to any database, both with password (scram-sha-256), from any address (0.0.0.0/0). That last part — any address — is a learning shortcut, not a production setting. See the gaps.
  • users: learner — the superuser the lab logs in as. replicator — the replication user. Both passwords are written in plain text in this file. That is a learning shortcut too.
  • postgresql: listen: 0.0.0.0:5432, connect_address: patroni-1:5432, data_dir: /var/lib/postgresql/data, pgpass: /tmp/pgpass — this node's own database: which door it listens on, where its files live, and where it keeps the password file it uses to connect to the other node.
  • tags: nofailover: false, noloadbalance: false, clonefrom: false — all false, meaning this node may become leader, may take reads, and may be cloned from. Setting one to true would exclude the node from that job.

Advanced 6 — What this two-node setup still lacks

Say these plainly in any interview or write-up. Do not claim this lab is production.

  • No quorum. Two database nodes cannot vote a majority: if one dies, the other cannot prove it is the chosen one, it can only assume. Real clusters run three nodes, so two out of three is a majority. Worse, the etcd in this lab is a single node — if etcd dies, Patroni cannot make any failover decision at all. Real setups run three etcd nodes.
  • No WAL archiving, no backups. Covered above. The lab admits it; now you know the fix.
  • No TLS. Traffic between the nodes and from your machine is plain text. Anyone on the same network can read it. Real setups turn on TLS (ssl = on in the server settings, plus certificate files) so the traffic is scrambled.
  • Weak access rules. The pg_hba lines allow any address (0.0.0.0/0), the passwords are practice passwords written in plain text in the files, and learner is a superuser. Real setups allow only the app's addresses, give the app a user that can only do its own job, and keep passwords in a secrets store, never in a file.
  • No connection pooling. Every app connection is a real server process. A few hundred connections will exhaust the machine. Real setups put a pooler in front — PgBouncer is the usual one — which reuses a small set of real connections for many app connections.

What you can now say, truthfully — advanced

  • "I backed up a PostgreSQL database with pg_dump and with pg_basebackup, verified the backup against its manifest, and restored it into a scratch database and compared the row counts." (Only if you did Advanced 2 and 3.)
  • "I read the Patroni settings file and can explain what ttl, maximum_lag_on_failover, and use_pg_rewind do." (Only if you did Advanced 5.)
  • "I know what a two-node Patroni setup still lacks for production: quorum, WAL archiving, TLS, tight access rules, and connection pooling." (Only if you did Advanced 6.)

Quick check — try it yourself

Question: In the terminal, type: curl http://localhost:8008/cluster — which database copy has the leader (main database) role?

Open the practice terminal to test this →

Show answer

You should see {"name": "patroni-1", "role": "leader"}, showing that patroni-1 is the main database and patroni-2 is the replica.