Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 111 ยท Data and Volumes

Volumes

Master Docker volumes: docker volume create, ls, inspect, rm and prune, named versus anonymous volumes, -v versus --mount, sharing, read-only mounts and the volume lifecycle.

A volume is storage that Docker creates and manages for you, separate from any container. You give it a name, mount it into a container at some path, and from then on whatever the container writes there survives the container. Remove the container, start a new one, mount the same volume, and the data is waiting. For databases, uploads, caches you do not want to rebuild and anything else your application owns, volumes are the default answer.

This lesson covers the whole life of a volume: creating and listing it, the two ways to mount it (-v and --mount), what happens when a new volume meets an image that already has files at that path, sharing a volume between containers, mounting read-only or just one sub-folder, and removing volumes safely. Every command was run against a real Docker Engine. If you have not read Container Storage yet, start there to see why the container's own filesystem is not good enough.

Creating and listing volumes

CONSOLE
$ docker volume create pgdata
pgdata
$ docker volume create --label project=shop appfiles
appfiles
$ docker volume ls
DRIVER    VOLUME NAME
local     appfiles
local     pgdata

The local driver stores data on the machine that runs the Docker daemon. (Other drivers can store it on network storage; see Volume Drivers and Remote Storage.) Labels are free-form key/value tags you can filter on later. docker volume inspect shows everything Docker knows:

CONSOLE
$ docker volume inspect appfiles
[
    {
        "CreatedAt": "2026-10-23T14:52:08Z",
        "Driver": "local",
        "Labels": {
            "project": "shop"
        },
        "Mountpoint": "/var/lib/docker/volumes/appfiles/_data",
        "Name": "appfiles",
        "Options": null,
        "Scope": "local"
    }
]

The Mountpoint is where the files really are, on the Docker host. On a Linux server that is a real directory you could look at as root. On Docker Desktop (Windows, macOS) the daemon runs inside a small virtual machine, so that path is inside the VM and not visible from your normal file explorer. That is on purpose: treat the mount point as an implementation detail. Read and write volume contents through containers, as you will see in Backup and Restore, not by poking at /var/lib/docker.

You rarely need to create a volume by hand. Docker creates a named volume the first time a container mounts it:

CONSOLE
$ docker run --rm -v autovol:/d alpine:3.22 true
$ docker volume ls --filter name=autovol -q
autovol

Creating explicitly is still useful to set labels or driver options before first use, and it makes Compose-style infrastructure scripts clearer.

Mounting: -v and --mount

Docker offers two syntaxes that do the same job for volumes.

-v / --volume is short and has up to three colon-separated fields: source:destination[:options].

Terminal
docker run -d --name db -v pgdata:/var/lib/postgresql/data postgres:17-alpine
docker run --rm -v shared:/shared:ro alpine:3.22 cat /shared/msg.txt

--mount is longer, with explicit key=value pairs separated by commas. It is clearer to read and supports more options:

Terminal
docker run -d --name db \
  --mount type=volume,src=pgdata,dst=/var/lib/postgresql/data \
  postgres:17-alpine
-v form Meaning
-v pgdata:/data Named volume pgdata at /data
-v /data Anonymous volume (random name) at /data
-v pgdata:/data:ro Named volume, mounted read-only
-v ./site:/site or -v /abs/path:/site Not a volume: a bind mount (see Bind Mounts)

The rule for -v: if the first field is a plain name, it is a volume; if it looks like a path (starts with /, ./ or a drive letter), it is a bind mount. With --mount you always state type=volume, type=bind or type=tmpfs, so there is no guessing. The documentation and this course prefer --mount when explaining and -v when typing quickly. Use whichever your team agrees on, but know both when reading other people's commands.

Proving that data survives: a database

The classic example is a database. We start PostgreSQL with a named volume on its data directory, insert two rows, delete the container, start a brand new container on the same volume, and read the rows back:

