How to Use DNS in Docker: Simple Guide with Examples
To use
DNS in Docker, you can specify custom DNS servers with the --dns option in docker run or set DNS in Docker Compose files under dns. This lets containers resolve domain names using your chosen DNS servers instead of the default Docker DNS.Syntax
The main way to set DNS in Docker is using the --dns flag when running a container. You provide one or more DNS server IP addresses that the container will use for name resolution.
Example parts:
docker run: command to start a container--dns <IP>: sets a DNS server IP for the containerimage_name: the Docker image to run
bash
docker run --dns 8.8.8.8 --dns 8.8.4.4 image_name
Example
This example runs an alpine container with Google's public DNS servers set. It then uses nslookup to resolve example.com.
bash
docker run --rm --dns 8.8.8.8 alpine sh -c "apk add --no-cache bind-tools && nslookup example.com"
Output
Server: 8.8.8.8
Address 1: 8.8.8.8 google-public-dns-a.google.com
Non-authoritative answer:
Name: example.com
Address: 93.184.216.34
Common Pitfalls
Common mistakes when using DNS in Docker include:
- Not specifying DNS servers when the default Docker DNS is blocked or unreachable.
- Using invalid IP addresses for DNS servers.
- Forgetting to add the
--dnsflag or thednskey in Docker Compose. - Overriding DNS but not restarting containers, so changes don't apply.
Example of wrong and right usage:
bash
# Wrong: no DNS specified, might fail if default DNS is unreachable docker run alpine nslookup example.com # Right: specify DNS servers explicitly docker run --dns 8.8.8.8 alpine nslookup example.com
Quick Reference
| Option | Description | Example |
|---|---|---|
| --dns | Set custom DNS server for container | docker run --dns 8.8.8.8 alpine |
| dns (Compose) | Set DNS servers in docker-compose.yml | dns: - 8.8.8.8 - 8.8.4.4 |
| --dns-search | Set DNS search domain | docker run --dns-search example.com alpine |
| --dns-opt | Set DNS options | docker run --dns-opt ndots:2 alpine |
Key Takeaways
Use the --dns flag to specify custom DNS servers when running Docker containers.
You can also set DNS servers in docker-compose.yml under the dns key for multi-container setups.
Always verify DNS server IPs are correct and reachable from your Docker host.
Restart containers after changing DNS settings to apply the new configuration.
Use tools like nslookup inside containers to test DNS resolution.