Network Aliases and Service Discovery
Docker networks support service discovery using network aliases, which can be useful for creating resilient, scalable applications. This feature allows multiple containers to respond to the same DNS name, enabling basic load balancing.
- Create a new bridge network for this exercise:
docker network create service-network
- Verify the network creation:
docker network ls
You should see service-network
in the list.
- Create two containers with the same network alias:
docker run -d --network service-network --network-alias myservice --name service1 nginx
docker run -d --network service-network --network-alias myservice --name service2 nginx
- Create a client container and use
nslookup
to resolve the service:
docker run --rm --network service-network appropriate/curl nslookup myservice
You should see both container IPs returned, demonstrating that Docker's embedded DNS server is load-balancing between the two containers.
- Test accessing the service multiple times:
for i in {1..4}; do docker run --rm --network service-network appropriate/curl ping -c 1 myservice; done
You should see responses from both containers, demonstrating basic load balancing. The Docker DNS server will alternate between the two IP addresses when resolving myservice
.
PING myservice (172.18.0.2): 56 data bytes
64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.106 ms
--- myservice ping statistics ---
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max = 0.106/0.106/0.106 ms
PING myservice (172.18.0.3): 56 data bytes
64 bytes from 172.18.0.3: seq=0 ttl=64 time=0.119 ms
--- myservice ping statistics ---
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max = 0.119/0.119/0.119 ms
PING myservice (172.18.0.2): 56 data bytes
64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.097 ms
--- myservice ping statistics ---
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max = 0.097/0.097/0.097 ms
PING myservice (172.18.0.3): 56 data bytes
64 bytes from 172.18.0.3: seq=0 ttl=64 time=0.140 ms
--- myservice ping statistics ---
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max = 0.140/0.140/0.140 ms