CONSOLE
$ docker run -d --name db -e POSTGRES_PASSWORD=secret -v pgdata:/var/lib/postgresql/data postgres:17-alpine
$ docker exec db psql -U postgres -c "CREATE TABLE notes (id serial primary key, body text); INSERT INTO notes (body) VALUES ('survives restarts'), ('survives removal');"
CREATE TABLE
INSERT 0 2
$ docker rm -f db
db
$ docker run -d --name db2 -e POSTGRES_PASSWORD=secret -v pgdata:/var/lib/postgresql/data postgres:17-alpine
$ docker exec db2 psql -U postgres -c "SELECT * FROM notes;"
 id |       body        
----+-------------------
  1 | survives restarts
  2 | survives removal
(2 rows)
$ docker logs db2 2>&1 | grep -i skipping
PostgreSQL Database directory appears to contain a database; Skipping initialization

(The first psql right after docker run may fail for a second or two while the server starts; retry, or poll with pg_isready.) The second container found an existing database in the volume and skipped initialization, which is exactly the behavior you want. The container was disposable; the data was not.

What happens if you forget the volume? The official Postgres image declares VOLUME /var/lib/postgresql/data, so Docker silently creates an anonymous volume instead of using the writable layer:

CONSOLE
$ docker run -d --name db3 -e POSTGRES_PASSWORD=secret postgres:17-alpine
$ docker exec db3 psql -U postgres -c "SELECT * FROM notes;"
ERROR:  relation "notes" does not exist
LINE 1: SELECT * FROM notes;
                      ^
$ docker inspect -f '{{range .Mounts}}{{.Type}} len={{len .Name}} {{.Destination}}{{end}}' db3
volume len=64 /var/lib/postgresql/data

The table is not there (a fresh volume, so a fresh database), and the mount is a volume with a 64-character name. The data would survive docker stop, but nobody would recognize that volume tomorrow. That is why you name it. docker rm -v db3 removes the container and its anonymous volume in one go.

Named versus anonymous volumes

Named volume Anonymous volume
Created by -v name:/path, docker volume create name -v /path, or an image's VOLUME with nothing mounted
Name You choose 64 random hex characters
Removed by docker rm No No, unless docker rm -v (or --rm at run time)
Removed by docker volume prune Only with -a Yes, when no container uses it
Good for Data you care about Throwaway scratch space

Anonymous volumes are not wrong; they are a safety net for forgotten mounts. But if you care about the data, give it a name.

What a new volume contains: the copy-up

When you mount an empty, new named volume on a path that already holds files in the image, Docker first copies those files into the volume. The container then sees the same content it would have seen without the mount, and later changes persist. Mount a fresh volume over nginx's web root:

CONSOLE
$ docker run --rm -v html:/usr/share/nginx/html nginx:alpine ls /usr/share/nginx/html
50x.html
index.html
$ docker run --rm -v html:/h alpine:3.22 ls /h
50x.html
index.html

The second container (a different image, Alpine) sees the nginx default pages: they were copied into the volume the first time. This is how database images initialize an empty data directory and how you can seed a volume from an image.

Two rules govern it. The copy happens only if the volume is empty; a volume that already has files is never overwritten. And it applies to volumes, not to bind mounts: a bind mount shows exactly the host folder, hiding whatever the image had there. To switch the copy-up off, add the volume-nocopy option to --mount:

CONSOLE
$ docker run --rm --mount type=volume,src=empty,dst=/usr/share/nginx/html,volume-nocopy nginx:alpine ls -A /usr/share/nginx/html | wc -l
0

The directory is empty because nothing was copied. Copy-up also copies ownership and permissions, which is why a volume mounted on a directory owned by an unprivileged user in the image is writable by that user (see Users and Permissions).

Sharing a volume between containers

Several containers may mount the same volume, at the same time or one after another. A producer writes, a consumer reads; a web container serves files that a worker generates. Mounting read-only protects the data from the readers:

CONSOLE
$ docker run --rm -v shared:/shared alpine:3.22 sh -c 'echo "written by writer" > /shared/msg.txt'
$ docker run --rm -v shared:/shared:ro alpine:3.22 sh -c 'cat /shared/msg.txt; echo more >> /shared/msg.txt'
written by writer
sh: can't create /shared/msg.txt: Read-only file system
$ docker run --rm --mount type=volume,src=shared,dst=/shared,readonly alpine:3.22 touch /shared/x
touch: /shared/x: Read-only file system

