Volumes and Networks
~250 words ยท 2 min read
The persistence problem
Containers are ephemeral โ delete one and its filesystem goes with it. For databases, uploads, or any state you want to keep, you need a volume.
Two kinds of mounts
- Bind mount โ maps a specific path on your host into the container.
-v /host/path:/container/path. Great for local dev (live-reloading source code). - Named volume โ Docker manages a storage area for you.
-v mydata:/var/lib/postgresql/data. Best for production data โ portable and backup-friendly.
# Bind mount โ live code in dev
docker run -v $(pwd)/src:/app/src myapp
# Named volume โ persistent DB data
docker run -v pgdata:/var/lib/postgresql/data postgres
Ports
Containers have their own network. To reach a service inside one, map a host port to a container port:
docker run -p 8080:80 nginx
# host:container
# localhost:8080 -> container port 80
Two containers can both listen on port 80 internally, but each must map to a different host port โ you only have one port 8080 on the host.
Networks
- bridge (default) โ containers talk to each other and the host via a virtual network.
- host โ the container shares the host's network stack (no isolation).
- none โ no networking at all.
For multi-container apps, create a custom network so containers can reach each other by name.