Chapter 2 · Lesson 4 of 20
Docker

Docker volumes and persistent data: named volume vs bind mount

A Docker volume is storage managed by Docker that outlives any container that uses it.

By the end you will

Keep database data in a named volume that survives removing the container.

Time
20 min
Level
Beginner
Check
4 questions
You need
  • Docker installed

To keep data after a container is removed, mount a Docker volume (or a host folder) into the container at the path where the app writes. A named volume such as -v pgdata:/var/lib/postgresql/data lives on after docker rm, and the next container that mounts it sees the same files.

How it works#

A container sees the image’s files (read-only) plus a thin writable layer on top. That layer is deleted with the container. A mount attaches storage from somewhere else into a path inside the container, and that path then survives the container.

There are two common kinds. A named volume is storage Docker creates and manages. On Linux it lives under /var/lib/docker/volumes/NAME/_data, and you refer to it only by name. A bind mount maps a folder you choose on the host into the container, so both sides see the same files.

Named volumeBind mount
Created byDocker, on first useYou, a host path
Best forData the app owns, such as a databaseConfig files, source code you edit on the host
Syntax-v pgdata:/path-v /host/path:/path
Content on first useFilled from the image’s files at that path if the volume is emptyHides the image’s files at that path

The syntax decides which kind you get: if the left side starts with / (or ./ in Compose) it is a host path, otherwise it is a volume name. A mount also covers what the image had at that path, so mount only where you mean to.

A worked example, start to finish#

Start Postgres on a volume, create a table, destroy the container and look again.

bash
docker run -d --name db -v pgdata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=change-me postgres:16
docker exec db psql -U postgres -c "CREATE TABLE t (id int);"
docker rm -f db
docker run -d --name db -v pgdata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=change-me postgres:16
docker exec db psql -U postgres -c "\dt"

Wait a few seconds after the second docker run so the server is ready. The last command lists the table t. The container was new, the data was not: it sat in the volume the whole time. Run the same steps without the -v flag and the table is gone.

Step 1: Start a container with a volume#

bash
docker run -d --name db -v pgdata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=change-me postgres:16

-v pgdata:/var/lib/postgresql/data mounts the volume pgdata at Postgres’s data folder. Docker creates the volume the first time.

What you should see: a container ID, and docker ps shows db as Up.

Step 2: Check the volume#

bash
docker volume ls
docker volume inspect pgdata

What you should see: pgdata in the list with driver local, and JSON with a Mountpoint on the host and "Name": "pgdata".

Step 3: Prove the data survives#

bash
docker rm -f db
docker run -d --name db -v pgdata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=change-me postgres:16

-f force-removes the container even while it runs. The volume is untouched. The new container starts with the old data, so Postgres starts without initialising a new database.

What you should see: docker logs db mentions that the database directory already contains a database and skips initialisation.

Step 4: Back it up#

bash
docker run --rm -v pgdata:/data -v "$PWD":/backup alpine tar czf /backup/pgdata.tgz -C /data .

This starts a throwaway Alpine container with the volume at /data and your current folder at /backup, archives the volume into pgdata.tgz, and removes itself (--rm). For a running database, a dump with pg_dump (see Back up a Postgres database in Docker) is safer than copying files, because files copied mid-write can be inconsistent. Stop the database first if you must copy files.

What you should see: a pgdata.tgz file in your current folder.

Check it worked#

docker volume ls lists pgdata before and after docker rm -f db. After the second docker run, docker volume ls still shows one pgdata, not two. ls -lh pgdata.tgz shows a non-empty archive.

