# Running applications: Pods, Deployments, Jobs

The workload objects you use every day: Pods, ReplicaSets and Deployments with health probes and resources, StatefulSets in brief, and Jobs and CronJobs for work that finishes.

Course: [Kubernetes & Helm](https://devops.rajeev.pro/courses/kubernetes), lesson 4. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/kubernetes/04-running-applications

## What you will learn

- Explain why you rarely create bare Pods
- Write a Deployment with replicas, probes and resource requests
- Watch a ReplicaSet replace a deleted Pod and scale a Deployment
- Run a Job to completion and schedule work with a CronJob
- Know when a StatefulSet is the right choice

> **Lab status.** **Verified lab:** every command here ran on the course's EKS 1.37 cluster. The output shown is real. <br />**Code walkthrough:** none. <br />**Cloud lab:** none needed; all of it also works on a local kind cluster.

Kubernetes has several workload objects, and choosing the right one decides whether your app heals
itself, scales, and finishes cleanly. This lesson runs each of them on the shop-web app.

## Pods

A **Pod** is the smallest thing Kubernetes runs: one or more containers that share an IP address and
can share volumes.

> **Figure.** A worker node ip-10-42-28-149 holds Pod web with IP 10.42.22.16, one network namespace where localhost is shared. Inside: container web running shop-web:v1, listening on 8080 and writing to /var/log/app, and an optional log-shipper sidecar that reads /var/log/app and can call localhost:8080. Both mount the emptyDir volume logs at /var/log/app; it is created and deleted with the Pod. Right: shared by the containers are one IP and port space, localhost, the Pod's volumes, the same node and lifetime. Not shared: each container's own image and filesystem, its own CPU and memory limits, and its own restarts.
>
> The Pod is the unit with the IP address. The sidecar here is an example; shop-web runs a single container.

Here's the simplest one:

```yaml
# 04-pod.yaml
apiVersion: v1
kind: Pod
metadata:
  name: web
  labels:
    app: web
spec:
  containers:
    - name: web
      image: 626159997645.dkr.ecr.ap-south-1.amazonaws.com/shop-web:v1
      ports:
        - containerPort: 8080
```

```text
$ kubectl apply -f 04-pod.yaml
pod/web created
$ kubectl get pod web -o wide
NAME   READY   STATUS    RESTARTS   AGE   IP            NODE                                          NOMINATED NODE   READINESS GATES
web    1/1     Running   0          9s    10.42.22.16   ip-10-42-28-149.ap-south-1.compute.internal   <none>           <none>
$ kubectl delete pod web
pod "web" deleted from default namespace
$ kubectl get pod web
Error from server (NotFound): pods "web" not found
```

Delete it and it's gone. Nothing owns a bare Pod, so nothing brings it back, and if its node dies, it
dies too. That's why you almost never create Pods directly: you create a controller that creates Pods.

## Deployments and ReplicaSets

A **Deployment** is the controller for stateless apps. Here's the one the rest of the course uses:

```yaml
# 04-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop-web
  labels:
    app: shop-web
spec:
  replicas: 3
  selector:
    matchLabels:
      app: shop-web
  template:
    metadata:
      labels:
        app: shop-web
    spec:
      containers:
        - name: web
          image: 626159997645.dkr.ecr.ap-south-1.amazonaws.com/shop-web:v1
          ports:
            - containerPort: 8080
          readinessProbe:
            httpGet:
              path: /healthz
              port: 8080
            periodSeconds: 5
          livenessProbe:
            httpGet:
              path: /healthz
              port: 8080
            periodSeconds: 10
          resources:
            requests:
              cpu: 100m
              memory: 64Mi
            limits:
              memory: 128Mi
```

Read it in parts:

- **`replicas: 3`**: the desired count.
- **`selector.matchLabels`** must match **`template.metadata.labels`**: that's how the controller knows
  which Pods are its own.
- **`template`**: the Pod to stamp out, exactly like the bare Pod above.
- **`readinessProbe`**: the Pod gets traffic only after `/healthz` answers. During a rollout, new Pods
  must be ready before old ones are removed.
- **`livenessProbe`**: if `/healthz` stops answering, the kubelet restarts the container.
- **`resources.requests`**: what the scheduler reserves on a node (lesson 7). **`limits.memory`**: the
  most it may use before it's killed.

```text
$ kubectl apply -f 04-deployment.yaml
deployment.apps/shop-web created
$ kubectl get deployment shop-web
NAME       READY   UP-TO-DATE   AVAILABLE   AGE
shop-web   3/3     3            3           12s
$ kubectl get replicaset -l app=shop-web
NAME                  DESIRED   CURRENT   READY   AGE
shop-web-6c674ff8df   3         3         3       16s
$ kubectl get pods -l app=shop-web -o wide
NAME                        READY   STATUS    RESTARTS   AGE   IP             NODE                                          NOMINATED NODE   READINESS GATES
shop-web-6c674ff8df-bsf2k   1/1     Running   0          20s   10.42.2.204    ip-10-42-0-115.ap-south-1.compute.internal    <none>           <none>
shop-web-6c674ff8df-xfdh5   1/1     Running   0          20s   10.42.19.142   ip-10-42-28-149.ap-south-1.compute.internal   <none>           <none>
shop-web-6c674ff8df-zsh6h   1/1     Running   0          20s   10.42.26.70    ip-10-42-28-149.ap-south-1.compute.internal   <none>           <none>
```

Look at the names: Pod `shop-web-6c674ff8df-bsf2k` belongs to ReplicaSet `shop-web-6c674ff8df`, which
belongs to Deployment `shop-web`. The ReplicaSet keeps the **count**; the Deployment manages
**versions**, creating a new ReplicaSet for every change to the template (lesson 14 shows a rollout).

> **Figure.** Ownership chain with real names. Deployment shop-web, replicas 3, image shop-web:v1, manages versions, and owns ReplicaSet shop-web-6c674ff8df, whose name is the Deployment name plus a hash of the Pod template and which keeps the count at 3. The ReplicaSet owns three Pods: shop-web-6c674ff8df-bsf2k on node ip-10-42-0-115 at 10.42.2.204, shop-web-6c674ff8df-xfdh5 at 10.42.19.142 and shop-web-6c674ff8df-zsh6h at 10.42.26.70, both on ip-10-42-28-149. A dashed box shows that the next template change creates a new ReplicaSet that scales up while the old one scales to 0.
>
> Read the names right to left: Pod, ReplicaSet, Deployment.

### Self-healing and scaling

Delete a Pod and watch the ReplicaSet put one back:

> **Figure.** Animated, real names from the lab. ReplicaSet shop-web-6c674ff8df has desired 3 and current 3, with Pods bsf2k, xfdh5 and zsh6h Running. Step 1: kubectl delete pod shop-web-6c674ff8df-bsf2k; bsf2k turns red, Terminating for 30 seconds. Step 2: the ReplicaSet counts current 2 and creates a new Pod, d7mwm, first ContainerCreating. Step 3: d7mwm passes its readiness probe and is Running and Ready; current is 3 again, and bsf2k disappears once its graceful shutdown ends.
>
> The ReplicaSet's loop: watch, compare desired with current, create or delete. The replacement starts while the old Pod is still shutting down.

```text
$ kubectl delete pod shop-web-6c674ff8df-bsf2k
pod "shop-web-6c674ff8df-bsf2k" deleted from default namespace
$ kubectl get pods -l app=shop-web
NAME                        READY   STATUS    RESTARTS   AGE
shop-web-6c674ff8df-d7mwm   1/1     Running   0          43s
shop-web-6c674ff8df-xfdh5   1/1     Running   0          72s
shop-web-6c674ff8df-zsh6h   1/1     Running   0          72s
```

`bsf2k` is gone and `d7mwm` took its place. It's already 43 seconds old because `kubectl delete` waits
for the old Pod to shut down gracefully (30 seconds by default), while the replacement started
immediately. Scaling is just a new desired count:

```text
$ kubectl scale deployment shop-web --replicas=5
deployment.apps/shop-web scaled
$ kubectl get deployment shop-web
NAME       READY   UP-TO-DATE   AVAILABLE   AGE
shop-web   5/5     5            5           94s
$ kubectl scale deployment shop-web --replicas=3
deployment.apps/shop-web scaled
```

`kubectl scale` is fine for experiments. In real life, change `replicas` in the YAML and apply it, so Git
stays the truth, or let an autoscaler do it (lesson 10).

## StatefulSets

A Deployment treats its Pods as interchangeable: random names, any order, shared or no storage. A
database can't work like that. A **StatefulSet** gives each Pod:

- a **stable name** with an index: `db-0`, `db-1`,
- its **own disk** that follows it if it's recreated,
- **ordered** startup and shutdown.

> **Figure.** Two panels. Left, Deployment: Pods shop-web-6c674ff8df-d7mwm, -xfdh5 and -zsh6h; a replacement gets a new random name, Pods start in any order, have no disk of their own, right for stateless web apps. Right, StatefulSet db with replicas 2 and serviceName db: db-0 starts first, db-1 only after db-0 is Ready. Each has a stable DNS name, db-0.db and db-1.db, its own PVC, data-db-0 and data-db-1, 1Gi gp3 ReadWriteOnce, and its own EBS volume. Bottom: delete db-0 and it comes back as db-0 on the same disk; cat /data/id prints I am db-0, as in lesson 12.
>
> A StatefulSet Pod keeps its name, its disk and its place in line, even when it's recreated.

Use one for databases, queues and anything clustered. The Storage lesson runs a real StatefulSet with
an EBS volume per Pod. On AWS, managed services such as RDS are often simpler than running databases in
Kubernetes at all.

## Jobs and CronJobs

A Deployment restarts a container that exits. For work that should **finish**, use a **Job**:

```yaml
# 04-job.yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: report
spec:
  completions: 3 # succeed 3 times in total
  parallelism: 2 # at most 2 at once
  backoffLimit: 2 # give up after 2 failures
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: report
          image: 626159997645.dkr.ecr.ap-south-1.amazonaws.com/shop-web:v1
          command:
            [
              "python",
              "-c",
              "import socket,time; time.sleep(3); print('report done on', socket.gethostname())",
            ]
```

```text
$ kubectl get job report
NAME     STATUS     COMPLETIONS   DURATION   AGE
report   Complete   3/3           14s        17s
$ kubectl get pods -l job-name=report
NAME           READY   STATUS      RESTARTS   AGE
report-cgb2c   0/1     Completed   0          21s
report-gjrdv   0/1     Completed   0          14s
report-htm5v   0/1     Completed   0          21s
$ kubectl logs -l job-name=report --prefix
[pod/report-cgb2c/report] report done on report-cgb2c
[pod/report-gjrdv/report] report done on report-gjrdv
[pod/report-htm5v/report] report done on report-htm5v
```

Two Pods started together (`parallelism: 2`, both 21 seconds old) and the third started when one
finished. The Pods stay in `Completed` so you can read their logs.

A **CronJob** creates a Job on a schedule, in normal cron syntax:

```yaml
# 04-cronjob.yaml (excerpt)
spec:
  schedule: "*/1 * * * *" # every minute, for the demo
  successfulJobsHistoryLimit: 2
```

In the next lesson's output you'll see its Pods, `cleanup-29903405-qwsjq` and
`cleanup-29903406-ld6np`, one per minute, with only the last two kept.

> **Figure.** Top: Job report with completions 3, parallelism 2, backoffLimit 2 and restartPolicy Never. On a 0 to 14 second timeline, report-cgb2c and report-htm5v run together from 0 to about 7 seconds, giving 2 of 3 completions; then only report-gjrdv runs, because one completion is left, finishing at 14 seconds: 3 of 3, Complete. Bottom: CronJob cleanup with schedule every minute and successfulJobsHistoryLimit 2. Over four minutes it creates one Job per minute; the two older Jobs are deleted, and the last two, cleanup-29903405 with Pod cleanup-29903405-qwsjq and cleanup-29903406 with Pod cleanup-29903406-ld6np, are kept.
>
> Pod timings are worked out from the lab's Pod ages. The number in a CronJob's Job name is its scheduled time, in minutes since 1970.

## Mission: Run each workload type once

Run a bare Pod and delete it; apply a 3-replica Deployment with probes, delete one Pod and record the replacement; scale to 5 and back; run a Job with 3 completions and save its logs. Write down which objects brought Pods back and which didn't.

- You need: The YAML files from this lesson
- You'll have: ~/workloads.txt

```sh
$ kubectl apply -f 04-deployment.yaml && kubectl rollout status deployment/shop-web
$ kubectl get pods -l app=shop-web -o name > ~/workloads.txt
$ kubectl delete $(head -n 1 ~/workloads.txt) && kubectl get pods -l app=shop-web -o name >> ~/workloads.txt
$ kubectl apply -f 04-job.yaml && kubectl wait --for=condition=Complete job/report --timeout=120s
$ kubectl logs -l job-name=report --prefix >> ~/workloads.txt
```

You should see one Pod name change in the second list, and three "report done" lines. If the Job never
completes, check `kubectl describe job report` for image or command errors.

## Try it

- Create a bare Pod, delete it, and confirm nothing brings it back.
- Apply the shop-web Deployment and list its ReplicaSet and Pods.
- Delete one Pod and run `kubectl get pods` straight after.
- Scale to 5 replicas and back to 3.
- Run the report Job and read its logs with `--prefix`.
- Do the mini mission and keep `~/workloads.txt`.

## Quiz

1. You create a bare Pod and then delete it. What happens?
   - A new one starts automatically
   - **It's gone for good; nothing owns it, so nothing recreates it** (answer)
   - It restarts on another node
   Why: Bare Pods have no controller. Deployments (through ReplicaSets), StatefulSets and Jobs are what keep Pods running.

2. What is the difference between a readiness probe and a liveness probe?
   - They are the same
   - **Readiness decides whether the Pod receives traffic; liveness decides whether the container should be restarted** (answer)
   - Liveness runs only once at start
   Why: A Pod that's alive but still warming up should get no traffic (readiness), while a stuck process should be restarted (liveness).

3. Which object runs a task to completion, such as a nightly report?
   - Deployment
   - **Job, or a CronJob for a schedule** (answer)
   - Service
   Why: A Deployment restarts Pods that exit. A Job counts successful completions and stops; a CronJob creates a Job on a schedule.

## Resources

- [Workloads overview](https://kubernetes.io/docs/concepts/workloads/) (Kubernetes)
- [Deployments](https://kubernetes.io/docs/concepts/workloads/controllers/deployment/) (Kubernetes)
- [Liveness, readiness and startup probes](https://kubernetes.io/docs/concepts/configuration/liveness-readiness-startup-probes/) (Kubernetes)
- [Jobs](https://kubernetes.io/docs/concepts/workloads/controllers/job/) (Kubernetes)
- [StatefulSets](https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/) (Kubernetes)
