tezvyn:

Persist PostgreSQL data across compose down

AI-drafted, machine-checkedSource: interviewbeginner
WHAT IT TESTS

volume persistence basics.

OUTLINE

define a named volume and mount it at the database's data directory (/var/lib/postgresql/data); named volumes survive compose down.

WHAT THIS TESTS It checks whether you understand that a container's writable layer is ephemeral and how named volumes decouple data lifetime from container lifetime.

A GOOD ANSWER COVERS Anything written only to the container's writable layer disappears when the container is removed, which is what compose down does. To persist Postgres data you declare a named volume and mount it where Postgres stores data. In the YAML you add a top-level volumes: key with an entry like pgdata:, and under the db service you add volumes: with pgdata:/var/lib/postgresql/data. Now the data lives in a Docker-managed volume that survives container removal; docker compose down stops and removes containers but leaves named volumes, so the next docker compose up reattaches the same volume with your data intact. The important caveat: docker compose down -v explicitly deletes named volumes, so avoid -v unless you truly want a clean slate.

COMMON WRONG ANSWERS Relying on the writable layer and being surprised data vanishes. Mounting the wrong path, not the Postgres data directory. Confusing bind mounts with named volumes. Routinely using down -v and wondering why data is gone.

LIKELY FOLLOW-UPS What does down -v do? How does a named volume differ from a bind mount here? Where does Docker actually store the volume on disk, and how do you back it up?

ONE CONCRETE EXAMPLE The db service maps pgdata:/var/lib/postgresql/data and the file declares volumes: pgdata:. You insert rows, run docker compose down, then docker compose up -d; the rows are still there because the pgdata named volume was never removed. Only docker compose down -v would have wiped them.

Read the original → docs.docker.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.