Domain Configuration and DNS Management

Setting Up Your Application's Online Identity

Introduction to Domains and DNS

Domain names are the human-readable addresses of the internet. While computers communicate using IP addresses (like 192.168.1.1 or 2001:0db8:85a3:0000:0000:8a2e:0370:7334), humans prefer memorable names like "example.com" or "google.com". The Domain Name System (DNS) bridges this gap, translating domain names to IP addresses and enabling services to be discovered across the internet.

Think of DNS as the internet's phone book. Just as you don't need to memorize your friend's phone number to call them (you just look up their name in your contacts), you don't need to remember IP addresses to visit websites. DNS handles the lookup process automatically, usually in less than 100 milliseconds.

sequenceDiagram participant User participant Browser participant Resolver participant Root participant TLD participant Authoritative participant Server User->>Browser: Visit example.com Browser->>Resolver: Lookup example.com alt Cached result Resolver->>Browser: Return cached IP else No cached result Resolver->>Root: Query for .com nameservers Root->>Resolver: Return .com nameservers Resolver->>TLD: Query for example.com nameservers TLD->>Resolver: Return example.com nameservers Resolver->>Authoritative: Query for example.com records Authoritative->>Resolver: Return example.com IP Resolver->>Browser: Return IP address end Browser->>Server: Connect to server IP Server->>Browser: Return webpage Browser->>User: Display webpage

In this lecture, we'll explore how to configure and manage domains for your web applications, from registration to advanced DNS management and security considerations.

Domain Registration and Management

Choosing a Domain Name

Your domain name is your application's identity on the web, so choose wisely:

Tip: Consider variations and common misspellings of your chosen name. If your budget allows, you might want to register these to protect your brand and catch typo traffic.

Domain Extensions (TLDs)

The Top-Level Domain (TLD) is the part after the last dot in a domain name:

Strategic considerations: While .com remains the most recognized TLD, newer extensions can provide better name availability and industry relevance. However, some users might automatically add .com when typing an address, so consider defensive registrations if your budget allows.

Domain Registrars

Registrars are accredited organizations that can register domain names:

Registration Process

  1. Domain search - Check availability of your desired name
  2. Registration period - Choose 1-10 years (auto-renewal recommended)
  3. Contact information - Provide registrant details (name, email, address)
  4. WHOIS privacy - Enable to protect personal information
  5. Additional services - Consider email, hosting, or SSL certificates
  6. Payment - Complete purchase
  7. Verification - Some TLDs require email verification

Important: Always use a valid email address that you check regularly for domain registrations. Registrars will send important renewal notices and security alerts to this address.

Domain Management Best Practices

DNS Fundamentals

How DNS Works

The DNS resolution process typically involves several steps:

  1. DNS Query - Your browser asks the recursive resolver (usually provided by your ISP) for the IP address of a domain
  2. Resolver Check - The resolver checks its cache for a recent answer
  3. Root Servers - If not in cache, the resolver asks a root server for the TLD nameservers
  4. TLD Servers - The resolver asks the TLD nameservers for the authoritative nameservers
  5. Authoritative Nameservers - The resolver asks the authoritative nameservers for the IP address
  6. Response - The IP address is returned to your browser
  7. Caching - The result is cached at various levels for performance
graph TD A[Browser] -->|1. DNS Query| B[Recursive Resolver] B -->|2. Cache Check| B B -->|3. Query Root| C[Root Nameservers] C -->|4. TLD Nameservers| B B -->|5. Query TLD| D[TLD Nameservers] D -->|6. Authoritative Nameservers| B B -->|7. Query Authoritative| E[Authoritative Nameservers] E -->|8. IP Address| B B -->|9. IP Address| A A -->|10. HTTP Request| F[Web Server]

DNS Record Types

Different types of DNS records serve different purposes:

