The hard way · Part 5

Routes, tunnel and DNS

Routes between nodes, a way in for kubectl, and names.

Status

The scripts are checked (flags, local control plane run, AWS --dry-run) but have not yet been run end to end on AWS. The outputs below are real where marked; elsewhere the page says what to look for.

Three small things turn a set of machines into a cluster you can use: a route per node, a tunnel for kubectl, and DNS.

1Create the files

Same folder. Open each file below and use its copy button: it creates the file for you.

$ cd ~/k8s-hard-way
manifests/rbac-apiserver-to-kubelet.yaml (25 lines)
$ cat > manifests/rbac-apiserver-to-kubelet.yaml <<'SCRIPT_EOF'
# Why this exists: when you run `kubectl logs` or `kubectl exec`, the API server calls the
# kubelet on the node. The kubelet asks the API server "may this caller do that?"
# (authorization mode: Webhook). Our API server authenticates to kubelets as the user
# "kubernetes" (its own certificate). This grants that user exactly the kubelet APIs it needs.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: system:kube-apiserver-to-kubelet
rules:
  - apiGroups: [""]
    resources: ["nodes/proxy", "nodes/stats", "nodes/log", "nodes/spec", "nodes/metrics"]
    verbs: ["*"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: system:kube-apiserver
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:kube-apiserver-to-kubelet
subjects:
  - apiGroup: rbac.authorization.k8s.io
    kind: User
    name: kubernetes
SCRIPT_EOF
manifests/coredns.yaml (109 lines)
$ cat > manifests/coredns.yaml <<'SCRIPT_EOF'
# CoreDNS: the cluster's DNS. It turns a name like "hello.default.svc.cluster.local" into the
# Service's address. The kubelet is already told to send every Pod's DNS lookups to
# 10.32.0.10 (CLUSTER_DNS_IP in config.env), so the Service below must have that address.
apiVersion: v1
kind: ServiceAccount
metadata:
  name: coredns
  namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: system:coredns
rules:
  - apiGroups: [""]
    resources: ["endpoints", "services", "pods", "namespaces"]
    verbs: ["list", "watch"]
  - apiGroups: ["discovery.k8s.io"]
    resources: ["endpointslices"]
    verbs: ["list", "watch"]
  - apiGroups: [""]
    resources: ["nodes"]
    verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: system:coredns
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:coredns
subjects:
  - kind: ServiceAccount
    name: coredns
    namespace: kube-system
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: coredns
  namespace: kube-system
data:
  Corefile: |
    .:53 {
        errors
        health { lameduck 5s }
        ready
        kubernetes cluster.local in-addr.arpa ip6.arpa {
          pods insecure
          fallthrough in-addr.arpa ip6.arpa
          ttl 30
        }
        forward . /etc/resolv.conf { max_concurrent 1000 }
        cache 30
        loop
        reload
        loadbalance
    }
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: coredns
  namespace: kube-system
spec:
  replicas: 2
  selector:
    matchLabels: { k8s-app: kube-dns }
  template:
    metadata:
      labels: { k8s-app: kube-dns }
    spec:
      serviceAccountName: coredns
      dnsPolicy: Default            # CoreDNS itself must NOT use cluster DNS
      containers:
        - name: coredns
          image: registry.k8s.io/coredns/coredns:COREDNS_VERSION
          args: ["-conf", "/etc/coredns/Corefile"]
          ports:
            - { name: dns, containerPort: 53, protocol: UDP }
            - { name: dns-tcp, containerPort: 53, protocol: TCP }
          livenessProbe:
            httpGet: { path: /health, port: 8080 }
          readinessProbe:
            httpGet: { path: /ready, port: 8181 }
          securityContext:
            allowPrivilegeEscalation: false
            capabilities: { add: ["NET_BIND_SERVICE"], drop: ["ALL"] }
            readOnlyRootFilesystem: true
          volumeMounts:
            - { name: config, mountPath: /etc/coredns, readOnly: true }
      volumes:
        - name: config
          configMap:
            name: coredns
            items: [{ key: Corefile, path: Corefile }]
---
apiVersion: v1
kind: Service
metadata:
  name: kube-dns
  namespace: kube-system
spec:
  selector: { k8s-app: kube-dns }
  clusterIP: 10.32.0.10
  ports:
    - { name: dns, port: 53, protocol: UDP }
    - { name: dns-tcp, port: 53, protocol: TCP }
SCRIPT_EOF
scripts/95-routes.sh (22 lines)
$ cat > scripts/95-routes.sh <<'SCRIPT_EOF'
#!/usr/bin/env bash
# 95 - Pod network routes.
#
# Each worker hands out Pod IPs from its own /24 (node-0: 10.200.0.0/24, node-1: 10.200.1.0/24).
# A Pod on node-0 that talks to a Pod on node-1 sends a packet to 10.200.1.x. Nothing in a
# VPC knows where that is, so we tell the VPC: "10.200.1.0/24 lives behind node-1".
# This is the whole "network plugin" of this cluster: a bridge on each node, plus these routes.
# (Without them, Pods on different nodes cannot reach each other. Try it: skip this and run 97.)
# The source/destination check was already turned off in 20-compute.sh.
source "$(dirname "$0")/../lib.sh"
confirm_account
RTB=$(state_need RTB)

route() {  # route CIDR INSTANCE_ID
  aws ec2 create-route --route-table-id "$RTB" --destination-cidr-block "$1" --instance-id "$2" >/dev/null 2>&1 \
    || aws ec2 replace-route --route-table-id "$RTB" --destination-cidr-block "$1" --instance-id "$2" >/dev/null
  log "$1 -> $2"
}
route "$NODE0_POD_CIDR" "$(state_need ID_node-0)"
route "$NODE1_POD_CIDR" "$(state_need ID_node-1)"
aws ec2 describe-route-tables --route-table-ids "$RTB" \
  --query 'RouteTables[0].Routes[].[DestinationCidrBlock,InstanceId||GatewayId,State]' --output text
SCRIPT_EOF
scripts/96-kubectl.sh (49 lines)
$ cat > scripts/96-kubectl.sh <<'SCRIPT_EOF'
#!/usr/bin/env bash
# 96 - reach the API server from your machine, with no inbound port.
#
#   ./96-kubectl.sh start    open a tunnel: your localhost:6443 -> the server's port 6443
#   ./96-kubectl.sh stop     close it
#   ./96-kubectl.sh status
#
# The tunnel is an SSM Session Manager port forward. Traffic goes out over HTTPS to AWS and
# back in to the instance's loopback. The API server's certificate lists 127.0.0.1, so
# https://127.0.0.1:6443 verifies. The first start also installs a kubectl matching the cluster
# and applies the one RBAC rule the API server needs to call kubelets.
source "$(dirname "$0")/../lib.sh"
PID="$STATE/tunnel.pid"; PORT=6443

install_kubectl() {
  [ -x "$STATE/bin/kubectl" ] && return
  log "downloading kubectl $K8S_VERSION to $STATE/bin"
  mkdir -p "$STATE/bin"; local base="https://dl.k8s.io/release/$K8S_VERSION/bin/linux/amd64"
  curl -fsSL -o "$STATE/bin/kubectl" "$base/kubectl"
  echo "$(curl -fsSL "$base/kubectl.sha256")  $STATE/bin/kubectl" | sha256sum -c - >/dev/null
  chmod +x "$STATE/bin/kubectl"
}

running() { [ -f "$PID" ] && kill -0 "$(cat "$PID")" 2>/dev/null; }

case "${1:-status}" in
  start)
    running && { log "tunnel already running"; exit 0; }
    ss -ltn 2>/dev/null | grep -q ":$PORT " && die "something is already listening on localhost:$PORT"
    install_kubectl; export KUBECTL="$STATE/bin/kubectl"   # used by kc() in lib.sh
    log "opening the tunnel to the API server"
    # setsid: own process group, so `stop` can end aws + session-manager-plugin together
    setsid nohup aws ssm start-session --target "$(state_need ID_server)" \
      --document-name AWS-StartPortForwardingSession \
      --parameters "{\"portNumber\":[\"6443\"],\"localPortNumber\":[\"$PORT\"]}" \
      > "$STATE/tunnel.log" 2>&1 < /dev/null &
    echo $! > "$PID"
    for _ in $(seq 1 20); do kc get --raw /healthz >/dev/null 2>&1 && break; sleep 2; done
    kc get --raw /healthz >/dev/null 2>&1 || die "the API server did not answer; see $STATE/tunnel.log"
    log "API server: $(kc get --raw /healthz)"
    kc apply -f "$ROOT/manifests/rbac-apiserver-to-kubelet.yaml"
    log "try:  .state/bin/kubectl --kubeconfig .state/kubeconfigs/admin.kubeconfig get nodes"
    ;;
  stop)
    if running; then kill -- "-$(ps -o pgid= "$(cat "$PID")" | tr -d ' ')" 2>/dev/null || kill "$(cat "$PID")"; log "tunnel closed"; fi
    rm -f "$PID" ;;
  status) running && echo "tunnel running (pid $(cat "$PID"))" || echo "tunnel not running" ;;
  *) die "usage: $0 start|stop|status" ;;
