🌍 Networking

DNS

Domain Name System

A system that translates domain names into IP addresses. Serves as the internet's phone book.

📖 Detailed Explanation

DNS (Domain Name System) is a distributed database system that translates human-friendly domain names (e.g., google.com) into IP addresses (e.g., 142.250.196.110) that computers understand. Often called the phone book of the internet, without DNS we would have to memorize numeric IP addresses to access every website.

DNS was designed in 1983 by Paul Mockapetris. In the early internet (ARPANET), all host names were managed with a single hosts.txt file, but as networks grew rapidly this approach reached its limits, and DNS, with its distributed hierarchical structure, was born.

DNS operates in a hierarchical structure. Queries are passed in the order of Root DNS server → TLD (Top-Level Domain) server (.com, .kr, etc.) → Authoritative DNS server. The local DNS resolver caches these results to quickly handle repeated queries for the same domain. A typical DNS lookup completes within 100ms.

In modern web services, DNS goes beyond simple name resolution and performs various roles such as load balancing, CDN routing, failover, and geographic routing. Services such as AWS Route 53 and Cloudflare DNS guarantee availability of 99.99% or higher and handle billions of queries worldwide every day.

💻 Code Example

import socket
import dns.resolver  # pip install dnspython

# 기본 DNS 조회
hostname = "google.com"
ip_address = socket.gethostbyname(hostname)
print(f"{hostname} → {ip_address}")  # google.com → 142.250.196.110

# dnspython으로 상세 DNS 조회
resolver = dns.resolver.Resolver()

# A 레코드 (IPv4 주소)
a_records = resolver.resolve("google.com", "A")
for rdata in a_records:
    print(f"A Record: {rdata}")

# MX 레코드 (메일 서버)
mx_records = resolver.resolve("google.com", "MX")
for rdata in mx_records:
    print(f"MX Record: {rdata.preference} {rdata.exchange}")

# TXT 레코드 (SPF, DKIM 등)
txt_records = resolver.resolve("google.com", "TXT")
for rdata in txt_records:
    print(f"TXT Record: {rdata}")

# 커스텀 DNS 서버 사용 (Google DNS)
resolver.nameservers = ["8.8.8.8", "8.8.4.4"]
result = resolver.resolve("example.com", "A")
print(f"Google DNS 결과: {list(result)}")
# nslookup - 기본 DNS 조회
nslookup google.com
nslookup -type=MX google.com  # 메일 서버 조회
nslookup google.com 8.8.8.8   # 특정 DNS 서버 사용

# dig - 상세 DNS 조회 (추천)
dig google.com                 # A 레코드
dig google.com MX             # MX 레코드
dig google.com +short         # IP만 출력
dig @8.8.8.8 google.com       # Google DNS 사용
dig google.com +trace         # DNS 해석 경로 추적

# DNS 캐시 확인 및 삭제 (macOS)
sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder

# DNS 캐시 삭제 (Linux)
sudo systemctl restart systemd-resolved

# DNS 캐시 삭제 (Windows)
ipconfig /flushdns

# 역방향 DNS 조회 (IP → 도메인)
dig -x 8.8.8.8 +short  # dns.google 반환

# DNS 응답 시간 측정
dig google.com | grep "Query time"
const dns = require('dns');
const { Resolver } = require('dns').promises;

// 기본 DNS 조회 (콜백)
dns.lookup('google.com', (err, address, family) => {
    console.log(`IP: ${address}, IPv${family}`);
});

// Promise 기반 DNS 조회 (권장)
async function dnsLookup() {
    const resolver = new Resolver();

    // A 레코드 조회
    const addresses = await resolver.resolve4('google.com');
    console.log('A Records:', addresses);

    // MX 레코드 조회
    const mxRecords = await resolver.resolveMx('google.com');
    mxRecords.forEach(mx => {
        console.log(`MX: ${mx.exchange} (priority: ${mx.priority})`);
    });

    // TXT 레코드 조회
    const txtRecords = await resolver.resolveTxt('google.com');
    console.log('TXT Records:', txtRecords);

    // 역방향 조회 (IP → 도메인)
    const hostnames = await resolver.reverse('8.8.8.8');
    console.log('Reverse DNS:', hostnames);
}

// 커스텀 DNS 서버 설정
const customResolver = new Resolver();
customResolver.setServers(['8.8.8.8', '1.1.1.1']);

dnsLookup().catch(console.error);

🗣️ Say It Like This in Practice

💬 In an incident response meeting
"The DNS TTL is set to 1 hour, so even after the IP change, traffic may go to the old server for up to 1 hour. To prepare for emergencies, it would be good to lower the TTL to 5 minutes. For reference, Cloudflare's default TTL is 300 seconds."
💬 In an Interview
"DNS operates with a distributed caching structure. When a client requests a domain, it first checks the local DNS cache, and if the record is not there, the Recursive DNS server performs iterative queries in the order of Root → TLD → Authoritative server. In actual production, we used Route 53 or Cloudflare to implement regional routing and health-check-based failover."
💬 In Infrastructure Design Discussions
"For a multi-region service, it's better to apply GeoDNS and route users to the region closest to them. If you send Asian users to ap-northeast-2 and US users to us-east-1, you can reduce latency by more than 100ms."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Setting the TTL too long

If you migrate servers after setting the TTL to 24 hours, some users will connect to the old server for up to a day. Lower the TTL to 300 seconds (5 minutes) or less at least 48 hours before the migration.

❌
Ignoring DNS propagation time

DNS changes are not reflected immediately. It can take up to 48 hours to propagate to DNS servers worldwide. Make important changes in advance, during low-traffic hours.

❌
Relying on a single DNS provider

In 2016, the Dyn DNS attack took down Twitter, Netflix, and others. For critical services, use multiple DNS providers, such as Route 53 + Cloudflare.

✅
How to configure DNS correctly

Set the TTL to 1 hour (3600 seconds) during normal operation and to 5 minutes (300 seconds) when a change is planned. Enable DNSSEC to prevent DNS spoofing. Use monitoring tools to check DNS resolution time at all times.

🔗 Related Terms

📚 Learn More