Record Type Purpose Example
A Maps a domain to an IPv4 address example.com. IN A 93.184.216.34
AAAA Maps a domain to an IPv6 address example.com. IN AAAA 2606:2800:220:1:248:1893:25c8:1946
CNAME Creates an alias pointing to another domain www.example.com. IN CNAME example.com.
MX Specifies mail servers for the domain example.com. IN MX 10 mail.example.com.
TXT Stores text information (often for verification) example.com. IN TXT "v=spf1 include:_spf.example.com ~all"
NS Delegates a subdomain to a set of nameservers example.com. IN NS ns1.example.com.
SOA Start of Authority - Contains administrative information example.com. IN SOA ns1.example.com. admin.example.com. ( 2025050501 ; Serial 3600 ; Refresh 1800 ; Retry 604800 ; Expire 86400 ; Minimum TTL )
CAA Specifies which CAs can issue certificates example.com. IN CAA 0 issue "letsencrypt.org"
SRV Specifies location of services _sip._tcp.example.com. IN SRV 10 60 5060 sip.example.com.
PTR Reverse lookup (IP to domain) 34.216.184.93.in-addr.arpa. IN PTR example.com.

Common DNS Configurations for Web Applications

Basic Website Setup
; Root domain pointing to your server
example.com.           IN  A       93.184.216.34
example.com.           IN  AAAA    2606:2800:220:1:248:1893:25c8:1946

; www subdomain as alias to root
www.example.com.       IN  CNAME   example.com.

; Mail server configuration
example.com.           IN  MX      10 mail.example.com.
mail.example.com.      IN  A       93.184.216.35

; SPF record for email authentication
example.com.           IN  TXT     "v=spf1 ip4:93.184.216.35 ~all"

; DKIM record for email authentication
mail._domainkey.example.com. IN TXT "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDHY..."
Subdomain Configuration
; API subdomain
api.example.com.       IN  A       93.184.216.36

; Blog subdomain pointing to a different host
blog.example.com.      IN  A       93.184.216.37

; App subdomain for mobile backend
app.example.com.       IN  A       93.184.216.38

; Development environment
dev.example.com.       IN  A       93.184.216.39

; Staging environment
staging.example.com.   IN  A       93.184.216.40
Load Balanced Configuration
; Multiple A records for simple load balancing
example.com.           IN  A       93.184.216.34
example.com.           IN  A       93.184.216.35
example.com.           IN  A       93.184.216.36

; Regional subdomains
us-east.example.com.   IN  A       93.184.216.37
us-west.example.com.   IN  A       93.184.216.38
eu-central.example.com. IN A       93.184.216.39
Wildcard Subdomain
; Wildcard record for dynamic subdomains
*.example.com.         IN  A       93.184.216.34

; Specific subdomain that overrides the wildcard
specific.example.com.  IN  A       93.184.216.35

Nameserver Configuration

Nameserver Options

You have several options for managing your domain's nameservers:

Choosing a DNS Provider

Consider these factors when selecting a DNS provider:

Popular DNS Providers

Setting Up Custom Nameservers

To use a DNS provider different from your registrar:

  1. Create an account with your chosen DNS provider
  2. Add your domain to the DNS provider
  3. Configure your DNS records at the provider
  4. Update the nameservers at your registrar
  5. Wait for the changes to propagate (often 24-48 hours)
# Example: Updating nameservers using the AWS CLI
aws route53domains update-domain-nameservers \
  --region us-east-1 \
  --domain-name example.com \
  --nameservers \
    Name=ns-123.awsdns-15.com \
    Name=ns-456.awsdns-57.net \
    Name=ns-789.awsdns-36.org \
    Name=ns-012.awsdns-01.co.uk

DNS Propagation

When you make DNS changes, they don't take effect immediately due to caching:

Tip: When planning changes to production domains, reduce the TTL values 24-48 hours before the change to minimize downtime during the transition.

# Check nameserver propagation status
dig NS example.com +short

# Check A record propagation
dig A example.com +short

# Check from specific DNS server
dig @8.8.8.8 A example.com +short

# Check with TTL information
dig A example.com

Advanced DNS Configurations

Load Balancing with DNS

DNS can provide simple load balancing by returning different IP addresses for the same domain:

