Docker Volumes Explained with docker-compose
Hi there! I’m Maneshwar. Right now, I’m building LiveAPI, a first-of-its-kind tool that helps you automatically index API endpoints across all your repositories. LiveAPI makes it easier to discover, understand, and interact with APIs in large infrastructures.
When working with containers, managing data is just as important as running the app.
Docker offers multiple ways to handle data persistence and sharing—volumes.
Let’s break down the different types of volumes and how to use them with docker-compose
.
1. Named Volumes
Docker manages these under /var/lib/docker/volumes
. You define and reference them by name.
Example:
version: '3.8'
services:
db:
image: postgres:15
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:
- Volume
pgdata
will persist even if the container is removed. - It can be reused by other services too.
2. Anonymous Volumes
No name given. Docker generates a random volume ID.
Example:
version: '3.8'
services:
app:
image: myapp
volumes:
- /var/www/data
- The
/var/www/data
path in the container is backed by a randomly created volume. - These are not easily reusable and can pile up if not managed.
3. Bind Mounts
Mounts a specific path from the host directly into the container.
Example:
version: '3.8'
services:
web:
image: nginx
volumes:
- ./html:/usr/share/nginx/html:ro
- Changes on your host (
./html
) reflect live inside the container. - Ideal for local development and live reloading.
4. tmpfs Mounts
A mount in RAM. Fast and volatile—data disappears after container stops.
Example:
version: '3.8'
services:
scratch:
image: alpine
command: sleep 3600
tmpfs:
- /tmp/cache
- Good for scratch space, secrets, build caches, or anything ephemeral.
5. Volume Plugins / External Volumes
For using storage from NFS, cloud providers, etc.
Example with external NFS 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.100,rw
device: ":/exported/path"
- Useful in cluster setups or multi-host Docker environments.
Quick Recap
Type | Persist | Host Access | Good For |
---|---|---|---|
Named Volume | ✅ | ❌ | App data (db, logs) |
Anonymous Volume | ✅ | ❌ | Ephemeral container data |
Bind Mount | ✅ | ✅ | Local dev, config files |
tmpfs | ❌ | ❌ | Temp data, secrets, cache |
Plugin/Remote | ✅ | varies | Multi-host or cloud storage |
Final Tip
To inspect volumes:
docker volume ls
docker volume inspect <volume_name>
To clean up unused:
docker volume prune
LiveAPI helps you get all your backend APIs documented in a few minutes.
With LiveAPI, you can generate interactive API docs that allow users to search and execute endpoints directly from the browser.
If you’re tired of updating Swagger manually or syncing Postman collections, give it a shot.