:ro (in -v) and readonly (in --mount) are the same thing. Make it a habit: containers that only need to read should get read-only mounts.

Sharing a volume does not make concurrent writes safe. Two processes appending to the same file or two database servers using the same data directory will corrupt data, because Docker does not coordinate access. Share volumes for hand-off (one writer, many readers), not for simultaneous editing, and never point two database containers at one data directory.

Mounting just one folder: volume-subpath

Sometimes one volume holds several areas and a container should see only one of them. --mount accepts volume-subpath to mount a sub-directory of the volume:

CONSOLE
$ docker run --rm -v users:/d alpine:3.22 sh -c 'mkdir -p /d/alice /d/bob; echo a > /d/alice/f.txt; echo b > /d/bob/f.txt'
$ docker run --rm --mount type=volume,src=users,dst=/home/me,volume-subpath=alice alpine:3.22 sh -c 'ls /home/me; cat /home/me/f.txt'
f.txt
a

The container sees only alice's files, mounted at /home/me; bob is invisible to it. The sub-directory must already exist.

Labels, options and the local driver

--mount can set labels on a volume it creates (volume-label=...), and docker volume create can pass driver options. The built-in local driver is flexible: with type=tmpfs it creates a volume backed by memory (useful for tests), and the same mechanism mounts NFS or other filesystems (see Volume Drivers and Remote Storage).

CONSOLE
$ docker run --rm --mount type=volume,src=labelled,dst=/d,volume-label=team=blue alpine:3.22 true
$ docker volume inspect -f '{{.Labels}}' labelled
map[team:blue]
$ docker volume create --driver local --opt type=tmpfs --opt device=tmpfs --opt o=size=8m,uid=1000 memvol
memvol
$ docker run --rm -v memvol:/m alpine:3.22 sh -c 'df -h /m | tail -1; ls -ldn /m'
tmpfs                     8.0M         0      8.0M   0% /m
drwxrwxrwt    2 1000     0               40 ... /m
$ docker volume inspect -f '{{json .Options}}' memvol
{"device":"tmpfs","o":"size=8m,uid=1000","type":"tmpfs"}

The volume is a real 8 MB tmpfs owned by UID 1000. Its contents vanish when the last container using it stops, so this is a niche tool; the point is that --opt hands arbitrary mount options to the driver.

Inspecting, sizing and finding users of a volume

How big is a volume, and who uses it?

CONSOLE
$ docker run --rm -v shared:/shared alpine:3.22 du -sh /shared
8.0K	/shared
$ docker system df -v | grep -E "VOLUME NAME|^shared"
VOLUME NAME                                                        LINKS     SIZE
shared                                                             0         18B
$ docker run -d --name who -v users:/d alpine:3.22 sleep 100
$ docker ps -a --filter volume=users --format '{{.Names}} {{.Status}}'
who Up 1 second

LINKS in docker system df -v is the number of containers (running or stopped) that reference the volume; 0 means nothing uses it. The filter docker ps -a --filter volume=NAME lists those containers, and docker volume ls --filter dangling=true lists the volumes nobody uses.

CONSOLE
$ docker volume ls --filter dangling=true

(Output is the list of unused volumes on your machine, named and anonymous alike.) Run this before you clean up, never after.

Copying a volume

There is no docker volume cp. Use a throwaway container that mounts both volumes (the source read-only):

CONSOLE
$ docker run --rm -v users:/from:ro -v users-copy:/to alpine:3.22 cp -a /from/. /to/
$ docker run --rm -v users-copy:/v alpine:3.22 find /v -type f
/v/bob/f.txt
/v/alice/f.txt

cp -a preserves ownership and permissions, and the trailing /. copies hidden files too. The same helper-container idea is the basis of backups and migrations in Backup and Restore.

The lifecycle: when are volumes removed?

Volumes outlive containers by design, so removal is always explicit. Here is what each command does to them:

Command Effect on volumes
docker stop, docker rm Nothing. Named and anonymous volumes stay.
docker rm -v NAME Also removes the container's anonymous volumes
docker run --rm Removes the container and its anonymous volumes when it exits
docker compose down Nothing; volumes stay
docker compose down -v Removes the named volumes declared in the Compose file, plus anonymous ones
docker volume rm NAME Removes that volume, if no container uses it
docker volume prune Removes unused anonymous volumes (-a: unused named volumes too)

A volume that a container still references cannot be removed, running or not:

CONSOLE
$ docker run -d --name holder -v scratch:/d alpine:3.22 sleep 300
$ docker volume rm scratch
Error response from daemon: remove scratch: volume is in use - [5bdde506d53c...]
$ docker stop holder
$ docker volume rm scratch
Error response from daemon: remove scratch: volume is in use - [5bdde506d53c...]
$ docker rm holder
$ docker volume rm scratch
scratch
$ docker volume rm scratch
Error response from daemon: get scratch: no such volume

The error names the container ID that holds it (shortened here). Stopping is not enough, because the stopped container could be started again and would need its volume; only removing the container frees the volume. Removing a volume that does not exist is an error, and removing one that exists is permanent: there is no recycle bin.

Give every important volume a descriptive name and a label such as keep=yes, then use --filter label!=keep in cleanup commands. See Cleaning Up.

Volumes in Compose and in practice

In a Compose file, volumes are declared once and referenced by services; Compose prefixes the name with the project name (myproject_pgdata):

YAML
services:
  db:
    image: postgres:17-alpine
    environment:
      POSTGRES_PASSWORD: secret
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:

Chapter Docker Compose covers this in detail. A few practical rules:

  1. One volume per concern, named for what it holds (pgdata, uploads, redis-data), not for the container.
  2. Back up what matters. A volume protects against container removal; it does not protect against disk failure, accidental volume rm, or a bad migration.
  3. Do not mount a volume over a directory that holds your application code unless you mean to. The volume's content wins after the first copy-up, so a rebuilt image's new code would be hidden by the old copy in the volume. This is a classic cause of "I deployed, but nothing changed".
  4. Mind the permissions on volumes your non-root user writes to.
  5. Do not store secrets in plain volumes if other containers can mount them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You run docker run -v data:/app/data myimage, and no volume named data exists. What happens?

    A plain name before the colon means a named volume, and Docker creates it on first use. Only paths (starting with /, ./ or a drive letter) are treated as bind mounts.
  2. 2. A new, empty named volume is mounted over /usr/share/nginx/html, a path that contains files in the image. What does the container see?

    Docker copies the image's content at that path into a new empty volume (copy-up). A bind mount behaves differently and hides the image's files; volume-nocopy disables the copy.
  3. 3. Why does docker volume rm myvol fail even though the container using it is stopped?

    A container (running or stopped) keeps its references to the volumes it was created with, because it could be started again. Remove the container with docker rm, and then the volume can go.
  4. 4. Which mount option makes a volume read-only for one container?

    :ro in -v and readonly in --mount mount the volume read-only for that container. The container's --read-only flag affects the root filesystem, not volumes.
  5. 5. What is the best way to see what is stored in a volume on Docker Desktop for Windows?

    The Mountpoint is inside Docker Desktop's virtual machine, not on your Windows disk. A helper container (for example docker run --rm -v vol:/v alpine ls -l /v) is the portable way to look inside.

Summary

  • A volume is Docker-managed storage that outlives containers. Create it explicitly with docker volume create, or let -v name:/path create it on first use.
  • -v source:dest[:ro] is the short syntax; --mount type=volume,src=...,dst=... is explicit and supports readonly, volume-subpath, volume-nocopy and volume-label.
  • Anonymous volumes (random names) appear when an image declares VOLUME and you mount nothing. Name your volumes.
  • A new, empty named volume is pre-filled from the image's files at that path (copy-up), including ownership. An already filled volume is never overwritten.
  • Share volumes for hand-off with read-only mounts for readers; never let two writers (or two databases) use the same files.
  • Volumes are removed only on purpose: docker volume rm, docker rm -v, docker compose down -v or prune. A volume used by any container, even a stopped one, cannot be removed, and removal is permanent.
  • Look inside volumes with helper containers, not by browsing /var/lib/docker.

Next: Bind Mounts