# Route 53: DNS for your apps

Create a private hosted zone in the console, add A, CNAME and alias records, pick a routing policy, add health checks, and clean up without buying a domain.

Course: [AWS for DevOps](https://devops.rajeev.pro/courses/aws), lesson 8. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/aws/08-route-53

## What you will learn

- Distinguish public and private hosted zones.
- Choose A, AAAA, CNAME and alias records correctly.
- Explain simple, weighted, latency, failover and geolocation routing.
- Use health checks and understand their limits.
- Avoid registering a domain when a hosted zone is all the application needs.

## DNS in one minute

Before DNS, a client would need a server's IP address written directly into configuration. When the server
moved, every client with the old address had to be updated. DNS lets a client ask for a stable name and receive
the address selected by a resolver.

**Domain Name System (DNS)** maps names such as `api.example.com` to records that clients can use. Amazon Route
53 hosts DNS zones and answers queries; it can also check endpoint health and register domains. A resolver asks
the authoritative servers for the record, caches the answer for its time to live (TTL), and returns it to the
client. The name Route 53 refers to DNS's port number, 53.

Everything below was done in a real practice account with a **private** zone, which costs nothing if deleted
within 12 hours, and then deleted. No domain was bought and no public DNS changed.

In this lesson you'll create a private hosted zone linked to a VPC, add records and inspect routing policies.
Private DNS answers are visible only to associated VPCs, so this exercise does not change a public website.

> **Figure.** Step one, the browser asks its DNS resolver for www.example.com. If the resolver has a cached answer within its TTL it replies at once. Otherwise, step two, it asks a root server, which points to the .com servers; step three, the .com servers point to the domain's authoritative name servers, which are Route 53 when the hosted zone lives there; step four, Route 53 answers from the hosted zone's record, for example an alias record to a load balancer; step five, the resolver caches the answer for the record's TTL and returns it to the browser.
>
> The resolver walks root, .com and Route 53 once, then answers from its cache until the TTL runs out.

## Hosted zones

A **hosted zone** is the authoritative container for records under a domain name. Without a zone, the DNS
system has no place where your team can define the answers for `academy.internal` or `example.com`. Route 53
offers public zones, queried through public DNS, and private zones, associated with one or more VPCs.

When a resolver asks about a name, Route 53 finds the matching zone and returns the record data and TTL. A
private zone answers only for queries coming from associated VPCs with DNS support enabled. A public zone is
reachable through the public DNS hierarchy, but creating it alone does not make it authoritative for a
registered domain; the registrar's name-server delegation must point to it.

The two kinds of zone serve different audiences:

| Zone        | Answers                              | Use for                                        |
| ----------- | ------------------------------------ | ---------------------------------------------- |
| **Public**  | anyone on the internet               | your website and APIs (`example.com`)          |
| **Private** | only from VPCs you associate with it | internal service names (`db.academy.internal`) |

**Route 53 → Hosted zones → Create hosted zone:**

> **Figure.** Create hosted zone: (1) domain name academy.internal, (2) type Private hosted zone selected instead of Public, (3) VPC to associate: Region Asia Pacific (Mumbai) and the default VPC.
>
> (1) The domain. (2) Private: answers only inside the VPCs you pick. (3) The VPC that can resolve it.

A private zone needs the VPC's **DNS hostnames** and **DNS resolution** settings turned on; the default VPC and
lesson 4's wizard VPC have both. A new zone starts with two records Route 53 manages for you: **NS** (the name
servers answering for the zone) and **SOA** (zone metadata).

Use a private zone for internal service names and a public zone for names customers must resolve on the
internet. A common mistake is creating a public zone and assuming the domain now points to it. Change the
registrar's name-server delegation only when you intend to move live DNS; this lesson uses a private zone and
does not touch a public domain.

## Records

> **Figure.** The private hosted zone academy.internal with 5 records: NS and SOA for the zone, (1) api.academy.internal A 10.0.0.10, web.academy.internal A 10.0.0.20, and (2) www.academy.internal CNAME web.academy.internal, each with routing Simple and TTL 300. (3) Create record button.
>
> (1) An A record. (2) A CNAME pointing one name at another. (3) Create record adds more.

