Introduction to Volumes

Volumes are Docker-managed storage that persists data even after a container is removed.

Syntaxdocker run -v VOLUME_NAME:/path/in/container IMAGE

By default, anything a container writes lives in its writable layer and disappears when the container is deleted. To keep data, use a volume.

What is a volume?

A volume is storage managed by Docker, stored outside any single container. Multiple containers can share it, and it survives container removal.

Why prefer volumes

  • Data persists across container restarts and rebuilds.
  • Docker manages the location, so it is portable.
  • Better performance than bind mounts on Docker Desktop.

Mount a volume with the -v or --mount flag, giving a volume name and a path inside the container.

Example

Example · bash
# Create a named volume and use it for Postgres data
docker volume create pgdata
docker run -d \
  -v pgdata:/var/lib/postgresql/data \
  -e POSTGRES_PASSWORD=secret \
  --name db postgres:16

# The data survives even if you remove and recreate the container
docker rm -f db

When to use it

  • A team mounts a named volume to a PostgreSQL container so database data persists across container upgrades and restarts.
  • A DevOps engineer backs up application uploads by copying the contents of a named volume to an S3 bucket each night.
  • Two containers share a named volume so a file-processing worker can read files written by the web container.

More examples

Create and mount a named volume

Creates a Docker-managed volume and mounts it at the path where Postgres stores its data files.

Example · bash
# Create a named volume
docker volume create pgdata

# Mount it to a Postgres container
docker run -d \
  --name db \
  -v pgdata:/var/lib/postgresql/data \
  postgres:16-alpine

Share volume between two containers

Mounts the same named volume in two containers so they can exchange files through the shared directory.

Example · bash
docker volume create shared-uploads

docker run -d --name web \
  -v shared-uploads:/app/uploads myapp:latest

docker run -d --name worker \
  -v shared-uploads:/data/uploads myworker:latest

Backup a volume to a tar archive

Spins up a temporary Alpine container to tar the volume contents into the current host directory.

Example · bash
docker run --rm \
  -v pgdata:/data \
  -v $(pwd):/backup \
  alpine \
  tar czf /backup/pgdata-backup.tar.gz -C /data .

Discussion

  • Be the first to comment on this lesson.