BuildBot

Containers from Scratch

Volumes & data

Lesson 3 of 5

What you'll learn

  • Understand why writes to a container's filesystem vanish on recreate
  • Distinguish named volumes from bind mounts
  • See how a volume keeps data alive across container replacements

A container writes to its writable layer, which is destroyed when the container is removed. Recreate the container and that data is gone. To persist anything — a database, uploads, logs — you mount storage that lives outside the container.

There are two kinds:

  • Named volume — Docker-managed storage, ideal for databases. Survives container removal.
  • Bind mount — a host directory mapped into the container, great for live-editing source in development.
# docker-compose.yml
services:
  db:
    image: postgres:16
    volumes:
      - dbdata:/var/lib/postgresql/data   # named volume: persists
  app:
    build: .
    volumes:
      - ./src:/app/src                     # bind mount: host <-> container

volumes:
  dbdata:

Recreate the container, keep the data

When you run docker compose up after a rebuild, the container is replaced — but anything written to a mounted volume path stays put. Write to a non-volume path and it dies with the old container.

No volume, no persistence

Database containers without a volume look fine until the first recreate, then the data is gone. Always mount a named volume at the database's data directory before you trust it with anything.

Data lost without a volume, kept with one

Run it. The same write survives a container recreate only when it lands in a volume. Compare both containers.

Loading editor…

Next: how containers find and talk to each other over a network.