# Route 53 CLI example: Create geolocation-based routing
aws route53 change-resource-record-sets \
  --hosted-zone-id Z1D633PJN98FT9 \
  --change-batch '{
    "Changes": [
      {
        "Action": "CREATE",
        "ResourceRecordSet": {
          "Name": "example.com",
          "Type": "A",
          "SetIdentifier": "US-East",
          "GeoLocation": {
            "CountryCode": "US",
            "SubdivisionCode": "NY"
          },
          "TTL": 60,
          "ResourceRecords": [
            {
              "Value": "203.0.113.10"
            }
          ]
        }
      },
      {
        "Action": "CREATE",
        "ResourceRecordSet": {
          "Name": "example.com",
          "Type": "A",
          "SetIdentifier": "Europe",
          "GeoLocation": {
            "ContinentCode": "EU"
          },
          "TTL": 60,
          "ResourceRecords": [
            {
              "Value": "203.0.113.20"
            }
          ]
        }
      },
      {
        "Action": "CREATE",
        "ResourceRecordSet": {
          "Name": "example.com",
          "Type": "A",
          "SetIdentifier": "Default",
          "GeoLocation": {
            "CountryCode": "*"
          },
          "TTL": 60,
          "ResourceRecords": [
            {
              "Value": "203.0.113.30"
            }
          ]
        }
      }
    ]
  }'

Health Checks and Failover

Some DNS providers offer health checks to automatically route traffic away from failing endpoints:

# Route 53 health check example
aws route53 create-health-check \
  --caller-reference $(date +%s) \
  --health-check-config '{
    "IPAddress": "203.0.113.10",
    "Port": 80,
    "Type": "HTTP",
    "ResourcePath": "/health",
    "RequestInterval": 30,
    "FailureThreshold": 3
  }'

# Create failover routing policy
aws route53 change-resource-record-sets \
  --hosted-zone-id Z1D633PJN98FT9 \
  --change-batch '{
    "Changes": [
      {
        "Action": "CREATE",
        "ResourceRecordSet": {
          "Name": "example.com",
          "Type": "A",
          "SetIdentifier": "Primary",
          "Failover": "PRIMARY",
          "HealthCheckId": "health-check-id",
          "TTL": 60,
          "ResourceRecords": [
            {
              "Value": "203.0.113.10"
            }
          ]
        }
      },
      {
        "Action": "CREATE",
        "ResourceRecordSet": {
          "Name": "example.com",
          "Type": "A",
          "SetIdentifier": "Secondary",
          "Failover": "SECONDARY",
          "TTL": 60,
          "ResourceRecords": [
            {
              "Value": "203.0.113.20"
            }
          ]
        }
      }
    ]
  }'

Multi-region Deployments

For global applications, configure DNS to route users to the nearest region:

graph TD A[User in Europe] -->|DNS Query| B[DNS with Geo-routing] C[User in Asia] -->|DNS Query| B D[User in Americas] -->|DNS Query| B B -->|European IP| E[EU Data Center] B -->|Asian IP| F[Asia Data Center] B -->|Americas IP| G[US Data Center] E -.->|Replication| F E -.->|Replication| G F -.->|Replication| E F -.->|Replication| G G -.->|Replication| E G -.->|Replication| F

Subdomain Delegation

You can delegate control of a subdomain to a different set of nameservers:

# Example: Delegating api.example.com to different nameservers
api.example.com.       IN  NS      ns1.api-provider.com.
api.example.com.       IN  NS      ns2.api-provider.com.

# You may also need glue records if there's a circular dependency
ns1.api.example.com.   IN  A       203.0.113.40
ns2.api.example.com.   IN  A       203.0.113.41

DNSSEC (DNS Security Extensions)

DNSSEC adds cryptographic signatures to DNS records to prevent tampering:

  1. Generate key pairs for your domain
  2. Sign your DNS zone with the private key
  3. Publish the public key in your parent zone
  4. Enable DNSSEC validation
# Example: Configuring DNSSEC with Cloudflare API
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/zone_id/dnssec" \
     -H "Authorization: Bearer your_api_token" \
     -H "Content-Type: application/json" \
     --data '{"status":"active"}'

CDN Integration

What is a CDN?

A Content Delivery Network (CDN) is a distributed network of servers that delivers web content to users based on their geographic location:

graph LR A[Users] -->|Requests| B[CDN Edge Servers] B -->|Cache Hits| A B -->|Cache Misses| C[Origin Server] C -->|Content| B B -->|Cached Content| A subgraph "Edge Locations" D[North America] E[Europe] F[Asia] G[Australia] H[South America] end D --- B E --- B F --- B G --- B H --- B

CDN Integration Methods

There are several ways to integrate a CDN with your domain:

CNAME Method

Point your domain to the CDN's domain using a CNAME record:

www.example.com.       IN  CNAME   example-com.cdn-provider.net.

