When you first start using Docker, networking seems like magic. You map a port, and suddenly your application is accessible on `localhost`. But what happens when you need multiple containers to talk to each other?
In this deep dive, we'll strip away the magic and look at how Docker networking actually works under the hood. We'll cover the default bridge network, the performance benefits of the host network, and how overlay networks enable swarm mode.
Prerequisites
Before diving in, you should have a basic understanding of IP addressing, subnets, and how to use the Docker CLI to start a container.
1. The Default Bridge Network
When you install Docker, it creates a default bridge network named `bridge`. By default, every new container you start is attached to this network unless you specify otherwise.
Containers on the default bridge network can communicate with each other using their IP addresses. However, IP addresses can change when containers are recreated. This is why user-defined bridge networks are strongly recommended.
In the example above, the `web` container can reach the `db` container simply by using the hostname `db`. Docker's embedded DNS server handles the resolution automatically.
Automatic DNS Resolution
Automatic service discovery via embedded DNS only works on user-defined networks. Containers on the default bridge network must use legacy `--link` flags to communicate by name.
2. The Host Network
For standalone containers, you can bypass Docker's network isolation entirely and use the host's networking stack directly. This is done by passing `--network host`.
- Performance: Because it removes network address translation (NAT), the host network offers the best networking performance.
- Ports: You don't need to publish ports with `-p`. If your app binds to port 80, it will be immediately available on port 80 of the host machine.
Security Implications
Using host networking significantly reduces the isolation between the container and the host machine. It should only be used when absolutely necessary for high-throughput or low-latency applications.
3. Overlay Networks (Swarm & K8s)
When your infrastructure scales beyond a single host, bridge networks are no longer sufficient. This is where overlay networks come into play. An overlay network creates a distributed network among multiple Docker daemon hosts.
Conclusion
Understanding Docker networking drivers allows you to architect your applications securely and efficiently. Default to user-defined bridge networks for isolated applications, consider host networks for extreme performance requirements, and use overlay networks when scaling horizontally across a cluster.