🎓 A1Learner
🔍
0 of 50 lessons completed

Persist a Database

A database in a container keeps its data only when the data lives in a volume. Restart the container, and the rows are still there, because the volume never moved.

Start Postgres on a volume

This command starts Postgres with a named volume for its data.

docker run -d --name g5-db -v g5-pgdata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=secret postgres:16-alpine

Make a table and a row

psql runs inside the container and makes one table with one row.

docker exec g5-db psql -U postgres -c "CREATE TABLE notes (id INT PRIMARY KEY, text TEXT); INSERT INTO notes VALUES (1, 'hello');"

Example

docker volume create g5-pgdata
docker run -d --name g5-db -v g5-pgdata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=secret postgres:16-alpine >/dev/null
sleep 5
docker exec g5-db psql -U postgres -c "CREATE TABLE notes (id INT PRIMARY KEY, text TEXT); INSERT INTO notes VALUES (1, 'hello');"
docker exec g5-db psql -U postgres -c "SELECT * FROM notes;"
docker stop g5-db >/dev/null
docker rm g5-db >/dev/null
docker run -d --name g5-db2 -v g5-pgdata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=secret postgres:16-alpine >/dev/null
sleep 5
docker exec g5-db2 psql -U postgres -c "SELECT * FROM notes;"

Key points

  • Postgres stores its data in /var/lib/postgresql/data inside the container.
  • Mount a volume at that path, and the data outlives the container.
  • Stop and remove the container, and the volume stays.
  • Start a new container on the same volume, and the rows come back.
  • Use a password from an environment variable, never in the image.

In this example, a row is read, the container is stopped and removed, and a new container starts on the same volume. The second read shows the same row. The row proves the volume kept the data past the container.

Note

Removing the volume deletes the data. Remove a volume only when the data is truly done.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What makes database rows survive a container restart?