Day 34: Volumes and networks
Making state and networking survive a container's lifecycle
A container's writable layer disappears when the container is removed — fine for stateless apps, disastrous for a database. A volume is storage managed by Docker outside any container's writable layer, so it survives container removal and can be shared between containers.
docker volume create pgdata
docker run -d --name db -v pgdata:/var/lib/postgresql/data postgres:16
# remove and recreate the container — pgdata persists
docker rm -f db
docker run -d --name db2 -v pgdata:/var/lib/postgresql/data postgres:16Networks
By default, containers on the same user-defined bridge network can reach each other by container name (Docker runs an embedded DNS resolver for this) — no manual IP tracking needed, and this is exactly the pattern Docker Compose (tomorrow) automates.
docker network create app-net
docker run -d --name db --network app-net postgres:16
docker run -d --name api --network app-net -e DB_HOST=db myapi:latest
# inside "api", "db" resolves to the database container's IP automaticallyKey terms
- Volume
- Docker-managed storage outside a container's writable layer, persisting across container removal.
- Bridge network
- A user-defined virtual network letting containers reach each other by name via embedded DNS.
Why does removing a Postgres container without a volume lose all its data?