Edge cases and gotchas#

  • Anonymous volumes pile up. -v /var/lib/postgresql/data (no name) creates a volume with a random ID each time. They keep data but are hard to find, and docker volume ls fills with hash names. Always name volumes you care about.
  • A bind mount hides the image’s files. Mounting an empty host folder over /app makes the container see an empty /app. Only an empty named volume is filled from the image on first use.
  • Permissions on bind mounts. The container’s user is a numeric ID, and it must be allowed to write the host folder. Fix with chown on the host, or run the container as a user ID that owns the folder.
  • Docker may create a missing host path as root. With -v /host/new:/data, a missing folder is created owned by root. The --mount form fails instead, which is stricter.
  • Initial settings apply only once. Variables such as POSTGRES_PASSWORD are read only when the volume is empty. A reused volume keeps its old data and old password.
  • A volume in use cannot be removed. docker volume rm pgdata fails while a container (even a stopped one) uses it. Remove the container first.
  • Clean-ups can delete volumes. docker volume prune (see Free disk space with docker prune) removes volumes no container uses. A volume whose container you just removed counts as unused.

Troubleshooting#

SymptomLikely causeFix
Data gone after recreating the containerNo volume, or a different volume name or pathCheck docker inspect db under Mounts, and use the same name
volume is in useA container still references the volumedocker rm that container, then remove the volume
permission denied writing to a mounted folderUID of the container user cannot write the host folderchown the folder, or run with a matching --user
Mounted folder looks empty inside the containerThe mount hides the image’s content, or the host path is wrongCheck the host path and the target path
invalid mount config for type "bind": bind source path does not exist--mount with a missing host folderCreate the folder first
Backup archive is tiny or emptyThe wrong volume name, so Docker made a new empty volumeCheck docker volume ls and the name in -v
docker volume ls shows many hash-named volumesAnonymous volumes created by -v /path or by the imageName the volumes you care about, and remove old ones with care
Compose data seems missing after you moved the projectCompose prefixes the volume with the project name, so a new folder name means a new empty volumeKeep the project name, or set name: on the volume
Restore from pgdata.tgz gives an empty folderThe archive path or -C option was wrongList it with tar tzf pgdata.tgz before restoring

Real-world scenario#

A small team runs a wiki in Docker. The first version stores pages inside the container, and an upgrade (docker rm plus a new image) wipes every page on a Friday afternoon. The fix is two lines: a named volume on the wiki’s data folder, and the same volume name in the new docker run.

The following week they add a nightly backup. A cron job runs the Alpine tar command from step 4 against the volume, then copies the archive to another machine. They also read Backups and the 3-2-1 rule and test one restore. The next upgrade is boring: stop, remove the container, pull the new image, start it on the same volume.

Quick reference#

TaskCommand
Create a volumedocker volume create pgdata
List and inspectdocker volume ls, docker volume inspect pgdata
Mount a named volume-v pgdata:/var/lib/postgresql/data
Mount a host folder-v /srv/app/config:/etc/app:ro
Back up a volumedocker run --rm -v pgdata:/data -v "$PWD":/backup alpine tar czf /backup/pgdata.tgz -C /data .
Remove a volume (data loss)docker volume rm pgdata

Security and safety notes#

  • docker volume rm, docker volume prune and docker compose down -v delete data permanently. Back up first.
  • Do not copy the files of a running database as your only backup. Use pg_dump or stop it first.
  • Keep backups on another machine as well as on the same disk. See Backups and the 3-2-1 rule.

Next#

Turn your own app into an image with Write your first Dockerfile.

Try it: Prove a volume keeps data

Start Postgres with a named volume, inspect it, remove the container and start it again.

practice, nothing runs on your machine

Want a real machine? Free browser labs: Killercoda Play with Docker

Check what you learned4 questions
1You run docker rm -f db on a container that used the volume pgdata. What happens to the data?
2When should you pick a bind mount instead of a named volume?
3Which is safer for backing up a running database?
4You bind mount an empty host folder over a path that holds files in the image. What does the container see there?

Frequently asked questions

Volume or bind mount?

Use a named volume for data an app owns, such as a database. Use a bind mount when you need to edit files on the host, such as config or source code.

Where is a named volume stored on the server?

Under /var/lib/docker/volumes/NAME/_data on a Linux host. Use docker volume inspect NAME to see the exact path. Treat it as Docker's, and read or copy it with a container or backup command instead of editing it by hand.

Why does my container get permission denied on a bind mount?

The user inside the container is a numeric user ID, and it must be allowed to read and write the host folder. Match ownership with chown, or run the container as a user that owns the folder.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios