5. Docker networking
5.1 Network drivers
| Driver | What it is | Use for |
|---|---|---|
bridge (default docker0) |
private L2 bridge on the host + NAT; containers get 172.17.x.x | quick one-offs; no DNS between containers on the default bridge |
user-defined bridge |
same, but with embedded DNS (container name → IP) and isolation | every multi-container app (Compose creates one automatically) |
host |
no network namespace; container uses the host's stack | max performance, network tools; port conflicts become your problem |
none |
loopback only | batch jobs that must not touch the network |
overlay |
VXLAN across hosts (Swarm) | multi-host Swarm; in Kubernetes the CNI plugin does this job |
macvlan/ipvlan |
container gets an IP on the physical LAN | legacy apps that need to look like a physical host |
docker network create orbit-net
docker run -d --name redis --network orbit-net redis:7-alpine
docker run --rm --network orbit-net redis:7-alpine redis-cli -h redis ping # PONG: DNS by name
docker network inspect orbit-net | jq '.[0].Containers'
5.2 How port publishing works
-p 8080:80 installs a DNAT rule in iptables (or nftables): traffic to
host:8080 is rewritten to container_ip:80. From inside a container,
localhost is the container itself, not your laptop. To reach a
service on the host from a container, use host.docker.internal (Docker
Desktop, or add --add-host=host.docker.internal:host-gateway on Linux).
War story: "The app works locally but can't connect to the DB in Docker." The app was configured with
DB_HOST=localhost. In a container that means the container's own loopback. Use the service name (db) on a shared network.
5.3 Debugging container networking
# netshoot: a container full of network tools, joined to another container's network namespace
docker run --rm -it --network container:orders nicolaka/netshoot
# ss -tlnp -> what is listening
# dig redis -> DNS
# curl -v http://catalog:8080/readyz
# tcpdump -i eth0 port 5432
The --network container:<name> trick is the same idea as the ephemeral
debug containers you'll use in Kubernetes (§33.3).