TExcelTAD
Home › Docker Compose › Named Volumes

Named Volumes

Containers are disposable: docker compose up after a change throws the old container away and starts a fresh one. Anything the old container wrote to its own filesystem is gone. A database, an upload folder or a search index therefore needs a volume, storage that Docker manages outside the container and mounts back in every time the service starts.

This lesson covers named volumes, the kind Docker creates and owns. The next lesson covers bind mounts and tmpfs. If you have never used volumes with plain docker run, skim Docker Volumes first.

Declaring and using a volume

A named volume needs two things: an entry in the top-level volumes: section, and a mount in the service.

compose · try it yourself
services:
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: example
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:
name: demo
services:
  db:
    environment:
      POSTGRES_PASSWORD: example
    image: postgres:17
    networks:
      default: null
    volumes:
      - type: volume
        source: pgdata
        target: /var/lib/postgresql/data
        volume: {}
networks:
  default:
    name: demo_default
volumes:
  pgdata:
    name: demo_pgdata

Read the result closely, because it shows three things Compose does for you:

  • The short string pgdata:/var/lib/postgresql/data became the long syntax: type: volume, source, target.
  • The top-level pgdata got a real name, demo_pgdata: the project name, an underscore, the key. Two copies of the same app in different folders (different project names) get separate data.
  • Nothing about size or location: a named volume lives wherever the volume driver puts it (for the default local driver, under /var/lib/docker/volumes/ on the Docker host).

Forgetting the top-level declaration is the most common mistake. Compose refuses the file instead of guessing:

compose · try it yourself
services:
  db:
    image: postgres:17
    volumes:
      - pgdata:/var/lib/postgresql/data
service "db" refers to undefined volume pgdata: invalid compose project

Note: the rule of thumb for the short syntax: if the part before the first : starts with ., / or ~, it's a path on the host (a bind mount). Otherwise it's the name of a volume, which must be declared.

The long syntax and its options

The short form covers name:path and name:path:ro. Everything else needs the long form. Here a reporting job mounts only one sub-folder of a shared volume, read-only, and keeps a scratch area in an anonymous volume (no source at all):

compose · try it yourself
# $ docker compose config --volumes
# $ docker compose config
services:
  reports:
    image: alpine:3.22
    volumes:
      - type: volume
        source: shared
        target: /data/reports
        read_only: true
        volume:
          subpath: reports
          nocopy: true
      - logs:/var/log/app:ro
      - /scratch

volumes:
  shared:
    name: acme-shared
    labels:
      com.acme.team: data
  logs:
    driver: local
    driver_opts:
      type: tmpfs
      device: tmpfs
      o: size=100m
$ docker compose config --volumes
logs
shared
$ docker compose config
name: demo
services:
  reports:
    image: alpine:3.22
    networks:
      default: null
    volumes:
      - type: volume
        source: shared
        target: /data/reports
        read_only: true
        volume:
          nocopy: true
          subpath: reports
      - type: volume
        source: logs
        target: /var/log/app
        read_only: true
        volume: {}
      - type: volume
        target: /scratch
        volume: {}
networks:
  default:
    name: demo_default
volumes:
  logs:
    name: demo_logs
    driver: local
    driver_opts:
      device: tmpfs
      o: size=100m
      type: tmpfs
  shared:
    name: acme-shared
    labels:
      com.acme.team: data
Option Where Meaning
read_only: true (:ro) service mount the container can read but not write
volume.subpath service mount mount only a sub-directory of the volume
volume.nocopy: true service mount don't copy the image's files at target into a new empty volume
name: top level exact volume name, no project prefix (shared between projects!)
driver / driver_opts top level which volume plugin to use and its options (NFS, tmpfs, cloud disks…)
labels top level metadata, handy for docker volume ls --filter label=…
external: true top level the volume already exists; Compose never creates or deletes it

The anonymous /scratch volume gets a random name each time the container is recreated, so it's only useful for data you're happy to lose. And note the --volumes list: it shows the keys Compose manages, while name: changes what the volume is called on the Docker host.

Copy-on-first-mount

