EMZETT.
Login

Docker volumes and networks: Data and connections for containers

In short: Containers are ephemeral: volumes store data permanently outside the container, networks connect containers with each other.

In more detail: A container’s file system belongs to its life cycle: when it is deleted, the data in it is gone. For databases, uploads and configurations you therefore need volumes. And for several containers (for example web app and database) to talk to each other, Docker uses networks.

In Depth

Volumes and bind mounts

  • Volume: storage managed by Docker. docker run -v data:/var/lib/postgresql/data postgres creates the volume data and mounts it into the container. It survives deletion of the container.
  • Bind mount: a folder of the host is mounted directly (-v $(pwd)/code:/app). Handy for development because changes are immediately visible in the container.
  • tmpfs: memory in RAM, lost when it stops.
docker volume ls
docker volume inspect data
docker volume rm data

Networks

Containers in a user-defined bridge network reach each other via container names as host names:

docker network create appnet
docker run -d --name db --network appnet postgres
docker run -d --name web --network appnet -p 8080:80 my-app

In the app the database address is then db:5432. Only with -p (port publishing) is a service also reachable from the host or the internet; without it it stays hidden in the network, which is good for security (do not publish the database).

Docker Compose

In a compose.yaml you describe several containers together with volumes and networks:

services:
  web:
    build: .
    ports: ["8080:3000"]
    depends_on: [db]
  db:
    image: postgres:17
    volumes: [dbdata:/var/lib/postgresql/data]
volumes:
  dbdata:

docker compose up -d starts everything, docker compose down stops it (volumes remain, except with -v).

Notes

Back up data stored in volumes like any other database (backups!). Permissions between host and container (user IDs) are a frequent stumbling block with bind mounts. Network modes such as host remove isolation. In Kubernetes, PersistentVolumes and Services take over these tasks.

See also: Docker, Dockerfile, Kubernetes basics, Backup strategy