Guides: Kubernetes DNS Policy

Kubernetes dnsPolicy: The Basics and 6 Critical Best Practices

How Does DNS Work in Kubernetes?

DNS is a component in Kubernetes that enables service discovery and inter-pod communication. When a pod or service is created in the cluster, Kubernetes automatically generates DNS records for these objects. It translates human-readable names like service.namespace.svc.cluster.local to machine-readable IP addresses.

These records follow a specific naming convention and are maintained by a DNS service, typically CoreDNS, running within the cluster. This DNS service ensures that every pod and service can be accessed via a unique, resolvable DNS name, simplifying communication and integration across the cluster.

When a pod makes a DNS query, the request is directed to the CoreDNS server within the cluster. CoreDNS then checks its records to resolve the query. If the DNS query relates to an internal service or pod, CoreDNS responds with the appropriate IP address. For external DNS queries, CoreDNS can forward the request to an external DNS server.

This is part of a series of articles about Kubernetes networking.

In this article:

What Objects Get DNS Records in Kubernetes?

Pods

Each pod in Kubernetes can have a DNS record when the DNS policy and the respective service are correctly configured. The DNS name of a pod is typically structured as pod-ip-address.namespace.pod.cluster.local, where “pod-ip-address” is replaced with the actual IP address assigned to that pod in the cluster. This structure ensures that each pod can be uniquely identified and reached through DNS within the cluster.

The DNS entry for a pod facilitates network communication with other pods and services, whether they reside on the same node or different nodes across the cluster. This is crucial for maintaining the functionality of applications that rely on inter-podal communication.

Services

Kubernetes services receive DNS records which enable other services or pods to locate them via easy-to-remember domain names. A typical DNS record for a service might look something like service.namespace.svc.cluster.local. Here, “service” refers to the name of the Kubernetes Service, providing a consistent endpoint to access the pods grouped by this Service.

Having a DNS record for each service solves the problem of changing pod IPs; Kubernetes dynamically updates DNS records to reflect changes in the pods backing a service. This ensures continuous connectivity and availability, even as pods are created, destroyed, or moved around in the cluster.

What Is dnsPolicy in Kubernetes?

dnsPolicy is a specification within the pod’s configuration that dictates how DNS queries are resolved within the pod’s containers. It plays a vital role in networking within a Kubernetes cluster, determining which DNS server responds to the DNS requests from the pods. This configuration impacts how services and pods locate one another through DNS within and outside the Kubernetes cluster.

The dnsPolicy setting offers several predefined options, discussed in more detail in the following section, each of which manipulates DNS resolution in different ways.

Here is an example of a pod manifest that defines a ClusterFirst DNS policy:

apiVersion: v1
kind: Pod
metadata:
  name: busybox
  namespace: default
spec:
  containers:
  - image: busybox:1.28
    command:
      - sleep
      - "3600"
    imagePullPolicy: IfNotPresent
    name: busybox
  restartPolicy: Always
  dnsPolicy: ClusterFirst

Related content: Read our guide to Kubernetes network security

Values in dnsPolicy

Default

The Default dnsPolicy uses the DNS configuration inherited from the node on which the pod runs. This policy is straightforward, as it relies on the existing DNS setup of the host, which means no specific configuration within Kubernetes is required for DNS policy. If the node’s DNS config changes, the pods’ DNS config also changes automatically.

However, while Default is simple and does not isolate DNS services within the cluster, it can introduce complexities when nodes are configured differently or when migrating services from one cluster environment to another.

None

When the dnsPolicy is set to None, this allows full user control over DNS settings. Users must provide DNSConfig when using None as the policy, specifying exactly how DNS queries should be resolved. This option is used in scenarios where custom DNS setups are needed, such as in hybrid cloud environments or with special network architectures.

The None policy is particularly useful for fine-tuning DNS configurations to optimize performance or meet specific security policies. However, it requires careful configuration to ensure that DNS resolution works as expected across all pods and nodes in the cluster.

ClusterFirst

ClusterFirst dnsPolicy makes the pod ignore DNS settings from the host, and only use the DNS server specified within the Kubernetes cluster. This ensures that the DNS queries for domains and services within the cluster are always resolved internally. It’s the default setting for most Kubernetes deployments, enhancing internal connectivity and security.

The policy is designed to fail if DNS queries are intended for cluster-internal resources, which are not available. This prevents leakage of cluster-internal DNS queries to external DNS servers, safeguarding the internal structure of the cluster.

ClusterFirstWithHostNet

For pods running with the hostNetwork setting enabled, the ClusterFirstWithHostNet dnsPolicy should be used. It allows pods to use the host’s network but still prioritize internal cluster DNS resolution before querying external DNS servers, just like ClusterFirst.

This policy is essential for applications that need to access both cluster services and external networks. It maintains an optimal balance between internal cluster isolation and necessary external access, ensuring efficient and secure communication for pods on the host network.

Best Practices for Implementing DNS Policies in Kubernetes

1. Fine-Tune CoreDNS

Fine-tuning CoreDNS is essential for maximizing DNS performance and reliability in your Kubernetes cluster. CoreDNS is highly configurable, allowing you to adjust various parameters to match the specific needs of your environment. For example, by customizing the cache settings, you can determine how long DNS records are stored, which directly impacts the speed of DNS resolution for recurring queries.

Additionally, you can enable query logging, which is useful for auditing and troubleshooting DNS issues, providing insights into how DNS is being utilized within the cluster. Tuning CoreDNS also involves configuring its plugins, such as the forward plugin to handle external DNS queries efficiently, or the rewrite plugin to manage DNS requests dynamically. By thoughtfully adjusting these settings, you ensure that CoreDNS is not only responsive but also resilient to the high demand typical of dynamic Kubernetes workloads.