| Type             | Points to                                                    | Example                                      |
| ---------------- | ------------------------------------------------------------ | -------------------------------------------- |
| **A** / **AAAA** | an IPv4 / IPv6 address                                       | `api.academy.internal → 10.0.0.10`           |
| **CNAME**        | another name (never at the zone apex)                        | `www → web.academy.internal`                 |
| **Alias**        | an AWS resource: ALB, CloudFront, S3 website, another record | `example.com → my-alb-123.elb.amazonaws.com` |
| **MX** / **TXT** | mail servers / text, such as domain verification             | `TXT "v=spf1 …"`                             |

**Alias** is Route 53's own record: it works at the zone apex (`example.com` itself, where CNAMEs aren't
allowed), follows the target's IP addresses as they change, and queries to AWS targets are free. Point domains at
lesson 5's load balancer or lesson 9's CloudFront with an alias.

**TTL** (time to live) is how long resolvers cache an answer. 300 seconds is a sensible default; lower it a day
before a planned change so the switch spreads quickly.

> **Figure.** Create record, quick create: (1) record name (a subdomain of academy.internal), (2) record type A, routes traffic to an IPv4 address, value, TTL 300 with 1m, 1h and 1d shortcuts, alias toggle, (3) routing policy Simple routing.
>
> (1) The name. (2) The type. (3) The routing policy: Simple returns the same answer to everyone.

## Routing policies

The record wizard shows every policy:

> **Figure.** Create record wizard, Choose routing policy: Simple routing (selected), Weighted, Geolocation, Latency, Failover, Multivalue answer and Geoproximity, each with a short description and diagram. Weighted, Latency and Failover are highlighted.
>
> Simple, plus six ways to choose between several answers. (1) Weighted, (2) Failover and (3) Latency are the ones you'll use most.

| Policy          | Answers with                                   | Use for                           |
| --------------- | ---------------------------------------------- | --------------------------------- |
| **Simple**      | the same value for everyone                    | one endpoint                      |
| **Weighted**    | each record in proportion to its weight        | canary releases: 90% old, 10% new |
| **Latency**     | the Region with the lowest latency to the user | apps running in several Regions   |
| **Failover**    | primary while healthy, otherwise secondary     | disaster recovery                 |
| **Geolocation** | by the user's country or continent             | legal or language requirements    |
| **Multivalue**  | up to eight healthy records at random          | simple client-side spreading      |

> **Video.** [Master AWS Route 53: Hands-On Geolocation, Weighted & Failover Routing](https://www.youtube.com/watch?v=0Il_9_FlSpI) (MechCloud Academy)

## Health checks

> **Figure.** Create health check: resource Endpoint highlighted, with Calculated health check and CloudWatch alarm as alternatives, endpoint by IP address or domain name, protocol HTTP, and an IP, port and path field.
>
> An endpoint health check calls a URL from locations around the world and marks it unhealthy when it fails.

Attach a health check to a failover or weighted record, and Route 53 stops returning an unhealthy answer. Check a
path that proves the app works (`/health` that touches the database), not just that a port is open. Health checks
cost a little per month each, so this lesson only opened the form.

> **Video.** [Amazon Route 53: Health Checks and DNS Failover](https://www.youtube.com/watch?v=Kxpl0ICzQV0) (Stormit)

## Domain registration

When a team needs a new public name, it must register the domain with a registrar and then publish the DNS
records that direct traffic to its services. Route 53 can act as both registrar and DNS host, but those are
separate jobs: registration reserves the name; a hosted zone contains its records.

**Registered domains → Register domains** purchases a domain through Route 53 and creates its public hosted
zone. If a domain is registered elsewhere, create the zone and update the registrar's name-server delegation
to the four servers in its NS record. DNS changes can take time to propagate because resolvers cache answers.
Registration costs money and renews yearly, so it is not part of a practice mission.

Register through Route 53 only when its pricing, supported suffix and renewal terms fit the requirement. If
you already own the domain elsewhere, keep the registrar and delegate DNS to Route 53 instead. A common
mistake is treating a zone as proof that you own a domain; only registration gives you that ownership, and a
public zone that is not delegated will not answer authoritative lookups for visitors.

> **Delete records before the zone.** Route 53 refuses to delete a hosted zone that still has records other than NS and SOA. Delete your records first, then the zone. A hosted zone kept longer than 12 hours is billed for the month.

> **In production.** Keep public zones in code (Terraform or CloudFormation), use alias records for AWS endpoints, keep TTLs short around migrations, use private zones for internal names instead of hard-coded IPs, and protect the domain with registrar lock and auto-renew so it can never lapse.

## Mission: Private DNS for a VPC

Create a private hosted zone attached to your default VPC, add two A records and a CNAME, list them, then delete the records and the zone and confirm it's gone.

- You need: An AWS account and the AWS CLI configured for ap-south-1
- You'll have: Five records (NS, SOA, two A, one CNAME), then no academy.internal zone

```sh
$ VPC=$(aws ec2 describe-vpcs --filters Name=isDefault,Values=true --query 'Vpcs[0].VpcId' --output text)
$ Z=$(aws route53 create-hosted-zone --name academy.internal --caller-reference academy-$RANDOM \
    --vpc VPCRegion=ap-south-1,VPCId=$VPC --query HostedZone.Id --output text)
$ cat > rec.json <<'EOF'
{"Changes":[
 {"Action":"CREATE","ResourceRecordSet":{"Name":"api.academy.internal","Type":"A","TTL":300,"ResourceRecords":[{"Value":"10.0.0.10"}]}},
 {"Action":"CREATE","ResourceRecordSet":{"Name":"web.academy.internal","Type":"A","TTL":300,"ResourceRecords":[{"Value":"10.0.0.20"}]}},
 {"Action":"CREATE","ResourceRecordSet":{"Name":"www.academy.internal","Type":"CNAME","TTL":300,"ResourceRecords":[{"Value":"web.academy.internal"}]}}]}
EOF
$ aws route53 change-resource-record-sets --hosted-zone-id $Z --change-batch file://rec.json
$ aws route53 list-resource-record-sets --hosted-zone-id $Z --query 'ResourceRecordSets[].[Name,Type,ResourceRecords[0].Value]' --output text
academy.internal.	NS	ns-1536.awsdns-00.co.uk.
academy.internal.	SOA	ns-1536.awsdns-00.co.uk. awsdns-hostmaster.amazon.com. 1 7200 900 1209600 86400
api.academy.internal.	A	10.0.0.10
web.academy.internal.	A	10.0.0.20
www.academy.internal.	CNAME	web.academy.internal
$ sed 's/"CREATE"/"DELETE"/g' rec.json > del.json
$ aws route53 change-resource-record-sets --hosted-zone-id $Z --change-batch file://del.json
$ aws route53 delete-hosted-zone --id $Z
$ aws route53 list-hosted-zones-by-name --dns-name academy.internal --query 'HostedZones[?Name==`academy.internal.`]'
[]
```

Your name servers will differ. A delete batch must match each record exactly, which is why reusing the create
file with `DELETE` is the safe way to remove them.

## Try it

- Create a private hosted zone associated with a VPC.
- Add A and CNAME records and list them with the CLI.
- Inspect the default SOA and NS records.
- Delete custom records before deleting the hosted zone.

## Quiz

1. Which hosted zone resolves names only inside associated VPCs?
   - Public hosted zone
   - **Private hosted zone** (answer)
   - Registrar zone
   Why: A private hosted zone answers queries from associated VPCs through Route 53 Resolver.

2. Which record maps a name directly to an IPv4 address?
   - **A** (answer)
   - AAAA
   - CNAME
   Why: An A record contains an IPv4 address. AAAA is for IPv6 and CNAME points at another DNS name.

3. Which routing policy splits traffic by configured proportions?
   - **Weighted** (answer)
   - Simple
   - Geolocation
   Why: Weighted records distribute traffic according to weights when the names and record types match.

4. What is the main reason to use an alias record in AWS?
   - **It can target selected AWS resources without a CNAME at the zone apex** (answer)
   - It encrypts DNS
   - It registers a domain
   Why: Alias records can point at supported AWS resources and work where a CNAME cannot, such as the zone apex.

5. What must be removed before deleting a hosted zone?
   - The default SOA and NS records
   - **Custom records** (answer)
   - The VPC itself
   Why: Route 53 deletes a hosted zone only after non-default resource record sets are removed.

## Resources

- [Amazon Route 53 Developer Guide](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/Welcome.html) (AWS Docs)
- [Working with hosted zones](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/AboutHostedZones.html) (AWS Docs)
- [Choosing a routing policy](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy.html) (AWS Docs)
- [Route 53 health checks](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/health-checks-how-route-53-chooses-an-endpoint.html) (AWS Docs)
- [Route 53 pricing](https://aws.amazon.com/route53/pricing/) (AWS)
