# Services, Ingress and load balancing

How Pods find each other and how users reach them: Pod networking, ClusterIP and NodePort Services, cluster DNS, and real AWS load balancers from a LoadBalancer Service and an Ingress.

Course: [Kubernetes & Helm](https://devops.rajeev.pro/courses/kubernetes), lesson 5. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/kubernetes/05-services-networking

## What you will learn

- Explain how Pods get IP addresses and why you never call them directly
- Create ClusterIP and NodePort Services and see their endpoints
- Resolve a Service by DNS name from inside the cluster
- Install the AWS Load Balancer Controller and expose an app with an NLB and an ALB
- Diagnose an Ingress rule that points at a missing Service

> **Lab status.** **Verified lab:** Services, endpoints, DNS, the AWS Load Balancer Controller, a real NLB and ALB on EKS, and the broken-Ingress case. The output shown is real. <br />**Code walkthrough:** Gateway API (explained, not run). <br />**Cloud lab:** load balancers need EKS or another cloud; on kind, use port-forward or NodePort.

Pods get new IP addresses every time they're replaced, and there are usually several of them. This
lesson builds up from the Pod network to a Service with one stable name, to real AWS load balancers that
users on the internet can reach.

## Pod networking

Kubernetes has one simple rule: **every Pod gets its own IP address, and every Pod can reach every other
Pod directly**, across nodes, without NAT. How that's done depends on the network plugin (CNI). On EKS,
the **VPC CNI** gives Pods real addresses from the VPC subnets.

> **Figure.** A VPC in ap-south-1 with two t3.medium worker nodes, each holding at most 17 Pods. Node ip-10-42-0-115 runs shop-web d7mwm at 10.42.5.89 and shop-web zl6qc at 10.42.3.48. Node ip-10-42-28-149 runs shop-web xfdh5 at 10.42.19.142 and coredns at 10.42.29.171. In each node the VPC CNI, the aws-node DaemonSet, attaches network interfaces and gives each Pod one secondary IP from the subnet. Arrow 1: 10.42.3.48 sends straight to 10.42.19.142 on the other node, with no NAT and no overlay. Above, an AWS load balancer with target-type ip sends requests straight to a Pod IP.
>
> On EKS a Pod's IP is a real VPC address, so other Pods and load balancers reach it directly.

The shop-web Pods from lesson 4:

```text
$ kubectl get pods -l app=shop-web -o wide
NAME                        READY   STATUS    RESTARTS   AGE     IP             NODE                                          NOMINATED NODE   READINESS GATES
shop-web-6c674ff8df-d7mwm   1/1     Running   0          3m9s    10.42.5.89     ip-10-42-0-115.ap-south-1.compute.internal    <none>           <none>
shop-web-6c674ff8df-xfdh5   1/1     Running   0          3m38s   10.42.19.142   ip-10-42-28-149.ap-south-1.compute.internal   <none>           <none>
shop-web-6c674ff8df-zl6qc   1/1     Running   0          2m13s   10.42.3.48     ip-10-42-0-115.ap-south-1.compute.internal    <none>           <none>
```

`10.42.5.89` is a real address in the VPC, so a load balancer can send traffic straight to the Pod. The
catch: each node can hold only as many Pods as its network interfaces allow (17 on a `t3.medium`). The
Advanced lesson shows that limit on a real node.

By default, any Pod can talk to any other Pod, in any namespace. NetworkPolicies (lesson 8) restrict that.

## Services

A **Service** gives a set of Pods one stable virtual IP and DNS name, and spreads traffic across them. It
finds its Pods by **label selector**:

```yaml
# 05-services.yaml
apiVersion: v1
kind: Service
metadata:
  name: shop-web
spec:
  selector:
    app: shop-web # every Pod with this label is a backend
  ports:
    - port: 80 # the Service's port
      targetPort: 8080 # the container's port
---
apiVersion: v1
kind: Service
metadata:
  name: shop-web-nodeport
spec:
  type: NodePort
  selector:
    app: shop-web
  ports:
    - port: 80
      targetPort: 8080
      nodePort: 30080 # also open on every node's IP
```

```text
$ kubectl get service shop-web shop-web-nodeport
NAME                TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)        AGE
shop-web            ClusterIP   172.20.14.2   <none>        80/TCP         6s
shop-web-nodeport   NodePort    172.20.9.51   <none>        80:30080/TCP   5s
$ kubectl get endpointslices -l kubernetes.io/service-name=shop-web
NAME             ADDRESSTYPE   PORTS   ENDPOINTS                            AGE
shop-web-52sf8   IPv4          8080    10.42.5.89,10.42.3.48,10.42.19.142   10s
```

The **EndpointSlice** lists the three Pod IPs from above. Kubernetes keeps it updated as Pods come and go,
and only **ready** Pods (passing their readiness probe) are listed.

| Type                         | Reachable from                              | Use for                           |
| ---------------------------- | ------------------------------------------- | --------------------------------- |
| **ClusterIP** (default)      | Inside the cluster only                     | Service-to-service calls          |
| **NodePort**                 | Any node's IP on a port 30000–32767         | Quick tests; rarely in production |
| **LoadBalancer**             | The internet, through a cloud load balancer | Exposing one Service directly     |
| Headless (`clusterIP: None`) | DNS returns the Pod IPs                     | StatefulSets (lesson 12)          |

### Load balancing and DNS

Six calls to the Service from short-lived busybox Pods (one line per request):

```text
{"version": "v1", "pod": "shop-web-6c674ff8df-zl6qc", "greeting": "Hello from Kubernetes", "uptime_seconds": 137}
{"version": "v1", "pod": "shop-web-6c674ff8df-d7mwm", "greeting": "Hello from Kubernetes", "uptime_seconds": 199}
{"version": "v1", "pod": "shop-web-6c674ff8df-zl6qc", "greeting": "Hello from Kubernetes", "uptime_seconds": 151}
{"version": "v1", "pod": "shop-web-6c674ff8df-zl6qc", "greeting": "Hello from Kubernetes", "uptime_seconds": 158}
{"version": "v1", "pod": "shop-web-6c674ff8df-zl6qc", "greeting": "Hello from Kubernetes", "uptime_seconds": 165}
{"version": "v1", "pod": "shop-web-6c674ff8df-zl6qc", "greeting": "Hello from Kubernetes", "uptime_seconds": 171}
```

Different Pods answer, but not in neat rotation: kube-proxy picks a backend at random for each new
connection, so six requests aren't enough to look even. (kubectl printed each line twice, its log fallback
for very short-lived Pods; they're shown once here.)

The name `shop-web` works because of **cluster DNS** (CoreDNS). Every Service gets the name
`<service>.<namespace>.svc.cluster.local`:

```text
$ kubectl run dns --image=busybox:1.37 --restart=Never --rm -i --quiet -- nslookup shop-web.default.svc.cluster.local
Server:		172.20.0.10
Address:	172.20.0.10:53

Name:	shop-web.default.svc.cluster.local
Address: 172.20.14.2
```

It resolves to the Service's ClusterIP from above. Within the same namespace, the short name `shop-web` is
enough; from another namespace, use `shop-web.default`.

## Real load balancers on AWS

On EKS, the **AWS Load Balancer Controller** watches Services and Ingresses and creates AWS load balancers
for them. It needs AWS permissions, given here through EKS Pod Identity (set up with the cluster in
lesson 3), and it's installed with Helm:

```text
$ helm repo add eks https://aws.github.io/eks-charts
"eks" has been added to your repositories
$ helm install aws-load-balancer-controller eks/aws-load-balancer-controller -n kube-system \
    --set clusterName=academy --set serviceAccount.name=aws-load-balancer-controller \
    --set region=ap-south-1 --set vpcId=<vpc-id> --wait
NAME: aws-load-balancer-controller
NAMESPACE: kube-system
STATUS: deployed
REVISION: 1
$ kubectl get deployment -n kube-system aws-load-balancer-controller
NAME                           READY   UP-TO-DATE   AVAILABLE   AGE
aws-load-balancer-controller   2/2     2            2           21s
```

### A LoadBalancer Service becomes an NLB

```yaml
# 05-loadbalancer.yaml
apiVersion: v1
kind: Service
metadata:
  name: shop-web-lb
  annotations:
    service.beta.kubernetes.io/aws-load-balancer-type: external
    service.beta.kubernetes.io/aws-load-balancer-nlb-target-type: ip # send straight to Pod IPs
    service.beta.kubernetes.io/aws-load-balancer-scheme: internet-facing
spec:
  type: LoadBalancer
  selector:
    app: shop-web
  ports:
    - port: 80
      targetPort: 8080
```

## Ingress and Gateway API

A LoadBalancer Service gives **one** load balancer per Service, at layer 4 (TCP). An **Ingress** describes
HTTP routing (hosts and paths) for many Services behind **one** load balancer. On EKS, the controller turns
it into an **Application Load Balancer**:

```yaml
# 05-ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: shop
  annotations:
    alb.ingress.kubernetes.io/scheme: internet-facing
    alb.ingress.kubernetes.io/target-type: ip
    alb.ingress.kubernetes.io/healthcheck-path: /healthz
spec:
  ingressClassName: alb
  rules:
    - http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: shop-web
                port:
                  number: 80
```

A few minutes later both had public addresses, and the app answered from the internet:

```text
$ kubectl get ingress shop
NAME   CLASS   HOSTS   ADDRESS                                                              PORTS   AGE
shop   alb     *       k8s-default-shop-88ce9c933a-837023423.ap-south-1.elb.amazonaws.com   80      4m41s
$ kubectl get service shop-web-lb
NAME          TYPE           CLUSTER-IP       EXTERNAL-IP                                                                     PORT(S)        AGE
shop-web-lb   LoadBalancer   172.20.154.171   k8s-default-shopwebl-0399cc1ecf-e78d5867a18483ac.elb.ap-south-1.amazonaws.com   80:32002/TCP   4m41s
$ for i in 1 2 3 4; do curl -s http://k8s-default-shop-88ce9c933a-837023423.ap-south-1.elb.amazonaws.com/api; done
{"version": "v1", "pod": "shop-web-55d49ccc4b-mp85d", "greeting": "Namaste from a ConfigMap", "uptime_seconds": 230}
{"version": "v1", "pod": "shop-web-55d49ccc4b-vrdz4", "greeting": "Namaste from a ConfigMap", "uptime_seconds": 234}
{"version": "v1", "pod": "shop-web-55d49ccc4b-5xkmp", "greeting": "Namaste from a ConfigMap", "uptime_seconds": 231}
{"version": "v1", "pod": "shop-web-55d49ccc4b-vrdz4", "greeting": "Namaste from a ConfigMap", "uptime_seconds": 234}
```

(The greeting comes from the ConfigMap added in lesson 6.)

> **Figure.** A browser page served through the Application Load Balancer, on a red background, reading Namaste from a ConfigMap, version v1, and the name of the Pod that answered.
>
> shop-web in a browser, through the ALB: the greeting and colour come from a ConfigMap, and the Pod name shows which replica answered.

> **Figure.** The AWS EC2 console Load balancers page listing two active, internet-facing IPv4 load balancers in the cluster VPC: k8s-default-shopwebl of type network and k8s-default-shop of type application.
>
> The two load balancers Kubernetes created: an NLB for the LoadBalancer Service and an ALB for the Ingress.

With `target-type: ip`, the load balancers send traffic straight to Pod IPs, and the controller keeps the
target list in step with the Pods. Right after lesson 6 replaced the Pods, the ALB showed exactly that:

```text
+-----------+----------------+-------+
|  health   |      ip        | port  |
+-----------+----------------+-------+
|  draining |  10.42.3.48    |  8080 |
|  draining |  10.42.19.142  |  8080 |
|  healthy  |  10.42.2.204   |  8080 |
|  healthy  |  10.42.25.76   |  8080 |
...
```

Old Pod IPs **draining**, new ones **healthy**. Draining lets in-flight requests finish before a target is
removed, which is how rollouts stay zero-downtime behind an ALB.

**Gateway API** is the newer, more expressive successor to Ingress: separate `Gateway` and `HTTPRoute`
objects, with traffic splitting and header matching built in. Controllers, including the AWS one, support
it. New projects can start there; Ingress remains everywhere.

> **Figure.** Gateway API request flow: a client sends an HTTP request to a Gateway; an HTTPRoute attached to it applies a routing rule and forwards to a Service, which sends to two Pods.
>
> With Gateway API, the Gateway is the entry point, usually run by the platform team, and each app team attaches its own HTTPRoute. White background added.

### When an Ingress rule points at nothing

A common mistake: renaming a Service and forgetting the Ingress. The lab added a rule for `/old` pointing
at a Service that doesn't exist:

```text
$ kubectl describe ingress shop | sed -n '/Rules:/,/Annotations/p'
Rules:
  Host        Path  Backends
  ----        ----  --------
  *
              /old   shop-web-v0:80 (<error: services "shop-web-v0" not found>)
              /      shop-web:80 (10.42.31.211:8080,10.42.19.186:8080)
$ curl -s -o /dev/null -w '%{http_code}\n' http://k8s-default-shop-88ce9c933a-837023423.ap-south-1.elb.amazonaws.com/old
503
```

The controller still reported `Successfully reconciled`, so the events don't warn you. Users get a **503**
on that path. `kubectl describe ingress` shows the cause: the backend column says the Service isn't
found. Check the backends after every Service rename.

> **Load balancers outlive careless cleanup.** The load balancers belong to the Service and Ingress objects. Delete those first and wait for AWS to remove the load balancers, then destroy the cluster. Destroying the cluster first leaves orphaned load balancers billing by the hour.

## Mission: From Pod IPs to a public URL

Create the shop-web ClusterIP Service, list its EndpointSlice, resolve it with nslookup, and call it from a busybox Pod. On EKS, install the AWS Load Balancer Controller, apply the Ingress, and curl its address four times. Record which Pods answered.

- You need: The shop-web Deployment from lesson 4
- You'll have: ~/networking.txt

```sh
$ kubectl apply -f 05-services.yaml && kubectl get endpointslices -l kubernetes.io/service-name=shop-web > ~/networking.txt
$ kubectl run dns --image=busybox:1.37 --restart=Never --rm -i --quiet -- nslookup shop-web >> ~/networking.txt
$ kubectl apply -f 05-ingress.yaml
$ ALB=$(kubectl get ingress shop -o jsonpath='{.status.loadBalancer.ingress[0].hostname}')
$ for i in 1 2 3 4; do curl -s http://$ALB/api; done >> ~/networking.txt
```

The ALB takes two to three minutes to provision; until then the ADDRESS is empty and curl fails to
resolve. On kind, replace the Ingress steps with `kubectl port-forward service/shop-web 8080:80` and curl
`localhost:8080`.

## Try it

- Create the shop-web Service and run `kubectl get endpointslices -l kubernetes.io/service-name=shop-web`.
- Call the Service six times from busybox Pods and note which Pods answer.
- Run `nslookup shop-web.default.svc.cluster.local` from a busybox Pod.
- On EKS, apply the Ingress and wait for its ADDRESS, then curl it.
- Do the mini mission and keep `~/networking.txt`.

## Quiz

1. Why do you put a Service in front of Pods instead of using Pod IPs?
   - Pod IPs are not real
   - **Pods are replaced all the time and get new IPs; a Service keeps one stable name and IP and tracks the current Pods** (answer)
   - Services are faster
   Why: The Service's EndpointSlice is updated as Pods come and go, so callers always use the same name.

2. Which Service type gives you a cloud load balancer reachable from the internet?
   - ClusterIP
   - **LoadBalancer (or an Ingress handled by a controller)** (answer)
   - Headless
   Why: ClusterIP is internal only. On EKS, the AWS Load Balancer Controller turns a LoadBalancer Service into an NLB and an Ingress into an ALB.

3. An Ingress rule points at a Service that doesn't exist. What does a user get on that path?
   - The page from another Service
   - **A 503 from the load balancer, while kubectl describe ingress shows the backend error** (answer)
   - A 404 from Kubernetes
   Why: The ALB rule exists but has no healthy targets behind it. In the lab, curl returned 503 and describe showed "services shop-web-v0 not found".

## Resources

- [Services](https://kubernetes.io/docs/concepts/services-networking/service/) (Kubernetes)
- [DNS for Services and Pods](https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/) (Kubernetes)
- [Ingress](https://kubernetes.io/docs/concepts/services-networking/ingress/) (Kubernetes)
- [Gateway API](https://gateway-api.sigs.k8s.io/) (Kubernetes SIG Network)
- [AWS Load Balancer Controller](https://kubernetes-sigs.github.io/aws-load-balancer-controller/latest/) (Kubernetes SIGs)