2. Restrict External DNS Queries

Restricting external DNS queries within a Kubernetes cluster is a best practice that enhances both security and efficiency. Kubernetes clusters often contain sensitive microservices that should not communicate with external networks unless absolutely necessary.

By configuring CoreDNS to limit which domains can be resolved externally, you can prevent accidental exposure of internal services and data to the internet, thereby reducing the risk of attacks like DNS spoofing or data exfiltration. This restriction can be implemented using CoreDNS plugins like kubernetes, which ensures that DNS queries for internal services are handled within the cluster, and block, which can explicitly block queries to certain external domains.

Additionally, restricting external DNS queries helps to reduce unnecessary network traffic, which can improve overall cluster performance and reduce costs, particularly in environments with metered data transfers.

3. Enable DNS Caching

Enabling DNS caching in your Kubernetes cluster is a powerful way to enhance the performance and efficiency of DNS operations. When DNS caching is enabled, CoreDNS stores responses for a specified duration, meaning that repeat queries for the same domain can be resolved more quickly without querying the original source repeatedly. This reduces latency, making service discovery faster, and also decreases the load on DNS servers, which is particularly beneficial in large clusters where DNS traffic can become a bottleneck.

Properly configured DNS caching can improve the user experience for applications that rely on rapid and frequent DNS lookups. For instance, by adjusting the time-to-live (TTL) settings, you can control how long a DNS response is cached—shorter TTLs keep data fresh, while longer TTLs maximize performance by reducing the number of external queries. This balance is crucial for maintaining a responsive and scalable DNS infrastructure.

4. Implement DNS Load Balancing

Implementing DNS load balancing in Kubernetes ensures that DNS queries are distributed evenly across multiple DNS servers, preventing any single server from becoming overloaded and improving the resilience of the DNS infrastructure. CoreDNS can be configured with load balancing strategies like round_robin, which rotates DNS responses among different endpoints to distribute the load.

This not only enhances the availability of DNS services but also ensures that queries are handled efficiently, even during peak traffic periods. Load balancing is particularly important in large, production-grade Kubernetes clusters, where the volume of DNS queries can be substantial. By evenly distributing these queries, you avoid performance degradation and ensure that DNS resolution remains fast and reliable.

DNS load balancing also contributes to fault tolerance, as it helps maintain service continuity even if one of the DNS servers becomes unavailable, automatically redirecting traffic to healthy servers.

5. Monitor DNS Performance and Health

Monitoring DNS performance and health is critical for maintaining a robust and responsive DNS service in your Kubernetes environment. By integrating monitoring tools like Prometheus with CoreDNS, you can gather detailed metrics on various aspects of DNS operation, such as query latency, error rates, and cache hit/miss ratios. These metrics provide valuable insights into the efficiency of DNS queries, helping you to identify potential bottlenecks or misconfigurations.

Regular monitoring enables proactive management, allowing you to detect and address issues such as DNS server overloads, network latency, or configuration errors before they impact the availability or performance of your services. Additionally, by setting up alerts based on DNS metrics, you can quickly respond to anomalies, ensuring that your cluster remains resilient and that DNS queries are always processed efficiently.

6. Implement DNSSEC (DNS Security Extensions)

Implementing DNSSEC (DNS Security Extensions) in your Kubernetes cluster is a vital step towards securing DNS communications. DNSSEC provides a way to verify the authenticity of DNS responses by digitally signing DNS records, protecting against threats such as DNS spoofing, where attackers can redirect traffic by providing false DNS information.

Although implementing DNSSEC requires careful planning and configuration, the benefits it offers in terms of security are substantial, especially in environments where data integrity and authenticity are paramount. For example, in a multi-tenant Kubernetes cluster or in a public cloud environment, DNSSEC ensures that only legitimate DNS responses are accepted, preventing malicious entities from injecting harmful or incorrect data into the DNS process.

Additionally, DNSSEC can be integrated with CoreDNS through plugins that handle the signing and verification of DNS records, making it a seamless part of your cluster’s DNS infrastructure. While DNSSEC adds a layer of complexity to DNS management, the enhanced security it provides is crucial for protecting the integrity of your applications and data within the Kubernetes ecosystem.

Kubernetes DNS Policy with Calico

DNS policies in Calico allow you to leverage domain names instead of IP addresses to identify and control traffic to destinations outside of your cluster. Both Calico Enterprise and Calico Cloud offer a pre-configured DNS Dashboard, as well as the flexibility to create your own custom DNS Dashboards, to gain a comprehensive overview of DNS within a Kubernetes cluster.

Calico offers the following capabilities to create, test, validate, monitor, and troubleshoot DNS policies in Kubernetes:

  • Flow logs – Calico collects a wide range of logs that can be used to investigate flows and validate policies. Flow logs include policy evaluation and the output, and can be used to verify whether a network policy is correctly denying or allowing traffic to pass through.
  • Policy Recommender – Calico’s policy engine recommends policies based on the traffic flow of your microservices. All recommended policies can be modified before enforcement.
  • Policies dashboard – The Policies dashboard can be used to identify misconfigurations, as it highlights policies that are denying traffic or that have no endpoints assigned to them.
  • DNS dashboard – ​​A comprehensive dashboard used to gain deeper insights into the DNS traffic within your environment. This dashboard offers various analytics that enable DevOps and application teams to quickly identify DNS health and performance issues.
  • Dynamic Service & Threat Graph – Provides a visual representation of cluster policies and traffic, allowing you to monitor and verify that policies are working correctly.

Next steps:

X