Module 10 Lesson 3: DNS and Service Discovery
Stop using IP addresses. Master Docker's internal DNS system to allow your containers to find and talk to each other using simple human-readable names.
Module 10 Lesson 3: DNS and Service Discovery
In a dynamic environment, you can never rely on a container's IP address. Every time a container restarts, its IP might change. Service Discovery solves this by letting you use the container's Name instead.
1. The Embedded DNS Server
Every Docker container (on a user-defined network) has a DNS resolver at 127.0.0.11.
- When
Container Atries to connect todb, it asks this internal server. - The DNS server looks up the current IP of the container named
dband returns it.
2. Default Bridge vs. User-Defined Networks
This is a major point of confusion:
- Default Bridge: Does NOT support DNS discovery. You must use outdated and clunky
--linkflags to make containers talk to each other. - User-Defined Bridge: Supports DNS discovery automatically.
Rule: Always create your own networks (docker network create ...) if you want your services to talk to each other.
3. Aliases and Hostnames
You can give a container secondary "Nicknames" on a network.
docker run -d \
--name app-v1 \
--network my-net \
--network-alias search-engine \
elasticsearch
Now, other containers can reach this app using either app-v1 or search-engine. This is useful for "Blue-Green" deployments where you want to swap a new version into the search-engine name without changing the code in your other apps.
4. Configuring External DNS
If you want your container to use a specific external DNS (like Google 8.8.8.8) instead of your local office's DNS:
docker run --dns 8.8.8.8 my-image
Exercise: The Discovery Lab
- Create a network called
lab-net. - Run an
nginxcontainer namedweb-serveron that network. - Run an
alpinecontainer (interactive) on the same network. - Inside
alpine, runping web-server. Does it work? - Now, stop the
web-serverand start a new one with the same name. - Run
ping web-serverfromalpineagain. Did the IP address change? Did the name still work? - Check the file
/etc/resolv.confinside the alpine container. What does it say about the nameserver?
Summary
Service discovery is the "Glue" of microservices. By relying on Docker's embedded DNS, you can build systems where containers find each other instantly, regardless of how many times they are moved, restarted, or scaled.
Next Lesson: Spreading the load: Load balancing with Nginx and Docker.