SyntaxStudy
Sign Up
Docker Container DNS and Network Aliases
Docker Beginner 1 min read

Container DNS and Network Aliases

Docker's embedded DNS server (running at 127.0.0.11 inside each container) resolves container names to IP addresses within user-defined networks. Every container on a user-defined network is automatically registered with its container name and any additional aliases. This is what makes service discovery work: a Node.js app can connect to postgres://db:5432 regardless of the database container's IP address. Network aliases (--network-alias) allow multiple containers to respond to the same hostname, enabling round-robin load balancing within a network. Running three instances of a service with the same alias and connecting to that alias distributes connections across them. This is the low-level mechanism that Docker Swarm's service DNS uses. DNS-based service discovery scales naturally as containers start and stop — no static IP configuration needed. Combined with health checks, unhealthy containers are automatically removed from DNS responses in orchestrated environments. For development, this means you write connection strings using service names matching Compose service names and they work without any /etc/hosts editing.
Example
# Create a network and start three app instances with the same alias
docker network create lb-net

for i in 1 2 3; do
  docker run -d \
    --name app$i \
    --network lb-net \
    --network-alias app \
    -e INSTANCE=$i \
    myapp:latest
done

# Requests to "app:3000" round-robin across the three containers
docker run --rm --network lb-net curlimages/curl \
  sh -c 'for i in 1 2 3 4 5 6; do curl -s app:3000/instance; echo; done'

# Inspect DNS — shows multiple A records
docker run --rm --network lb-net alpine nslookup app

# Custom hostname and extra hosts
docker run -d \
  --name myapi \
  --network app-net \
  --hostname api-server \
  --add-host external.svc:1.2.3.4 \
  myapp:latest

docker exec myapi hostname
docker exec myapi cat /etc/hosts

# Clean up
docker stop $(docker ps -q)
docker network rm lb-net