Skip to content

DevOps Operations / Docker Compose · Step 4 of 6

Lesson: VolumesSwitch
← DevOps Operations

Delivery and containers

Volumes

Keep data when containers are replaced, using named volumes and bind mounts.

Files written inside a container live in its writable layer. When the container is removed, that layer is removed too. A volume stores data outside the container so that a replacement can use it again.

Named volumes

A named volume is managed by Docker. Declare it at the top level, then mount it in a service:

yaml
services:
  db:
    image: postgres:17
    environment:
      POSTGRES_PASSWORD: example
    volumes:
      - dbdata:/var/lib/postgresql/data
volumes:
  dbdata:

The short syntax is SOURCE:TARGET. The target path depends on the image, so check its documentation. The official PostgreSQL image changed its volume path in version 18, which is why this example pins 17.

Compose prefixes the volume with the project name:

bash
docker volume ls
DRIVER    VOLUME NAME
local     demo_dbdata

Bind mounts

A bind mount maps a directory or file from your host into the container. A source that starts with . or / is a path:

yaml
services:
  web:
    image: nginx:alpine
    volumes:
      - ./site:/usr/share/nginx/html:ro

Edits in ./site appear in the container immediately. The ro option makes the mount read-only inside the container. A bind mount hides whatever the image already had at that path, so an empty site directory means there is no default page.

Use bind mounts for source code and configuration you edit yourself. Use named volumes for data the application owns, such as database files. File ownership matters with bind mounts, as covered in the permissions lab.

What removes a volume

bash
docker compose down

This removes containers and the project network, but keeps named volumes. Adding -v is destructive:

bash
docker compose down -v

It also deletes the named volumes declared in the file, along with anonymous volumes attached to the containers. Volumes marked external are not removed. A volume is not a backup, so copy important data somewhere else as well.

Try it

Create site/index.html with a line of text and run the bind mount example with a published port, "8080:80". Fetch the page, edit the file, and fetch it again. Then run the database example in a separate directory, use docker compose down, and confirm with docker volume ls that the volume is still there.

Check your understanding

Volumes

All 3 sections · no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.