Docker Compose — Volume Syntax
Compose supports two syntax forms for volume mounts: short form and long form. This page explains both and when to use each.
Short Form
The compact, most-used syntax:
volumes:
# Named volume
- pgdata:/var/lib/postgresql/data
# Bind mount
- ./src:/app/src
# Bind mount (read-only)
- ./config:/etc/myapp/config:ro
# Anonymous volume
- /app/node_modules
Format: [SOURCE:]TARGET[:OPTIONS]
| Part | Required | Example |
|---|---|---|
| SOURCE | Optional | pgdata, ./src, /home/user/data |
| TARGET | Yes | /var/lib/postgresql/data |
| OPTIONS | Optional | ro, rw |
Long Form
The verbose, explicit syntax:
volumes:
# Named volume
- type: volume
source: pgdata
target: /var/lib/postgresql/data
# Bind mount
- type: bind
source: ./src
target: /app/src
# Bind mount (read-only)
- type: bind
source: ./config
target: /etc/myapp/config
read_only: true
# tmpfs mount (in-memory)
- type: tmpfs
target: /tmp
tmpfs:
size: 100000000 # 100MB
Long Form Fields
| Field | Values | Purpose |
|---|---|---|
type |
volume, bind, tmpfs |
Mount type |
source |
Volume name or host path | Data source |
target |
Container path | Mount point inside container |
read_only |
true, false |
Prevent writes |
bind.propagation |
rprivate, shared, etc. |
Mount propagation |
tmpfs.size |
Bytes | Memory limit for tmpfs |
Short vs Long: When to Use
| Use Short When | Use Long When |
|---|---|
| Simple volume mounts | Need tmpfs mounts |
| Most everyday use | Need mount propagation |
| Quick and readable | Need explicit clarity |
| Team is comfortable | Onboarding new developers |
Most teams use short form for 90% of cases:
# Short form — most teams use this
services:
db:
image: postgres:16
volumes:
- pgdata:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql:ro
tmpfs Mounts
tmpfs mounts store data in memory only — useful for temporary files and secrets:
services:
app:
image: myapp
volumes:
- type: tmpfs
target: /tmp
tmpfs:
size: 52428800 # 50MB
tmpfs data is lost when the container stops. Use for:
- Temporary files
- Session data
- In-memory caches
Summary
| Syntax | Example | Use Case |
|---|---|---|
| Short: named volume | pgdata:/data |
Database storage |
| Short: bind mount | ./src:/app/src |
Development code |
| Short: read-only | ./config:/etc/config:ro |
Config files |
| Short: anonymous | /app/node_modules |
Exclude host dirs |
| Long: volume | type: volume, source: pgdata |
Explicit clarity |
| Long: bind | type: bind, source: ./src |
Mount options needed |
| Long: tmpfs | type: tmpfs, target: /tmp |
In-memory temp storage |
Quick Reference
| Item | Detail |
|---|---|
| Short named | pgdata:/var/lib/data |
| Short bind | ./src:/app/src |
| Short read-only | ./conf:/etc/conf:ro |
| Short anonymous | /app/node_modules |
| Long form | type: volume/bind/tmpfs |
| tmpfs | In-memory only, lost on stop |