CodeBlanks Logo Icon CodeBlanks

Challenge - Volume

Run a database with a volume for persistent data.

Challenge: a safe update with a volume

To move a database image to a new version, the container is removed and recreated with the same volume. But a backup is taken first; if something goes wrong you go back to the backup:

# 1. backup
docker run --rm -v pgdata:/veri:ro -v "$PWD":/yedek alpine tar czf /yedek/pgdata.tar.gz -C /veri .
# 2. replace
docker rm -f db
docker run -d --name db -e POSTGRES_PASSWORD=gizli -v pgdata:/var/lib/postgresql/data postgres:16.4
# 3. check
docker logs --tail 5 db

Practice Back up

Write the command that, in an alpine container deleted when done, mounts pgdata read-only at /veri and the current folder ("$PWD") at /yedek, and runs tar czf /yedek/pgdata.tar.gz -C /veri .; then show the created file with ls -lh pgdata.tar.gz.

Starter code

terminal
# buraya yaz

Sample solution

terminal
docker run --rm -v pgdata:/veri:ro -v "$PWD":/yedek alpine tar czf /yedek/pgdata.tar.gz -C /veri .
ls -lh pgdata.tar.gz

Expected output

-rw-r--r-- 1 root root 6.1M Nov  3 11:42 pgdata.tar.gz

Practice Upgrade the version

Write three commands: force-remove the db container; start a container named db from postgres:16.4 in the background with POSTGRES_PASSWORD=gizli and the pgdata volume mounted at /var/lib/postgresql/data; show the last 5 log lines.

Starter code

terminal
# buraya yaz

Sample solution

terminal
docker rm -f db
docker run -d --name db -e POSTGRES_PASSWORD=gizli -v pgdata:/var/lib/postgresql/data postgres:16.4
docker logs --tail 5 db

Expected output

db
8f90a1b2c3d4
PostgreSQL Database directory appears to contain a database; Skipping initialization
LOG:  database system is ready to accept connections

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When the new container mounts the same pgdata volume, what happens if POSTGRES_PASSWORD is changed?

  • Nothing; the variable is only used for first setup on an empty data directory Correct answer
  • The password is updated
  • The data is deleted
  • The container doesn't start

Explanation: In an existing database, the password is changed with SQL (ALTER USER).

2 Extract the backup back into the volume.

Question
docker run --rm -v pgdata:/veri -v "$PWD":/yedek alpine tar ____ /yedek/pgdata.tar.gz -C /veri
Answer
docker run --rm -v pgdata:/veri -v "$PWD":/yedek alpine tar xzf /yedek/pgdata.tar.gz -C /veri

Explanation: x extracts, c creates.

3 Match.

Term Meaning
tar czf Take a backup
tar xzf Restore
docker rm -f db Remove the old container
postgres:16.4 New version

All lessons in Beginner