Limitations: Can't use for apex (root) domains, as they require A records, not CNAMEs.

ANAME/ALIAS Method

Some providers offer special records that act like CNAMEs but work for apex domains:

example.com.           IN  ALIAS   example-com.cdn-provider.net.
CDN Provider's DNS

Use the CDN provider's DNS service for your domain:

  1. Transfer DNS management to the CDN provider
  2. Configure the CDN through their interface
  3. They handle all the necessary DNS records

Popular CDN Providers

Cloudflare Setup Example

Cloudflare is a popular choice for combined DNS and CDN services:

  1. Create a Cloudflare account
  2. Add your domain
  3. Review and configure DNS records
  4. Update nameservers at your registrar
  5. Configure Cloudflare settings (SSL, caching, etc.)
# Example Cloudflare API call to enable HTTPS
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/zone_id/settings/ssl" \
     -H "Authorization: Bearer your_api_token" \
     -H "Content-Type: application/json" \
     --data '{"value":"full_strict"}'

AWS CloudFront Example

# Create CloudFront distribution with AWS CLI
aws cloudfront create-distribution \
  --origin-domain-name example-bucket.s3.amazonaws.com \
  --default-root-object index.html \
  --aliases example.com www.example.com \
  --default-cache-behavior '{
    "TargetOriginId": "example-bucket",
    "ViewerProtocolPolicy": "redirect-to-https",
    "AllowedMethods": {
      "Quantity": 2,
      "Items": ["GET", "HEAD"]
    },
    "CachedMethods": {
      "Quantity": 2,
      "Items": ["GET", "HEAD"]
    },
    "ForwardedValues": {
      "QueryString": false,
      "Cookies": {
        "Forward": "none"
      }
    },
    "MinTTL": 0,
    "DefaultTTL": 86400,
    "MaxTTL": 31536000
  }'

Domain Security

Domain Hijacking Protection

Domain hijacking occurs when attackers gain unauthorized access to your domain registration:

DNS Security

Protect your DNS configuration:

CAA Records Example
; Allow Let's Encrypt to issue certificates
example.com.           IN  CAA     0 issue "letsencrypt.org"

; Allow Sectigo for wildcard certificates
example.com.           IN  CAA     0 issuewild "sectigo.com"

; Send violation reports to admin
example.com.           IN  CAA     0 iodef "mailto:admin@example.com"
Email Authentication Records
; SPF record - Specify authorized email senders
example.com.           IN  TXT     "v=spf1 ip4:203.0.113.10 include:_spf.example.com -all"

; DKIM record - Email signing key
mail._domainkey.example.com. IN TXT "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDHY..."

; DMARC record - Policy for handling authentication failures
_dmarc.example.com.    IN  TXT     "v=DMARC1; p=reject; rua=mailto:dmarc@example.com; pct=100"

HTTP Security Headers

Configure security headers for your website:

# Nginx configuration for security headers
server {
    listen 443 ssl http2;
    server_name example.com www.example.com;
    
    # SSL configuration
    ssl_certificate /path/to/certificate.pem;
    ssl_certificate_key /path/to/key.pem;
    
    # Security headers
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.example.com; style-src 'self' 'unsafe-inline' https://cdn.example.com; img-src 'self' data: https://cdn.example.com; connect-src 'self' https://api.example.com;" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
}

Domain Monitoring and Maintenance

Regular Audits

Periodically review your domain and DNS configuration:

Monitoring Tools

# Simple DNS monitoring script
#!/bin/bash
DOMAINS="example.com www.example.com api.example.com"
EXPECTED_IP="203.0.113.10"
ALERT_EMAIL="admin@example.com"

for domain in $DOMAINS; do
  resolved_ip=$(dig +short A $domain)
  
  if [ "$resolved_ip" != "$EXPECTED_IP" ]; then
    echo "ALERT: $domain is resolving to $resolved_ip instead of $EXPECTED_IP" | \
    mail -s "DNS Resolution Error for $domain" $ALERT_EMAIL
  fi
done

Automation and Infrastructure as Code

Manage DNS configuration as code for better control and versioning:

# Terraform example for DNS management
provider "aws" {
  region = "us-east-1"
}

resource "aws_route53_zone" "main" {
  name = "example.com"
}

