Container Networking
How containers communicate — bridge networks, DNS, port binding, and container-to-container traffic
Skills taught: docker.networks, docker.bridge, docker.dns, docker.port-binding, docker.container-dns
Docker's network drivers
# List available networks
docker network ls
# NETWORK ID NAME DRIVER SCOPE
# 1234abcd bridge bridge local
# 5678efgh host host local
# 9012ijkl none null local
# bridge (default): containers get their own network namespace;
# can reach each other by IP; host reaches them via -p ports
# host: container shares the host's network stack (no isolation);
# fastest, but loses network isolation
# none: no networking at all (fully isolated)
The problem with the default bridge
When you run containers on the default bridge network, they can technically reach each other by IP — but the IPs are assigned dynamically and change on restart. Worse, the default bridge has no built-in DNS. You can't reach a container by name.
Custom networks — the right way to connect containers
# Create a custom bridge network
docker network create myapp-network
# Run containers on the same network
docker run -d \
--name postgres \
--network myapp-network \
-e POSTGRES_PASSWORD=secret \
postgres:16
docker run -d \
--name api \
--network myapp-network \
-p 3000:3000 \
-e DATABASE_URL="postgres://postgres:secret@postgres:5432/mydb" \
myapi:latest
# Key insight: on a custom network, containers can reach each other
# by their --name as a DNS hostname.
# 'api' container connects to 'postgres:5432' — Docker DNS resolves 'postgres'
# to that container's IP automatically.
# Verify connectivity
docker exec api ping postgres
docker exec api nslookup postgres
# Remove the network when done
docker network rm myapp-network
Port binding — reaching containers from outside
# -p hostPort:containerPort
docker run -p 80:80 nginx # host:80 → container:80
docker run -p 8080:80 nginx # host:8080 → container:80
docker run -p 127.0.0.1:3000:3000 myapi # bind ONLY to localhost (not 0.0.0.0)
# Map a random available host port (useful in CI)
docker run -p 0:80 nginx
docker port container-id # see what port was assigned
# Multiple ports
docker run -p 80:80 -p 443:443 nginx
# -P (uppercase): publish ALL exposed ports to random host ports
docker run -P nginx
# See active port mappings
docker port my-nginx
# 80/tcp -> 0.0.0.0:80
Tip: Container-to-container traffic never needs -p. The -p flag only exposes a port to the host. When two containers are on the same Docker network, they communicate directly on any port without exposing it to the outside world. This is how you keep databases internal: no -p on the database container.
Frequently Asked Questions
How can I connect a container to multiple networks?
docker network connect <network> <container> — adds a container to an additional network while it's running. Useful when a reverse-proxy needs to reach multiple app networks: docker network connect frontend-net nginx; docker network connect backend-net nginx.