Networks
Containers talk to each other over Docker networks. A web app container reaches its database container by name (db:5432) on a shared network, without publishing any port to the host.
docker network create shop-net
docker run -d --name db --network shop-net -e POSTGRES_PASSWORD=dev postgres:17
docker run -d --name api --network shop-net -e DATABASE_URL=postgres://postgres:dev@db:5432/postgres -p 8000:8000 shop-api:1.4
docker run --rm --network shop-net alpine ping -c 1 dbSample output of the ping:
PING db (172.20.0.2): 56 data bytes
64 bytes from 172.20.0.2: seq=0 ttl=64 time=0.090 msNetwork drivers
| Driver | What it gives you | When to use |
|---|---|---|
bridge (user-defined) |
a private virtual network on one host, with DNS by container name | the default choice for multi-container apps |
bridge (the built-in one called bridge) |
where containers go if you don't pass --network; no name resolution |
legacy; avoid for real apps |
host |
no isolation: the container uses the host's network stack directly | maximum performance, or tools that must see host interfaces (Linux only) |
none |
only a loopback interface | jobs that must have no network access |
overlay |
a network spanning several hosts | Docker Swarm |
macvlan / ipvlan |
the container gets an address on your physical LAN | special cases (legacy apps that expect a real IP) |
Name resolution
Docker runs an embedded DNS server (at 127.0.0.11 inside containers) for user-defined networks. It answers with the IP of a container (or its --network-alias) on the same network. The default bridge network has no such DNS, which is why "it works with IPs but not names" usually means a container is on the default network.
import ipaddress
class Network:
def __init__(self, name, subnet, dns=True):
self.name, self.dns = name, dns
self.hosts = ipaddress.ip_network(subnet).hosts()
self.gateway = next(self.hosts) # .1 is the gateway
self.members = {}
def connect(self, container, aliases=()):
ip = next(self.hosts)
for name in (container, *aliases):
self.members[name] = ip
return ip
networks = {
"bridge": Network("bridge", "172.17.0.0/16", dns=False), # the default network
"shop-net": Network("shop-net", "172.20.0.0/16"),
}
attached = {}
def run(container, network, aliases=()):
ip = networks[network].connect(container, aliases)
attached.setdefault(container, []).append(network)
print(f"{container:<7} on {network:<9} ip {ip}")
def resolve(from_container, name):
for net_name in attached[from_container]:
net = networks[net_name]
if net.dns and name in net.members:
return f"{name} -> {net.members[name]} (via {net_name})"
return f"{name} -> bad address '{name}'"
run("db", "shop-net", aliases=["postgres"])
run("api", "shop-net")
run("legacy", "bridge")
run("old-db", "bridge")
print(resolve("api", "db"))
print(resolve("api", "postgres"))
print(resolve("legacy", "old-db")) # default bridge: no DNS
print(resolve("legacy", "db")) # different networkdb on shop-net ip 172.20.0.2
api on shop-net ip 172.20.0.3
legacy on bridge ip 172.17.0.2
old-db on bridge ip 172.17.0.3
db -> 172.20.0.2 (via shop-net)
postgres -> 172.20.0.2 (via shop-net)
old-db -> bad address 'old-db'
db -> bad address 'db'
Isolation between networks
Containers on different networks cannot reach each other at all. That is a feature: put the database on a backend network that only the API joins, and the public-facing proxy on a frontend network. A container can join several networks with docker network connect.
[ proxy ] ──frontend── [ api ] ──backend── [ db ]membership = {
"proxy": {"frontend"},
"api": {"frontend", "backend"},
"db": {"backend"},
"batch": {"backend"},
}
def can_reach(a, b):
shared = membership[a] & membership[b]
return ", ".join(sorted(shared)) if shared else None
pairs = [("proxy", "api"), ("api", "db"), ("proxy", "db"), ("batch", "db"), ("batch", "proxy")]
for a, b in pairs:
via = can_reach(a, b)
print(f"{a:>5} -> {b:<5} {'ok via ' + via if via else 'unreachable'}")proxy -> api ok via frontend
api -> db ok via backend
proxy -> db unreachable
batch -> db ok via backend
batch -> proxy unreachable
The proxy cannot talk to the database even though both run on the same host. If the proxy is compromised, the database is still not directly exposed.
Container ports vs published ports
Inside a network, containers use the container port directly: the API connects to db:5432, whatever (if anything) is published on the host. Publishing (-p) is only for traffic coming from outside Docker. A common mistake is configuring DATABASE_URL=...@localhost:5432: inside the API container, localhost is the API container itself.
To reach a service running on the host from a container, Docker Desktop provides the name host.docker.internal; on Linux add --add-host=host.docker.internal:host-gateway.
Useful commands
docker network ls
docker network inspect shop-net --format '{{range .Containers}}{{.Name}} {{.IPv4Address}}{{"\n"}}{{end}}'
docker network connect backend api
docker network disconnect bridge api
docker network pruneTest yourself
Two containers are on the default bridge network. ping db fails but ping 172.17.0.3 works. Why?
- DNS is disabled on Linux
- The default bridge network has no name resolution; use a user-defined network
- ping is not installed
- The db container is stopped
Inside the api container, what address should it use to reach a db container listening on 5432 on the same network?
- localhost:5432
- db:5432
- host.docker.internal:5432
- 0.0.0.0:5432
Containers proxy (network frontend) and db (network backend) run on the same host. Can proxy connect to db?
- Yes, all containers on a host can talk
- No, they share no network
- Only with root
- Only over UDP