esac
SCRIPT_EOF
scripts/98-coredns.sh (7 lines)
$ cat > scripts/98-coredns.sh <<'SCRIPT_EOF'
#!/usr/bin/env bash
# 98 - cluster DNS (CoreDNS), so Pods can use Service names instead of addresses.
# Needs the tunnel (96-kubectl.sh start) and working Pod networking (90, 95).
source "$(dirname "$0")/../lib.sh"
sed "s/COREDNS_VERSION/$COREDNS_VERSION/" "$ROOT/manifests/coredns.yaml" | kc apply -f -
kc -n kube-system rollout status deployment/coredns --timeout=180s
kc -n kube-system get pods -l k8s-app=kube-dns -o wide
SCRIPT_EOF
$ chmod +x scripts/*.sh remote/*.sh 2>/dev/null; true

2Run it

$ scripts/95-routes.sh
$ scripts/96-kubectl.sh start     # keep it open while you work
$ scripts/98-coredns.sh
Why a route per node?
  • A Pod on node-0 sends a packet to 10.200.1.x. The VPC has no idea where that is.
  • 95-routes.sh adds: 10.200.1.0/24 goes to node-1, and 10.200.0.0/24 goes to node-0.
  • With the source/destination check off from part 1, this is the whole network plugin: a bridge per node, plus these routes.
How can kubectl reach a server with no inbound port?
  • 96-kubectl.sh start opens an SSM port forward: localhost:6443 on your machine goes to port 6443 on the server.
  • The connection goes out from your machine to AWS, and out from the instance to AWS. No inbound rule is involved.
  • The API server certificate lists 127.0.0.1, so https://127.0.0.1:6443 verifies.

3Check it

$ .state/bin/kubectl --kubeconfig .state/kubeconfigs/admin.kubeconfig get nodes
NAME     STATUS   ROLES    AGE   VERSION
node-0   Ready    <none>   ...   v1.37.2
node-1   Ready    <none>   ...   v1.37.2
$ ... get pods -n kube-system
coredns-...   1/1   Running   ...   (two of them)

Look for both nodes Ready and two CoreDNS Pods Running. A node stuck in NotReady usually means the CNI config is missing or the kubelet cannot reach the API server.

Remember

The tunnel is an outbound connection, so the cluster has no open door and you still have a way in.

Dig deeper with your AI

Guess first, then click for the TL;DR. Ask your AI for the full answer, and check it on your cluster or with kubectl explain.

  • What happens to Pod traffic if I skip the routes?

    Pods on the same node still talk. Pods on different nodes cannot, and Services that spread over both nodes fail half the time. The smoke test in part 6 shows it.

  • Why does 96-kubectl.sh download its own kubectl?

    kubectl may differ from the cluster by one minor version at most. The cluster is 1.37, so the script fetches the same version and checks its sha256.

  • What is the RBAC rule for?

    kubectl logs and exec make the API server call the kubelet. The kubelet asks whether the API server's identity (kubernetes) may. The rule says yes, for the kubelet APIs only.

  • Why 10.32.0.10 for DNS?

    The kubelet is told to send every Pod's lookups there. The Service created by CoreDNS must use exactly that address.

Inspired by Kubernetes The Hard Way. Text and scripts: CC BY-NC-SA 4.0.