DockerIntermediate

Docker Volumes Guide: Managing Data in Containers

8 min read

TL;DR

Learn how to effectively manage data in Docker containers using volumes, bind mounts, and tmpfs mounts, with best practices for data persistence and sharing.

Docker Volumes Guide: Managing Data in Containers

Executive Summary

A container's writable layer is the wrong place for data you care about: it is tied to that container, it is slower than native storage, and it disappears when the container is removed. Docker gives you three alternatives: volumes, bind mounts, and tmpfs mounts. This guide explains how each works, how to choose between them, and how to operate them safely: naming and organising volumes, backing them up and restoring them with a throwaway container, sharing data between containers, using volume drivers and NFS where shared storage is genuinely required, and cleaning up without deleting something production needed. After reading, you should be able to design the storage for a Compose stack and defend each choice.

Why This Matters

Data loss in containerised systems rarely comes from exotic failures. It comes from a database writing into a container layer that a routine docker compose down or an over-eager prune deleted, from a bind mount that silently pointed at the wrong host directory on a new machine, or from a backup that was never tested and turns out to be a tarball of an inconsistent, half-written database. Storage decisions also have a security dimension: a read-write bind mount of a host directory gives the container, and anyone who compromises it, read-write access to that part of the host. Getting storage right is unglamorous and entirely determinative of whether containers are safe for stateful work.

Core Concepts

