Data persistence
- Docker & Kubernetes course
- Beginner
- Lesson 49/82
- 4 min
Learn to keep data even after a container is removed.
Data persistence
A container's writable layer is removed together with the container. When you delete and recreate a database container to update it, all data is lost. Docker offers two ways for persistent data:
- Volume: storage managed by Docker (
/var/lib/docker/volumes). - Bind mount: mounting a specific folder on the host into the container.
docker run -d --name db -v pgdata:/var/lib/postgresql/data postgres:16A life independent of the container
A volume isn't deleted when the container is removed. When a new container mounts the same volume, it continues from where the data left off. That makes an image update as simple as "remove and restart with the new version":
docker rm -f db
docker run -d --name db -v pgdata:/var/lib/postgresql/data postgres:16.4
# tables and records are in placePractice A persistent database
Start a container named db from postgres:16 in the background with POSTGRES_PASSWORD=gizli; mount the pgdata volume at /var/lib/postgresql/data.
Starter code
# buraya yazExpected output
3b4c5d6e7f80
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if a database container is removed and recreated without a volume?
- The data is backed up automatically
- Nothing changes
- All data is lost Correct answer
- The data is saved into the image
Explanation: The data was in the removed container's writable layer.
2 Mount the pgdata volume at the data directory.
docker run -d ____ pgdata:/var/lib/postgresql/data postgres:16
docker run -d -v pgdata:/var/lib/postgresql/data postgres:16
Explanation: -v name:path mounts a volume.
3 Match.
| Term | Meaning |
|---|---|
writable layer |
Removed with the container |
volume |
Managed by Docker, persistent |
bind mount |
Host folder |
/var/lib/docker/volumes |
Where volumes live |