Docker

Persistent Data in Docker: Volumes vs Bind Mounts

The difference between named volumes and bind mounts, which one to use for databases and for code, and how to back up a volume with tar.

Persistent Data in Docker: Volumes vs Bind Mounts
Table of contents
  1. Named volumes
  2. Bind mounts
  3. Which one where?
  4. Backing up a volume
  5. Cleaning up

Containers are disposable by design: remove a container and everything written inside it goes too. Persistent data such as databases and uploads has to live outside the container’s lifecycle, and Docker gives you two main ways to do that.

Named volumes

Docker stores them under /var/lib/docker/volumes/ on the host and manages them itself. They are the best choice for database data:

volumes:
  - db_data:/var/lib/mysql

Inspect the volumes you have:

docker volume ls
docker volume inspect wordpress-demo_db_data

An important detail: docker compose down keeps volumes, but docker compose down -v deletes them as well. Make sure you have a backup before you run it.

Bind mounts

A bind mount maps a specific path on the server into the container. It suits configuration files and code you are actively working on:

volumes:
  - ./nginx.conf:/etc/nginx/nginx.conf:ro

The :ro suffix makes the file read-only inside the container, which is a good convention for configuration.

Which one where?

  • Database data and uploads → named volume
  • Configuration files and project code → bind mount

Backing up a volume

A throwaway Alpine container with tar can compress the contents of a volume and write the archive to the host:

docker run --rm \
  -v wordpress-demo_wp_data:/data:ro \
  -v $(pwd)/backup:/backup \
  alpine tar czf /backup/wp-files.tar.gz -C /data .

For databases, use a dump instead of tar; our guide to MariaDB backups has the full command.

Cleaning up

docker volume prune removes unused volumes. Since Docker 23 it only removes anonymous volumes by default; named ones need -a. More on safe cleanup in reclaiming disk space from Docker.

About the author

Omid Nikpour

Linux systems administrator focused on Docker, databases and backups. Writes about keeping services running reliably in production.

All articles by Omid Nikpour

Comments

No comments yet. For technical questions, include the details (OS version, the exact error and the command you ran) to get a precise answer.

Leave a comment