Volumes and host folders

Named volumes, bind mounts and when to choose which.

There are two main ways to attach persistent storage. A named volume is created and stored by Docker itself: you only know its name, for example pgdata. A bind mount attaches a specific path on the host, for example the project folder. The syntax is similar: -v name:/path for a volume and -v /absolute/path:/path for a folder.

docker volume create uploads
docker run -d -v uploads:/app/uploads files-api:1.0
docker run --rm -it -v "$(pwd)":/app -w /app node:20 npm test

In the second example the project folder is mounted into the container, and the tests see fresh code without rebuilding the image. That is handy during development.

Volumes suit service data: Docker creates them with the right permissions, they do not depend on the folder layout of the server, and they work the same on Linux, Windows and macOS. Bind mounts suit development and configuration files you edit on the host. In production, bind mounts tie you to a specific server, so they are used deliberately.

There is also a more explicit form, --mount type=volume,source=uploads,target=/app/uploads. It is longer but stricter: if the host folder for a bind mount does not exist, --mount reports an error, while -v silently creates an empty folder. An empty folder on top of a needed directory is a frequent cause of the mysterious “the config is gone”.

A common mistake is to bind-mount a host folder over a directory that already has files in the image. The mounted folder hides the image's contents completely: if it is empty on the host, the application will not find its files. A named volume behaves differently: the first time an empty volume is mounted, it is filled with the contents of that directory from the image.

Practice

  1. What to choose for a database

    Where is the best place to keep database files on a production server?

    • In the container layer
    • In a named volume
    • In the host's /tmp
    • Inside the image
  2. Properties of a bind mount

    Which statements about bind-mounting a host folder are true? Mark all.

    • The mounted folder hides the image's files in that directory
    • With -v a missing host folder is created empty
    • Docker stores it in its own directory and manages its permissions
    • It is handy in development to see fresh code without rebuilding
  3. Listing volumes

    Which command lists all Docker volumes on the machine?