When an empty named volume is mounted over a directory that already has files in the image, Docker copies the image's files into the volume first. That is why mounting a volume at /usr/share/nginx/html shows the nginx welcome page instead of an empty directory, the first time. After that the volume wins: rebuilding the image with new files in that directory does not update the volume. This surprises people who put static assets in a volume and then wonder why a new release still serves old files. Use nocopy: true to turn the copy off, or don't put image content in volumes.

External volumes

Sometimes the data must outlive the project, or be shared by two projects. Create the volume once by hand (docker volume create shop-media) and mark it external:

compose · try it yourself
services:
  api:
    image: ghcr.io/acme/shop-api:2.1
    volumes:
      - media:/srv/media

volumes:
  media:
    external: true
    name: shop-media
  unused:
name: demo
services:
  api:
    image: ghcr.io/acme/shop-api:2.1
    networks:
      default: null
    volumes:
      - type: volume
        source: media
        target: /srv/media
        volume: {}
networks:
  default:
    name: demo_default
volumes:
  media:
    name: shop-media
    external: true

The external volume keeps its exact name shop-media, and Compose prints no driver or labels for it: it will only look it up. If it doesn't exist, docker compose up fails with external volume "shop-media" not found. Notice also that unused, declared but mounted by no service, simply doesn't appear in the resolved configuration.

Volume lifecycle

Volumes survive the commands that remove containers. That is the whole point, but it also means old data hangs around:

Command Containers Networks Named volumes External volumes
docker compose stop stopped kept kept kept
docker compose down removed removed kept kept
docker compose down -v removed removed removed kept
docker compose rm -v removed kept anonymous ones only kept

A small model of what each command leaves behind:

python · try it yourself
volumes = {
    "demo_pgdata":   {"external": False, "anonymous": False},
    "shop-media":    {"external": True,  "anonymous": False},
    "3f9c1e...":     {"external": False, "anonymous": True},
}

def after(command):
    kept = []
    for name, v in volumes.items():
        if v["external"]:
            kept.append(name)                      # never touched by Compose
        elif command == "down -v":
            continue                               # named + anonymous removed
        elif command == "rm -v" and v["anonymous"]:
            continue
        else:
            kept.append(name)
    return kept

for cmd in ["stop", "down", "rm -v", "down -v"]:
    print(f"docker compose {cmd:<7} -> volumes left: {', '.join(after(cmd))}")
docker compose stop    -> volumes left: demo_pgdata, shop-media, 3f9c1e...
docker compose down    -> volumes left: demo_pgdata, shop-media, 3f9c1e...
docker compose rm -v   -> volumes left: demo_pgdata, shop-media
docker compose down -v -> volumes left: shop-media

Tip: down -v is the "factory reset" for a development stack: the database starts empty again and init scripts re-run. Never put it in a production script.

Backing up a named volume

Compose has no backup command, but a throw-away container that mounts the volume and a host folder does the job. Sample session (--rm removes the helper container afterwards):

bash
$ docker compose stop db
$ docker run --rm -v demo_pgdata:/data:ro -v "$PWD":/backup alpine:3.22 \
    tar czf /backup/pgdata-2026-10-18.tgz -C /data .
$ docker compose start db

For a database, a logical dump (docker compose exec db pg_dump -U postgres app > app.sql) is usually better than copying files of a running server: it's consistent and portable between major versions.

Volumes beyond one host

The local driver stores data on the machine that runs the container. That's perfect for Compose on one host. In a cluster, a task that moves to another node won't find its data there: see Volumes in a Swarm and, in Kubernetes, Persistent Volumes.

Learn more: Bind Mounts & tmpfs · Docker Volumes · Compose Volumes & Networks

Test yourself

A service mounts pgdata:/var/lib/postgresql/data but the file has no top-level volumes: section. What happens?

  1. Compose creates an anonymous volume
  2. Compose treats pgdata as a relative bind mount
  3. Compose rejects the file: the service refers to an undefined volume
  4. Docker creates a volume called pgdata at runtime

In project shop, what is the Docker name of the volume declared as pgdata: (no options)?

  1. pgdata
  2. shop_pgdata
  3. shop-pgdata-1
  4. a random hash

Which command deletes the project's named volumes?

  1. docker compose stop
  2. docker compose down
  3. docker compose down -v
  4. docker compose restart