resource "aws_route53_record" "www" {
  zone_id = aws_route53_zone.main.zone_id
  name    = "www.example.com"
  type    = "A"
  ttl     = "300"
  records = ["203.0.113.10"]
}

resource "aws_route53_record" "api" {
  zone_id = aws_route53_zone.main.zone_id
  name    = "api.example.com"
  type    = "A"
  ttl     = "300"
  records = ["203.0.113.11"]
}

resource "aws_route53_record" "mail" {
  zone_id = aws_route53_zone.main.zone_id
  name    = "example.com"
  type    = "MX"
  ttl     = "300"
  records = ["10 mail.example.com"]
}

Disaster Recovery Planning

Prepare for domain-related emergencies:

Special Considerations for Production Environments

Zero-downtime Domain Transition

When switching providers or changing IP addresses:

  1. Reduce TTL - Lower TTLs 24-48 hours before the change
  2. Verify new configuration - Test before switching
  3. Make the change - Update records during off-peak hours
  4. Monitor closely - Watch for resolution issues
  5. Increase TTL - Return to normal values once stable

Multi-environment Setup

Standard practice for development workflow:

Microservices Architecture

Domain strategies for microservices:

graph TD A[Client] --> B[api.example.com] B --> C[API Gateway] C --> D[auth.internal] C --> E[users.internal] C --> F[payments.internal] C --> G[orders.internal] D --> H[Auth Database] E --> I[User Database] F --> J[Payment Database] G --> K[Order Database]

Blue-Green Deployments

Use DNS for zero-downtime deployments:

  1. Deploy new version to "green" environment
  2. Test the "green" environment thoroughly
  3. Switch DNS to point to "green" environment
  4. Monitor for issues
  5. If problems occur, switch back to "blue"
  6. Otherwise, maintain "blue" as rollback option
sequenceDiagram participant Client participant DNS participant Blue as Blue Environment participant Green as Green Environment Note over Blue: Running v1.0 Note over Green: Deploy v1.1 Client->>DNS: Request example.com DNS->>Client: IP for Blue Client->>Blue: Request content Note over Green: Testing v1.1 Note over DNS: Update DNS records Client->>DNS: Request example.com DNS->>Client: IP for Green Client->>Green: Request content Note over Blue: Standby for rollback

Troubleshooting Common Domain Issues

DNS Resolution Problems

# Troubleshooting commands for DNS issues
# Check nameservers
dig NS example.com +short

# Check A record
dig A example.com +short

# Check CNAME record
dig CNAME www.example.com +short

# Check MX record
dig MX example.com +short

# Get full DNS response
dig example.com ANY +noall +answer

# Check specific nameserver
dig @ns1.example.com example.com A

# Trace DNS resolution
dig +trace example.com

# Check DNS propagation globally
# (Use online tools like whatsmydns.net)

SSL Certificate Issues

# Check SSL certificate details
openssl s_client -showcerts -connect example.com:443

# Check certificate expiration
echo | openssl s_client -servername example.com -connect example.com:443 2>/dev/null | openssl x509 -noout -dates

# Test HTTPS connection
curl -IL https://example.com

Email Delivery Issues

# Check mail server configuration
dig MX example.com +short

# Check SPF record
dig TXT example.com +short

# Check DKIM record
dig TXT mail._domainkey.example.com +short

# Check DMARC record
dig TXT _dmarc.example.com +short

# Test mail server connection
telnet mail.example.com 25

Practical Exercise: Domain and DNS Configuration

Exercise Overview

In this exercise, you'll configure a domain and DNS for a multi-environment application:

  1. Register a test domain (or use a sandbox domain)
  2. Configure DNS with a provider
  3. Set up A records for different environments
  4. Configure email records (MX, SPF)
  5. Set up a CDN for the production environment
  6. Implement security best practices
  7. Test and monitor the configuration

Exercise Requirements

For detailed exercise instructions and starter code, refer to the course repository: Domain & DNS Workshop Repository (Example URL)

Conclusion and Key Takeaways

Proper domain and DNS configuration is essential for production applications. Key takeaways from this lecture include:

Remember: Your domain is your application's front door on the internet. Investing time in proper domain management pays dividends in reliability, performance, and security.

Additional Resources

Documentation

Tools

Books and Learning Resources

Next Lecture Preview: Final Production Deployment

In our next and final session of this module, we'll pull everything together for a successful production deployment, covering: