# Keeping data: volumes, bind mounts and backups

A container's files die with it. Keep what matters in named volumes, share your code with bind mounts, use tmpfs for scratch space, and back up and restore a database volume, proving each one works.

Course: [Docker](https://devops.rajeev.pro/courses/docker), lesson 6. About 35 minutes, beginner. Source: https://devops.rajeev.pro/courses/docker/06-data-persistence

## What you will learn

- Explain why data written inside a container is lost when it is removed
- Keep database data in a named volume, and find where Docker stores it
- Recognise anonymous volumes, and why they pile up
- Share files between your machine and a container with a bind mount, read-only when possible
- Use tmpfs for scratch data that must never touch the disk
- Back up and restore a database with pg_dump, and a whole volume with tar

## The container forgets

Before persistent storage was mounted, every container wrote into its own thin writable layer. That works for
a disposable web process, but a database loses its files when the container is removed. Recreating the
container from the same image gives you a clean database, not the data from the old one.

```sh
$ docker run -d --name db -e POSTGRES_PASSWORD=devpass postgres:17-alpine
$ docker exec db psql -h 127.0.0.1 -U postgres -c "create table notes(t text); insert into notes values ('keep me');"
$ docker rm -f db && docker run -d --name db -e POSTGRES_PASSWORD=devpass postgres:17-alpine
$ docker exec db psql -h 127.0.0.1 -U postgres -c "select t from notes"
ERROR:  relation "notes" does not exist
```

The fix is to keep data **outside** the container in storage that outlives it. Docker can mount a named volume,
a host directory or a memory-only filesystem at a path inside the container. The application still reads and
writes that path, but Docker stores the data separately from the container lifecycle.

> **Figure.** Animated, two runs of postgres:17-alpine side by side. Without a volume, container 1 inserts 'keep me', which is stored in its writable layer; docker rm -f deletes the container and the data with it, so a new container 2 answers ERROR: relation notes does not exist. With -v pgdata:/var/lib/postgresql/data, the same insert is written into the named volume pgdata under /var/lib/docker/volumes; after removing container 1, the new container 2 mounts the same volume and reads 'keep me' back.
>
> The same commands twice. Only the second keeps the data, because it lives in a volume, not in the container.

| Type                                  | Lives                               | Use for                                    |
| ------------------------------------- | ----------------------------------- | ------------------------------------------ |
| **Named volume** `-v pgdata:/path`    | Docker's storage, managed by Docker | database data, anything to keep            |
| **Bind mount** `-v "$PWD"/site:/path` | an exact folder on the host         | your code during development, config files |
| **tmpfs** `--tmpfs /path`             | memory only                         | scratch and sensitive temporary files      |

Use a named volume for data that should survive replacing a container, such as a local development database.
Use a bind mount when you need a specific host directory, often for source code or configuration. Use tmpfs
for temporary data that should not be written to disk. A volume is not automatically a backup: it can still
be lost with the host or a mistaken volume deletion.

## Named volumes

```sh
$ docker volume create pgdata
$ docker run -d --name db -e POSTGRES_PASSWORD=devpass -v pgdata:/var/lib/postgresql/data postgres:17-alpine
$ docker exec db psql -h 127.0.0.1 -U postgres -c "create table notes(t text); insert into notes values ('keep me');"
$ docker rm -f db
$ docker run -d --name db -e POSTGRES_PASSWORD=devpass -v pgdata:/var/lib/postgresql/data postgres:17-alpine
$ docker exec db psql -h 127.0.0.1 -U postgres -tAc "select t from notes"
keep me
$ docker volume ls --filter name=pgdata
DRIVER    VOLUME NAME
local     pgdata
$ docker volume inspect pgdata --format '{{.Mountpoint}}'
/var/lib/docker/volumes/pgdata/_data
```

The path inside the container (`/var/lib/postgresql/data`) comes from the image's documentation. Get it wrong
and the data quietly lands in the container layer again.

### Anonymous volumes pile up

The postgres image **declares** its data folder as a volume:

```sh
$ docker image inspect postgres:17-alpine --format '{{json .Config.Volumes}}'
{"/var/lib/postgresql/data":{}}
```

So every run _without_ `-v` for that path creates a new **anonymous** volume, named by a 64-character ID. After
this lesson's experiments, `docker volume ls` here listed ten of them. They hold old data, use disk, and
survive `docker rm` unless you add `-v` to it (`docker rm -v`) or run the container with `--rm`. Lesson 12
cleans them up.

> **Video.** [Docker Volumes Demo || Docker Tutorial 13](https://www.youtube.com/watch?v=SBUCYJgg4Mk&t=136s) (TechWorld with Nana)

## Bind mounts

A **bind mount** maps an exact host folder into the container. Edit on your machine, see it inside at once:

```sh
$ mkdir -p site && echo '<h1>v1</h1>' > site/index.html
$ docker run -d --name web -p 8080:80 -v "$PWD/site":/usr/share/nginx/html:ro nginx:1.30-alpine
$ curl -s localhost:8080
<h1>v1</h1>
$ echo '<h1>v2, edited on the host</h1>' > site/index.html
$ curl -s localhost:8080
<h1>v2, edited on the host</h1>
$ docker exec web sh -c 'echo x > /usr/share/nginx/html/hack.html'
sh: can't create /usr/share/nginx/html/hack.html: Read-only file system
```

`:ro` makes it read-only inside: the container can serve the files but never change them. Use it unless the
container must write. Bind mounts are the heart of a good development setup (lesson 13), but they tie a container
to one host's folder layout and file permissions: files a container writes into a bind mount are owned by the
container's user ID, often root.

`--mount` is the longer, explicit syntax, clearer in scripts:

```sh
$ docker run --mount type=bind,src="$PWD/site",dst=/usr/share/nginx/html,readonly nginx:1.30-alpine
$ docker run --mount type=volume,src=pgdata,dst=/var/lib/postgresql/data …
```

### tmpfs: memory only

```sh
$ docker run --rm --tmpfs /scratch alpine:3.22 sh -c 'echo hi > /scratch/a && df -h /scratch | tail -1'
tmpfs                     1.8G      4.0K      1.8G   0% /scratch
```

Nothing written there ever reaches the disk, and it vanishes when the container stops: good for temporary files
that may contain secrets.

## Backups: dump, restore, prove it

A named volume protects data from container replacement, but it remains storage on the same Docker host.
Disk failure, host loss or an accidental volume removal can still destroy it. A backup is a separate copy that
you can restore after the original data is unavailable.

For a database, use its export tool so the backup represents database contents rather than a set of files
copied while they are changing. Here `pg_dump` writes SQL to a host file, and a fresh database container
imports that file. Then query the restored row to prove the dump was usable:

```sh
$ docker exec db pg_dump -h 127.0.0.1 -U postgres --clean --if-exists postgres > backup.sql
$ docker run -d --name db3 -e POSTGRES_PASSWORD=devpass -v pgrestore:/var/lib/postgresql/data postgres:17-alpine
$ docker exec -i db3 psql -q -h 127.0.0.1 -U postgres < backup.sql > /dev/null
$ docker exec db3 psql -h 127.0.0.1 -U postgres -tAc "select t from notes"
keep me
```

For any volume, a tar archive works, with the container **stopped** so files aren't changing mid-copy:

```sh
$ docker stop db
$ docker run --rm -v pgdata:/data:ro -v "$PWD":/backup alpine:3.22 tar czf /backup/pgdata.tgz -C /data .
```

The helper container mounts the volume read-only and your folder as `/backup`, writes the archive and is removed.

For raw file backups, stop the writer first or use a filesystem-aware snapshot so the files are consistent.
Store backups on another host or storage system, and restrict who can delete them. Practice restoring on a
schedule and verify application data, not just that the command exited successfully. A common mistake is
creating a backup file and never testing it; unreadable or incomplete backups are not a recovery plan.

> **A backup you haven't restored isn't a backup.** Prefer the database's own tool (`pg_dump`, `mysqldump`) over copying files: it gives a consistent snapshot while the database runs. Store backups somewhere else (another machine, object storage), and restore one into a fresh volume on a schedule, checking the data, so you know it works before the day you need it.

> **Video.** [Migrate Docker Volumes from one Host to another // backup and restore](https://www.youtube.com/watch?v=ZEy8iFbgbPA) (Christian Lempa)

## Mission: Keep a database across containers, and prove your backup

Run Postgres with a named volume, add a row, replace the container, and show the row survived. Then back up with pg_dump, restore into a brand-new volume and container, and query the restored data. Finally, remove what you created.

- You need: Docker
- You'll have: 'keep me' read back after a container replacement and after a restore

```sh
$ docker volume create pgdata
$ docker run -d --name db -e POSTGRES_PASSWORD=devpass -v pgdata:/var/lib/postgresql/data postgres:17-alpine
$ until docker exec db pg_isready -h 127.0.0.1 -U postgres >/dev/null; do sleep 1; done
$ docker exec db psql -h 127.0.0.1 -U postgres -c "create table notes(t text); insert into notes values ('keep me');"
$ docker rm -f db
$ docker run -d --name db -e POSTGRES_PASSWORD=devpass -v pgdata:/var/lib/postgresql/data postgres:17-alpine
$ until docker exec db pg_isready -h 127.0.0.1 -U postgres >/dev/null; do sleep 1; done
$ docker exec db psql -h 127.0.0.1 -U postgres -tAc "select t from notes"
keep me
$ docker exec db pg_dump -h 127.0.0.1 -U postgres --clean --if-exists postgres > backup.sql
$ docker run -d --name restored -e POSTGRES_PASSWORD=devpass -v pgrestore:/var/lib/postgresql/data postgres:17-alpine
$ until docker exec restored pg_isready -h 127.0.0.1 -U postgres >/dev/null; do sleep 1; done
$ docker exec -i restored psql -q -h 127.0.0.1 -U postgres < backup.sql > /dev/null
$ docker exec restored psql -h 127.0.0.1 -U postgres -tAc "select t from notes"
keep me
$ docker rm -f db restored && docker volume rm pgdata pgrestore
```

Two separate proofs: the data outlived a container, and the backup file alone rebuilt it in a new database. That
second one is the habit that saves you.

## Try it

- Create a table in a Postgres container, remove it, start a new one, and see the table is gone.
- Repeat with `-v pgdata:/var/lib/postgresql/data` and see the table survive.
- Run `docker volume ls` and count the volumes named with long hexadecimal IDs.
- Serve a folder with nginx through a bind mount, edit a file on your machine and reload the page.
- Add `:ro` to the bind mount and try to write a file from inside the container.
- Back up a database with pg_dump and restore it into a brand-new volume.

## Quiz

1. A Postgres container without a volume is removed and recreated. What happens to the data?
   - It is kept automatically
   - **It is gone: it lived in the old container's writable layer** (answer)
   - It moves to the image
   - It is backed up to Docker Hub
   Why: docker rm deletes the writable layer. Database data must go to a volume (-v name:/path) to outlive the container.

2. What is a named volume?
   - A folder in the image
   - **Storage managed by Docker, outside any container, that you mount with -v name:/path and that survives docker rm** (answer)
   - A Docker Hub repository
   - A network
   Why: On Linux it lives under /var/lib/docker/volumes/<name>/_data. docker volume ls lists them; docker volume rm deletes one.

3. docker volume ls shows many volumes with 64-character hex names you never created. What are they?
   - Malware
   - **Anonymous volumes: the image declares a VOLUME, and every run without -v for that path creates a new one** (answer)
   - Docker's cache
   - Backups
   Why: The postgres image declares /var/lib/postgresql/data as a volume. Use a named volume, or --rm, and prune the rest.

4. When is a bind mount the right choice?
   - For production database data
   - **For sharing a specific host folder, such as your source code during development or a config file** (answer)
   - Never
   - For secrets in images
   Why: Bind mounts point at an exact path on the host, so they depend on that host's layout and permissions. Named volumes are portable and managed by Docker.

5. Why back up a database with pg_dump instead of copying the volume while it runs?
   - pg_dump is faster
   - **Copying files under a running database can capture a half-written, inconsistent state; pg_dump produces a consistent snapshot** (answer)
   - Volumes can't be copied
   - There is no difference
   Why: A file-level copy is only safe with the database stopped. Either way, a backup counts only once you've restored it somewhere and checked the data.

## Resources

- [Docker Docs: volumes](https://docs.docker.com/engine/storage/volumes/) (Docker Docs)
- [Docker Docs: bind mounts](https://docs.docker.com/engine/storage/bind-mounts/) (Docker Docs)
- [Docker Docs: tmpfs mounts](https://docs.docker.com/engine/storage/tmpfs/) (Docker Docs)
- [PostgreSQL: pg_dump](https://www.postgresql.org/docs/17/app-pgdump.html) (PostgreSQL)
