Docker Compose — Sharing Volumes

1 minute read

Multiple services can share the same volume, enabling data exchange between containers. This page shows common patterns for sharing data.


Sharing a Named Volume

Two services mounting the same named volume:

services:
  writer:
    image: alpine
    command: sh -c "while true; do date >> /data/log.txt; sleep 5; done"
    volumes:
      - shared-data:/data

  reader:
    image: alpine
    command: sh -c "tail -f /data/log.txt"
    volumes:
      - shared-data:/data

volumes:
  shared-data:
┌───────────┐                     ┌───────────┐
│  writer   │                     │  reader   │
│           │                     │           │
│  /data ───┼──→ shared-data ←───┼── /data   │
│  (writes) │    (named vol)     │  (reads)  │
└───────────┘                     └───────────┘

Real-World Example: Web Server + App

A common pattern — the app generates static files, the web server serves them:

services:
  app:
    build: .
    command: python manage.py collectstatic --noinput
    volumes:
      - static-files:/app/staticfiles

  web:
    image: nginx:alpine
    ports:
      - "80:80"
    volumes:
      - static-files:/usr/share/nginx/html/static:ro
      - ./nginx.conf:/etc/nginx/nginx.conf:ro

volumes:
  static-files:

The app service writes static files to the volume. The web service reads them (:ro).


Sharing Host Directories

Multiple services can bind-mount the same host directory:

services:
  linter:
    image: node:20
    volumes:
      - ./src:/app/src:ro
    command: npx eslint /app/src

  formatter:
    image: node:20
    volumes:
      - ./src:/app/src
    command: npx prettier --write /app/src

Caution: Concurrent Writes

When two containers write to the same volume simultaneously, you can get:

  • File corruption — Two processes writing the same file
  • Race conditions — Unpredictable ordering of writes
  • Lock contention — Database files shouldn’t be shared between two database instances

Rule: One writer, many readers. Or use a database for concurrent access.

✅ Safe:  App writes → Web server reads (different paths)
✅ Safe:  App writes logs → Log collector reads logs
❌ Unsafe: Two PostgreSQL instances writing to same volume
❌ Unsafe: Two apps writing to the same file

Summary

Pattern Safe? Example
One writer, many readers ✅ Yes App generates, Nginx serves
Many readers ✅ Yes Multiple services read config
One writer, writes different files ✅ Yes Multiple services write separate log files
Multiple writers, same files ❌ No Data corruption risk

Quick Reference

Item Detail
Share volume Mount same volume name in multiple services
Read-only reader Mount with :ro for read-only access
Safe pattern One writer, many readers
Unsafe pattern Multiple writers to same files
Static files App writes, Nginx serves (common pattern)
Host share Multiple services bind-mount same host dir