By default, data inside a container is not persisted — delete the container and the data is gone. Volumes solve this problem.
Three Ways to Mount
1. Named Volume (recommended for data)
Docker manages the storage. Data survives container removal.
docker run -v postgres_data:/var/lib/postgresql/data postgres
In docker-compose.yml:
services:
db:
image: postgres
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data: # declare the volume
2. Bind Mount (recommended for development)
You mount a directory from the host into the container. Changes in either direction are immediately visible.
docker run -v /path/on/host:/path/in/container myapp
docker run -v $(pwd):/app myapp # current directory
docker run -v ./src:/app/src myapp # relative path
In docker-compose.yml:
services:
web:
volumes:
- ./src:/app/src # for live reload in development
- ./static:/app/static
3. tmpfs (Linux only)
Data lives in memory, not on disk. For temporary data.
docker run --tmpfs /tmp myapp
Managing Volumes
docker volume ls # list volumes
docker volume inspect postgres_data # volume details
docker volume rm postgres_data # remove a volume
docker volume prune # remove unused volumes
When to Use What
| Type | When to use |
|---|---|
| Named volume | Database data, uploads, persistent data |
| Bind mount | Development — hot reload, config files |
| tmpfs | Cache, sessions, sensitive data |
Development Pattern
Mount your code as a bind mount, dependencies as a named volume:
services:
web:
build: .
volumes:
- .:/app # code — bind mount for hot reload
- /app/.venv # isolate .venv in a volume
Without the second line, the host .venv would shadow the .venv from the image.
Backing Up a Volume
# Create a backup of a volume as a tar archive
docker run --rm -v postgres_data:/data -v $(pwd):/backup \
ubuntu tar czf /backup/backup.tar.gz /data
# Restore
docker run --rm -v postgres_data:/data -v $(pwd):/backup \
ubuntu tar xzf /backup/backup.tar.gz -C /
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!