Lab 04 - Docker networking and volumes
Lab 04 - Docker networking and volumes
Goal: name resolution between containers, and data that survives. Cheat sheet: Docker
Networking
# 1 - the default networks
sudo docker network ls
# 2 - on the default bridge, name resolution does NOT work
sudo docker run -d --name db busybox sleep 3600
sudo docker run --rm busybox ping -c1 db # bad address 'db'
# 3 - a user-defined network gives you DNS by container name
sudo docker network create appnet
sudo docker run -d --name db2 --network appnet busybox sleep 3600
sudo docker run --rm --network appnet busybox ping -c1 db2 # works
This is the single most useful thing Docker networking does, and it is the concept a Kubernetes Service generalises: reach a moving target by a stable name. The difference is that Docker’s name points at one container, while a Service’s name points at whichever Pods are currently ready.
# 4 - host mode: no isolation, no -p needed
sudo docker run -d --name hostweb --network host nginx:1.27
curl -s localhost:80 | head -3
sudo docker rm -f hostweb
# 5 - none: no connectivity at all
sudo docker run --rm --network none busybox ip -brief address # only loopback
Volumes
# 6 - named volume: data outlives the container
sudo docker volume create appdata
sudo docker run --rm -v appdata:/data busybox sh -c 'echo persisted > /data/file'
sudo docker run --rm -v appdata:/data busybox cat /data/file # still there
sudo docker volume inspect appdata # where it lives on disk
Both containers are gone, the data is not. The volume is managed by the engine
and stored under /var/lib/docker/volumes on support01.
# 7 - bind mount: a host directory, read-only
mkdir -p ~/site && echo '<h1>bind mount</h1>' > ~/site/index.html
sudo docker run -d --name bweb -p 8082:80 \
-v ~/site:/usr/share/nginx/html:ro nginx:1.27
curl -s localhost:8082
echo '<h1>changed on the host</h1>' > ~/site/index.html
curl -s localhost:8082 # changed immediately, no restart
A bind mount is a window onto the host filesystem. Convenient for development,
and the closest Docker equivalent of a Kubernetes hostPath - with the same
drawback: it ties the workload to one machine.
Clean up
# 8 -
sudo docker rm -f db db2 bweb
sudo docker network rm appnet
sudo docker volume rm appdata
Keep the mental map: Docker volume -> PersistentVolume, bind mount -> hostPath,
container name resolution -> Service, --network container: -> Pod.