The Three Mount Types

  • Volumes are managed by Docker, stored in Docker's area on the host, and are the default choice for persistent data. They work identically across operating systems, can be backed by volume drivers, and are not tied to the host's directory layout.
  • Bind mounts map a specific host file or directory into the container. They are ideal for development, where you want the container to see your working tree, and for injecting configuration. They couple the stack to the host's filesystem and inherit its permissions and risks.
  • tmpfs mounts live in host memory only. Nothing persists, which is exactly the point for scratch space and sensitive intermediate data.
  • Named Volumes in Practice

    Declare volumes at the top level of the Compose file and reference them by name. Named volumes survive container replacement, image updates, and stack redeploys; only an explicit volume removal deletes them.

    version: '3.8'
    services:
      db:
        image: postgres:14
        volumes:
          - postgres_data:/var/lib/postgresql/data
        environment:
          POSTGRES_PASSWORD: example
    
    volumes:
      postgres_data:
        name: my_postgres_data
        driver: local
        driver_opts:
          type: none
          device: /data/postgres
          o: bind

    Anonymous volumes, created when a Dockerfile declares a VOLUME and you do not name one, are the main source of mystery data and of dangling volumes later. Name everything you intend to keep.

    Bind Mounts for Development

    The standard development pattern mounts source code from the host while keeping installed dependencies inside a named volume, so host and container dependency trees never fight:

    version: '3.8'
    services:
      app:
        image: node:18-alpine
        volumes:
          - ./src:/app/src
          - ./package.json:/app/package.json
          - node_modules:/app/node_modules
        working_dir: /app
        command: npm run dev
    
    volumes:
      node_modules:

    Treat this pattern as development-only. In production, code belongs in the image, where it is versioned, scanned, and identical on every host.

    Sharing Data Between Containers

    Multiple containers can mount the same volume, which suits patterns such as a backend generating files that a web server serves:

    version: '3.8'
    services:
      web:
        image: nginx
        volumes:
          - shared_data:/usr/share/nginx/html
    
      backend:
        image: node:18-alpine
        volumes:
          - shared_data:/app/public
    
    volumes:
      shared_data:

    Shared volumes are shared filesystems, with everything that implies: concurrent writers need the application's own coordination, and a volume is not a message queue. If containers need to exchange work rather than files, use a queue or an API and keep volumes for genuinely file-shaped data.

    Backup and Restore

    Volumes are backed up by running a temporary container that mounts the volume and archives it to a directory you control:

    #!/bin/bash
    # Backup volume data
    docker run --rm \
      --volumes-from source_container \
      -v $(pwd):/backup \
      alpine \
      tar czf /backup/volume_backup.tar.gz /data

    Restore is the same operation in reverse into a fresh volume. Two warnings matter more than the commands. First, archive a quiesced volume: stop the writer, or use the database's own dump tool, because a tarball of a live database directory is a corrupt backup with good compression. Second, test restores on a schedule. A backup you have never restored is a hypothesis.

    Volume Drivers and Network Storage

    The local driver covers most needs, including NFS mounts via driver options when several hosts must share one volume:

    version: '3.8'
    services:
      app:
        image: myapp
        volumes:
          - nfs_data:/data
    
    volumes:
      nfs_data:
        driver: local
        driver_opts:
          type: nfs
          o: addr=192.168.1.1,rw
          device: ":/path/to/dir"

    Third-party drivers exist for distributed and cloud storage. Choose them deliberately: network filesystems change latency and failure behaviour, and a database on NFS is a decision to make with measurements, not by default.

    tmpfs for Scratch and Sensitive Data

    version: '3.8'
    services:
      app:
        image: myapp
        tmpfs:
          - /tmp
          - /run
        volumes:
          - type: tmpfs
            target: /app/cache
            tmpfs:
              size: 100M

    Size every tmpfs mount. An unbounded tmpfs is a way for a container to consume host memory while looking like it uses no disk.

    Inspection, Cleanup, and Security

    # Inspect volume details
    docker volume inspect my_volume
    
    # Check volume usage
    docker system df -v
    
    # List unused volumes
    docker volume ls -f dangling=true

    Cleanup is where data loss happens, so make it a reviewed operation: list dangling volumes, confirm none belong to a stopped-but-important stack, and only then prune. On the security side, mount volumes read-only wherever the application only reads, and prefer volumes over bind mounts in production so container access to the host filesystem stays scoped to Docker-managed storage.

    version: '3.8'
    services:
      app:
        image: myapp
        volumes:
          - type: volume
            source: secure_data
            target: /data
            read_only: true
        security_opt:
          - no-new-privileges:true
    
    volumes:
      secure_data:

    Decision Framework

    SituationRecommendation
    Database or application state in productionNamed volume
    Live-reload developmentBind mount for source, named volume for dependencies
    Scratch space, caches, sensitive intermediatestmpfs with an explicit size limit
    Configuration files from the hostBind mount, read-only
    Data shared by containers on one hostOne named volume mounted by each consumer
    Data shared across hostsNFS-backed volume or a distributed driver, after latency testing
    Anything you cannot afford to loseNamed volume plus tested backups, or a managed data service

    Implementation Checklist

  • [ ] No production data lives in a container's writable layer
  • [ ] Every persistent volume is named and declared in the Compose file
  • [ ] Bind mounts are confined to development and read-only configuration
  • [ ] tmpfs mounts have explicit size limits
  • [ ] Backups are taken from a quiesced state or with the database's own dump tool
  • [ ] A restore has been performed and verified, not just scheduled
  • [ ] Volumes are mounted read-only wherever writes are not required
  • [ ] Pruning dangling volumes is a reviewed step, never an unattended cron job against production
  • Trade-offs

    Volumes hide data inside Docker's storage area, which is safe but opaque; operators used to browsing a filesystem need new habits and tooling. Bind mounts are transparent and fast on Linux but perform poorly through the file-sharing layer on macOS and Windows development machines. Network-backed volumes enable sharing at the cost of latency and a new failure domain. Backups via tar containers are simple and portable but are file-level copies; large or busy datasets eventually need application-aware backup tooling.

    When Not to Use

  • Bind mounts for production application code: you lose image versioning, scanning, and identical behaviour across hosts. Build the code into the image.
  • A shared volume as an integration mechanism between services: concurrent file access is a fragile contract. Use an API, a queue, or a database.
  • Volumes for data with real durability requirements and no backup plan: a volume on one host is one disk failure away from gone. Use replicated storage or a managed database service.
  • Conclusion

    The rule is simple: data outlives containers, so store it in something that does too. Named volumes for state, bind mounts for development and configuration, tmpfs for the ephemeral, and backups you have actually restored. Most container data-loss stories are one of those four decisions made carelessly.

    Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.