# Setting up: a cluster, kubectl and your first deployment

Choose between a local cluster and a managed one, build a real EKS cluster with Terraform, connect kubectl, and run and reach your first deployment.

Course: [Kubernetes & Helm](https://devops.rajeev.pro/courses/kubernetes), lesson 3. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/kubernetes/03-setting-up

## What you will learn

- Choose between kind or minikube, and a managed cluster such as EKS, GKE or AKS
- Build an EKS cluster with Terraform and connect kubectl to it
- Read cluster-info, nodes and the system Pods, and say what each one is
- Create a Deployment and a Service and reach the app from inside the cluster

> **Lab status.** **Verified lab:** the EKS 1.37 cluster built with Terraform, kubectl connected, and the first Deployment and Service. The output shown is real. <br />**Code walkthrough:** the kind and minikube commands (they work on a laptop; this course's real output comes from EKS). <br />**Cloud lab:** EKS bills by the hour for the control plane and nodes. Destroy the cluster when you finish.

You need two things: a cluster, and `kubectl`, the command-line tool that talks to it. This lesson
compares the ways to get a cluster, builds a real one on AWS, and runs the first app on it.

## Local or managed

| Option              | Where it runs                             | Good for                               | Can't do                                  |
| ------------------- | ----------------------------------------- | -------------------------------------- | ----------------------------------------- |
| **kind**            | Docker containers on your laptop          | Learning, CI tests, free               | Cloud load balancers, real cloud disks    |
| **minikube**        | A VM or container on your laptop          | Learning, has add-ons like a dashboard | Same as kind                              |
| **EKS / GKE / AKS** | The cloud provider runs the control plane | Real workloads, cloud integrations     | Free: the control plane bills by the hour |

Start locally for free:

```sh
$ kind create cluster --name academy    # a one-node cluster in Docker, in about a minute
$ kubectl get nodes
```

Everything from lessons 4 to 9 and 11 to 15 works on kind. The cloud-specific parts (a real load
balancer from a Service or Ingress, EBS volumes, adding nodes automatically) need a managed cluster,
which is why this course's real output comes from EKS. Delete a kind cluster with
`kind delete cluster --name academy`.

## Build an EKS cluster

The lab built the cluster with Terraform, using the community modules most teams use:
`terraform-aws-modules/vpc` and `terraform-aws-modules/eks`. The important part:

```hcl
module "eks" {
  source  = "terraform-aws-modules/eks/aws"
  version = "~> 21.0"

  name               = "academy"
  kubernetes_version = "1.37"

  endpoint_public_access                   = true
  enable_cluster_creator_admin_permissions = true

  vpc_id     = module.vpc.vpc_id
  subnet_ids = module.vpc.public_subnets

  addons = {
    coredns    = {}
    kube-proxy = {}
    vpc-cni = {
      before_compute       = true
      configuration_values = jsonencode({ enableNetworkPolicy = "true" })
    }
    eks-pod-identity-agent = { before_compute = true }
    aws-ebs-csi-driver     = {}
    metrics-server         = {}
  }

  eks_managed_node_groups = {
    default = {
      instance_types = ["t3.medium"]
      min_size       = 2
      max_size       = 3
      desired_size   = 2
    }
  }
}
```

What each piece gives you:

- **The control plane** (API server, etcd, scheduler, controllers) is run by AWS across availability
  zones. You never see those machines.
- **A managed node group**: two `t3.medium` EC2 instances in an Auto Scaling group, which EKS keeps
  patched and can replace.
- **Add-ons**: CoreDNS (cluster DNS), kube-proxy (Service routing), the VPC CNI (Pod networking), the
  Pod Identity agent (AWS permissions for Pods), the EBS CSI driver (disks) and metrics-server (CPU and
  memory numbers). Later lessons use every one.
- **Public subnets with no NAT gateway**, to keep the lab cheap. Production puts nodes in private
  subnets.

The real apply:

```text
module.eks.aws_eks_cluster.this[0]: Creation complete after 8m9s [id=academy]
module.eks.module.eks_managed_node_group["default"].aws_eks_node_group.this[0]: Creation complete after 2m44s [id=academy:default-4f8ac3296b79a6f028385674b6]
module.eks.aws_eks_addon.this["coredns"]: Creation complete after 15s [id=academy:coredns]
module.eks.aws_eks_addon.this["aws-ebs-csi-driver"]: Creation complete after 45s [id=academy:aws-ebs-csi-driver]
module.eks.aws_eks_addon.this["metrics-server"]: Creation complete after 46s [id=academy:metrics-server]
Apply complete! Resources: 57 added, 0 changed, 0 destroyed.
```

57 resources in 13 minutes: the control plane alone took 8, the nodes almost 3. That's normal for EKS.
GKE and AKS are similar in spirit, with their own tools (`gcloud`, `az`).

> **Figure.** The Amazon EKS console showing the cluster academy: status Active, Kubernetes version 1.37, standard support until December 1, 2027, provider EKS, platform version eks.7, cluster health 0 issues, and the API server endpoint and OpenID Connect provider URL.
>
> The cluster in the EKS console: Kubernetes 1.37, active, with its API server endpoint.

## Connect kubectl

`kubectl` reads its connection details from `~/.kube/config`. For EKS, the AWS CLI writes them:

```text
$ aws eks update-kubeconfig --name academy --region ap-south-1
Added new context arn:aws:eks:ap-south-1:626159997645:cluster/academy to /home/rajeev/.kube/config
$ kubectl cluster-info
Kubernetes control plane is running at https://FE0C73F5A84A580DD549BA9B43A57B7B.gr7.ap-south-1.eks.amazonaws.com
CoreDNS is running at https://FE0C73F5A84A580DD549BA9B43A57B7B.gr7.ap-south-1.eks.amazonaws.com/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
$ kubectl version
Client Version: v1.37.2
Kustomize Version: v5.8.1
Server Version: v1.37.1-eks-577a51e
```

kubectl must be within one minor version of the cluster, so 1.37 against 1.37 is ideal. On EKS, kubectl
authenticates with your AWS identity: the context runs `aws eks get-token` behind the scenes, and the
cluster maps your IAM user to Kubernetes permissions through an **access entry**.

```text
$ kubectl get nodes -o wide
NAME                                          STATUS   ROLES    AGE     VERSION               INTERNAL-IP    EXTERNAL-IP    OS-IMAGE                        KERNEL-VERSION                            CONTAINER-RUNTIME
ip-10-42-0-115.ap-south-1.compute.internal    Ready    <none>   4m13s   v1.37.1-eks-6e7947a   10.42.0.115    3.111.215.75   Amazon Linux 2023.12.20261102   6.18.56-125.164.amzn2023.x86_64 (amd64)   containerd://2.3.7+unknown
ip-10-42-28-149.ap-south-1.compute.internal   Ready    <none>   4m13s   v1.37.1-eks-6e7947a   10.42.28.149   16.4.41.2      Amazon Linux 2023.12.20261102   6.18.56-125.164.amzn2023.x86_64 (amd64)   containerd://2.3.7+unknown
```

Two nodes, one in each subnet (`10.42.0.x` in ap-south-1a, `10.42.28.x` in ap-south-1b), running
Amazon Linux 2023 with containerd. And the system Pods:

```text
$ kubectl get pods -A
NAMESPACE     NAME                                  READY   STATUS    RESTARTS   AGE
kube-system   aws-node-dtf7s                        2/2     Running   0          4m22s
kube-system   aws-node-hqdfw                        2/2     Running   0          4m21s
kube-system   coredns-8966fd9f9-b7ppz               1/1     Running   0          2m46s
kube-system   coredns-8966fd9f9-ks7sc               1/1     Running   0          2m46s
kube-system   ebs-csi-controller-5b647c79f4-5nmnx   6/6     Running   0          2m42s
kube-system   ebs-csi-controller-5b647c79f4-v9wwg   6/6     Running   0          2m42s
kube-system   ebs-csi-node-lp977                    3/3     Running   0          2m42s
kube-system   ebs-csi-node-s9tfh                    3/3     Running   0          2m42s
kube-system   eks-pod-identity-agent-kzqvg          1/1     Running   0          4m22s
kube-system   eks-pod-identity-agent-mfk7m          1/1     Running   0          4m21s
kube-system   kube-proxy-6r4f2                      1/1     Running   0          2m47s
kube-system   kube-proxy-ldk86                      1/1     Running   0          2m47s
kube-system   metrics-server-596c8d7669-2hkj6       1/1     Running   0          2m45s
kube-system   metrics-server-596c8d7669-j7hrt       1/1     Running   0          2m45s
```

Notice the pattern: things that must run on **every** node (`aws-node`, `kube-proxy`, `ebs-csi-node`,
`eks-pod-identity-agent`) have one Pod per node, which is a DaemonSet. The rest run two copies for
availability. There's no API server or etcd here: on EKS those run in AWS's account.

## Your first deployment

```text
$ kubectl create deployment hello --image=626159997645.dkr.ecr.ap-south-1.amazonaws.com/shop-web:v1 --replicas=2
deployment.apps/hello created
$ kubectl get deployment,replicaset,pods -l app=hello -o wide
NAME                    READY   UP-TO-DATE   AVAILABLE   AGE   CONTAINERS   IMAGES                                                      SELECTOR
deployment.apps/hello   2/2     2            2           10s   shop-web     626159997645.dkr.ecr.ap-south-1.amazonaws.com/shop-web:v1   app=hello

NAME                               DESIRED   CURRENT   READY   AGE   CONTAINERS   IMAGES                                                      SELECTOR
replicaset.apps/hello-55c65f6b5f   2         2         2       10s   shop-web     626159997645.dkr.ecr.ap-south-1.amazonaws.com/shop-web:v1   app=hello,pod-template-hash=55c65f6b5f

NAME                         READY   STATUS    RESTARTS   AGE   IP             NODE                                          NOMINATED NODE   READINESS GATES
pod/hello-55c65f6b5f-28mnj   1/1     Running   0          11s   10.42.29.172   ip-10-42-28-149.ap-south-1.compute.internal   <none>           <none>
pod/hello-55c65f6b5f-srzjg   1/1     Running   0          11s   10.42.5.89     ip-10-42-0-115.ap-south-1.compute.internal    <none>           <none>
```

One command made three objects, the chain from lesson 1: the **Deployment** created a **ReplicaSet**
(note the `pod-template-hash`), which created two **Pods**. The scheduler put one on each node, and each
Pod got a real VPC address from the VPC CNI.

Pods come and go, so you never call their IPs directly. A **Service** gives them one stable name:

```text
$ kubectl expose deployment hello --port=80 --target-port=8080
service/hello exposed
$ kubectl get service hello
NAME    TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE
hello   ClusterIP   172.20.181.121   <none>        80/TCP    4s
$ kubectl run curl --image=busybox:1.37 --restart=Never --rm -i --quiet -- wget -qO- http://hello/api
{"version": "v1", "pod": "hello-55c65f6b5f-28mnj", "greeting": "Hello from Kubernetes", "uptime_seconds": 28}
```

The throwaway busybox Pod called `http://hello`, cluster DNS resolved the Service name, and one of the
two Pods answered with its name. That's your app running on Kubernetes. Lesson 5 makes it reachable
from the internet.

> **Delete what you create.** An EKS cluster bills every hour, even when idle. Destroy it the same day with `terraform destroy`, after deleting any Kubernetes Services or Ingresses that created AWS load balancers, or those load balancers are left behind and keep billing.

## Mission: Run and reach your first app

On kind or EKS, create a Deployment of shop-web with two replicas, expose it as a ClusterIP Service on port 80, call it three times from a busybox Pod, and record which Pod answered each time.

- You need: A running cluster and the shop-web image
- You'll have: ~/first-deployment.txt

```sh
$ kubectl create deployment hello --image=<your-registry>/shop-web:v1 --replicas=2
$ kubectl expose deployment hello --port=80 --target-port=8080
$ for i in 1 2 3; do kubectl run c$i --image=busybox:1.37 --restart=Never --rm -i --quiet -- wget -qO- http://hello/api; done > ~/first-deployment.txt
$ kubectl delete deployment,service hello
```

Each line should name one of your two Pods. If wget hangs, check the Service's target port is 8080 and
that the Pods are Running.

## Try it

- Create a local cluster with `kind create cluster` and run `kubectl get nodes`.
- Run `kubectl get pods -A` and name every system Pod you see.
- Create a Deployment with `kubectl create deployment` and expose it with `kubectl expose`.
- Call the Service from a throwaway busybox Pod with wget.
- Do the mini mission and keep `~/first-deployment.txt`.

## Quiz

1. When does a local kind cluster make more sense than EKS?
   - For production traffic
   - **For learning and testing on your laptop, at no cost, where cloud integrations like load balancers aren't needed** (answer)
   - Never
   Why: kind runs a cluster in Docker containers in a minute. It can't create AWS load balancers or EBS volumes, which is what EKS adds.

2. What does `aws eks update-kubeconfig` do?
   - Creates the cluster
   - **Adds the cluster's address and an authentication command to ~/.kube/config, so kubectl can talk to it** (answer)
   - Upgrades Kubernetes
   Why: kubectl reads ~/.kube/config. On EKS it authenticates with your AWS identity through an exec plugin.

3. Why does the VPC CNI on EKS give Pods addresses like 10.42.29.172?
   - They are random
   - **Pods get real IP addresses from the VPC subnets, so they are reachable inside the VPC like EC2 instances** (answer)
   - Because of Docker
   Why: The VPC CNI assigns secondary IPs from the subnet to Pods. The node's instance type limits how many Pods fit.

## Resources

- [kind quick start](https://kind.sigs.k8s.io/docs/user/quick-start/) (kind)
- [Install and set up kubectl](https://kubernetes.io/docs/tasks/tools/) (Kubernetes)
- [Amazon EKS user guide](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html) (AWS Docs)
- [terraform-aws-modules/eks](https://registry.terraform.io/modules/terraform-aws-modules/eks/aws/latest) (Terraform Registry)
- [Amazon VPC CNI](https://docs.aws.amazon.com/eks/latest/userguide/managing-vpc-cni.html) (AWS Docs)
