How to persist data with Docker volumes?

· Category: Docker

Short answer

Docker volumes are the preferred mechanism for persisting data generated by containers. They are managed by Docker, stored outside the container filesystem, and can be shared among multiple containers.

Steps

  1. Create a volume with docker volume create.
  2. Mount it with -v volume:/path in docker run.
  3. Use named volumes in Docker Compose for declarative management.

Example

docker volume create pgdata

docker run -d   --name postgres   -v pgdata:/var/lib/postgresql/data   -e POSTGRES_PASSWORD=secret   postgres:15

Docker Compose:

services:
  db:
    image: postgres:15
    volumes:
      - pgdata:/var/lib/postgresql/data
volumes:
  pgdata:

Tips

  • Use docker volume ls to list volumes and docker volume inspect for details.
  • Back up volumes by mounting them in a temporary container and archiving.
  • Use volume drivers for remote or cloud-backed storage.

Common issues

  • Data loss can occur if you delete a volume without backing it up.
  • Anonymous volumes are created automatically but are hard to identify later.
  • Permission issues arise when the container user ID does not match the host file owner.