User-Defined Network: DNS-Based Service Discovery
The default bridge network is limited: no automatic DNS-based service discovery, weaker isolation controls. By creating your own bridge network, you get built-in DNS resolution, containers reach each other by name and clearer boundaries between different app stacks specially in a microservice based environment. In a User-Defined Network, Docker provides an internal DNS server. When container-a tries to ping container-b, Docker’s DNS resolves the name container-b to its current IP address automatically.
For this we will use docker-compose.yml for easy readability and creation of network and containers. Let's first create a compose file
Run and test it#
1. Start the services
2. Ping by container name. In previous examples as you seen this failed because default bridge network doesn’t support the dns resolution. But this time It works! You’ll see it resolving to an IP like 172.x.x.x automatically.
Not only ping we can actually do real-time request from the tester container to the web-server container.
Note:
- As we discussed earlier, the
alpineimage is the "minimalist" of the Linux world. To keep its size incredibly small (around 5MB), it doesn't come withcurlpre-installed. Alpine comes with a lightweight version ofwgetby default using which we can request to web-server container. - nginx runs on default on port 80 so we should use that port to connect it from tester as these two are on same network.
Why this is better than the Default Bridge?#
- No IP Management: You don't have to hardcode
172.xx.xx.xx. If the container restarts and gets a new IP, the DNS updates automatically. - Isolation: Only containers on
coding-shuttle-private-netcan talk to each other. If you had another project running on a different network, they wouldn't interfere. - Readability: Your code/config uses human names (
database,api,cache) instead of cryptic numbers.
Pro-Tip: The "Auto-Created" Network#
If you want to be even lazier (in a good way!), you don't even need to define a networks: section at all. If your docker-compose.yml looks like this:
YAML
Docker Compose automatically creates a network called projectname_default and puts both containers on it. This auto-created network is a user-defined bridge, so app can still ping db by name!
Conclusion#
User-defined Docker networks significantly improve container communication by enabling built-in DNS-based service discovery and better isolation. Instead of relying on changing IP addresses, containers can communicate using service or container names, making configurations simpler and more reliable. This approach is especially beneficial in microservice architectures where multiple services must interact seamlessly within an isolated network.