Skip to content

Lesson 5 of 24Containers

Volumes and Networking

Keep data alive across containers with volumes, and connect containers to each other by name on a network.

15 min read0/6 questions

A real app is never one container. Your API needs a database whose data survives restarts, and the API has to find that database on the network. Those two jobs belong to volumes and networks, and they are where most "it worked yesterday" Docker bugs live.

Three ways to store data outside the writable layer

You learned that a container's writable layer is deleted with docker rm. Docker gives you three kinds of mounts that put data somewhere else.

Where container files can live
./src: host folder./srchost folderpgdata: named volumepgdatanamed volumetmpfs: host memorytmpfshost memoryContainer: sees one treeContainersees one treeWritable layer: gone on rmWritable layergone on rmbind mountvolumetmpfsother writes

A bind mount maps a specific host path into the container. Edit a file on your laptop and the container sees it instantly. Perfect for development.

1/4
Bind mountNamed volumetmpfs
Syntax-v ./src:/app/src-v pgdata:/var/lib/postgresql/data--tmpfs /app/tmp
Lives inA path you choose on the hostDocker's storage areaHost RAM
Survives docker rmYesYesNo
Best forLive code in development, config filesDatabase files, uploadsScratch space, sensitive temp files
Watch out forFile permissions, slower on macOSBack it up; docker volume rm deletes itUses memory

The -v syntax tells them apart by the left side: a path (starts with /, ./, or ~) is a bind mount; a plain name is a named volume. The longer --mount flag spells it out and is clearer in scripts: --mount type=volume,source=pgdata,target=/var/lib/postgresql/data.

Match the pairs0/4 matched

Pick the right storage for each job.

Choose an item, then its match on the other side.

Persisting a database

Run Postgres with a named volume, delete the container, and start a new one on the same volume. The data is still there.

docker volume create pgdatadocker run -d --name db \  -e POSTGRES_PASSWORD=devpass \  -v pgdata:/var/lib/postgresql/data \  postgres:17docker rm -f db          # container gone...docker run -d --name db -e POSTGRES_PASSWORD=devpass \  -v pgdata:/var/lib/postgresql/data postgres:17   # ...data backdocker volume lsdocker volume inspect pgdata   # shows where Docker keeps it on the host

The target path matters: it must be the folder where the program actually writes. For the official postgres:17 image that is /var/lib/postgresql/data. Mount the wrong path and Postgres writes to the writable layer, and you lose everything on the next docker rm.

Quick check
You run Postgres with -v pgdata:/var/lib/postgresql/data. To apply a patch release, you docker rm -f db and docker run the newer postgres:17 image with the same -v flag. What happens to your tables?
Need a nudge? A hint rules out a wrong answer.

Networks: containers finding each other

Each container has its own network namespace and IP address. Those IPs change every time a container is recreated, so you never hard-code them. Instead, put containers on a user-defined bridge network. Docker runs a small DNS server on it, so each container can reach the others by name.

docker network create appnetdocker run -d --name db    --network appnet -e POSTGRES_PASSWORD=devpass postgres:17docker run -d --name cache --network appnet redis:7-alpinedocker run -d --name api   --network appnet -p 8000:8000 \  -e DATABASE_URL=postgresql://postgres:devpass@db:5432/postgres \  -e REDIS_URL=redis://cache:6379 \  myapi:1.0

Look at the connection strings: the host is db and cache, the container names.

A user-defined bridge network
network: appnetBrowser: localhost:8000Browserlocalhost:8000api: :8000api:8000db: :5432db:5432cache: :6379cache:6379-p 8000:8000db:5432cache:6379

Only api publishes a port, so it is the only container your browser can reach.

1/4

Here is a model of that DNS lookup. Names only resolve between containers on the same network.

Pythondocker_dns.py
networks = { "appnet": {"api": "172.18.0.2", "db": "172.18.0.3", "cache": "172.18.0.4"}, "othernet": {"worker": "172.19.0.2"},} def resolve(from_container: str, name: str) -> str: for members in networks.values(): if from_container in members and name in members: return members[name] return "could not resolve host" print("api -> db: ", resolve("api", "db"))print("api -> cache: ", resolve("api", "cache"))print("worker -> db: ", resolve("worker", "db"))
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

networks = {"front": {"web": "10.0.1.2", "api": "10.0.1.3"},
          "back": {"api": "10.0.2.3", "db": "10.0.2.4"}}

def resolve(src, name):
  for members in networks.values():
      if src in members and name in members:
          return members[name]
  return "fail"

print(resolve("web", "api"))
print(resolve("web", "db"))
print(resolve("api", "db"))
Need a nudge? Hints walk you through it.

Published ports vs internal ports

Two different things are easy to confuse:

  • An internal port is the port a process listens on inside its container. Other containers on the same network use it directly: db:5432.
  • A published port (-p) opens a port on the host and forwards it in. Only needed for traffic from outside Docker: your browser, psql on your laptop, the internet.

Publishing a database to the world is a classic leak. If you want to use a GUI client locally, bind to loopback only: -p 127.0.0.1:5432:5432. On Linux, Docker writes its own firewall rules for published ports, which can bypass tools like ufw, so an unintended -p 5432:5432 on a server is exposed to the internet.

Quick check
Inside the api container, the app connects to postgresql://...@localhost:5432/... and gets connection refused. Both containers are on appnet. Why?
Need a nudge? A hint rules out a wrong answer.
Quick check
Which containers in the diagram above need a -p flag for the app to work?
Need a nudge? A hint rules out a wrong answer.

Reaching the host, and host networking

Sometimes a container needs something running on your laptop, like a local model server on port 11434. Docker Desktop provides the name host.docker.internal for that. On Linux, add --add-host=host.docker.internal:host-gateway to get the same name.

With --network host, a container skips network isolation and shares the host's network stack: no -p needed, and the app's port 8000 is the host's port 8000. It is fastest, but you lose isolation and port conflicts come back. It is mainly a Linux feature and you will rarely need it.

Put it in order4 steps

Order the steps to run an API that talks to Postgres by name.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
bind mount
A host path mapped into a container. Changes show up on both sides instantly.
named volume
Docker-managed storage referenced by name. Outlives containers. Use it for databases.
tmpfs
A mount backed by host memory that disappears when the container stops.
user-defined bridge
A network you create with docker network create. Containers on it resolve each other by name.
published port
A host port forwarded into a container with -p. Only needed for traffic from outside Docker.
host.docker.internal
A hostname that lets a container reach services running on the host machine.