In some cases, you will encounter such instances where you need the containers to communicate with each other, share with the outside network, or expose the running services to external access. This is where the DNS configuration in Docker containers comes into play.
In simple steps, this tutorial explores the fundamentals of configuring DNS to run the Docker containers.
How Does DNS in Docker Container Works?
Let us start by exploring how DNS in Docker containers works.
By default, any Docker container uses the host DNS configuration that is inherited from the “/etc/resolv.conf” file in Unix-based systems. Any container that attaches to the default Docker network bridge gets a copy of the host’s “resolv.conf” file.
In the case of containers that attach to a custom network definition, that container uses the Docker’s embedded DNS.
Docker-embedded DNS is a built-in feature in the Docker engine to provide a DNS resolution for any container that runs in a user-defined network instead of the default bridge network.
This helps to ensure that the networking configuration is consistent and portable across containers.
The embedded DNS server then forwards the external DNS lookups to the DNS servers that are configured on the host system.
Configuring the DNS Container
We can configure the DNS resolution of a given container using various flags that are outlined in the following in the “docker run” or “docker create” command when starting the container.
The supported flags are as follows:
- –dns – This parameter defines the IP address of the DNS server that you wish to use. To specify multiple DNS addresses, use multiple –dns flags.
- –dns-search – This parameter specifies a DNS search domain to search for non-fully qualified hostnames.
- –dns-opt – This represents a key-value pair that is used to specify the DNS option and its value.
- –hostname – This parameter defines the hostname that a container uses.
Example Usage:
To specify a DNS server for a given container, we can use the –dns option as provided in the following example:
The given command should set the DNS server to the Cloudflare DNS.
To specify multiple DNS addresses, run the following command:
We can also set up a custom DNS server for all containers.
Start by editing the Docker daemon config file in the “/etc/docker/daemon.json”. You can create this file if it does not exist on your local machine.
Finally, restart the Docker daemon as follows:
Conclusion
In this post, we explore the DNS working in Docker containers. We learned how the containers use DNS by default and how to configure a custom DNS for a given container.