DevOps.Academy
CoursesCurriculumInterview prepPricing
◔My learningSign in
DevOps.Academy

Free, hands-on DevOps lessons. Made with care in India.

System status

Learn

All coursesLinux roadmapCurriculumInterview questionsCheat sheetsMy learning

Academy

PricingCertificates

Legal

PrivacyTermsContact

devops.rajeev.pro

Kubernetes & HelmLesson 4 of 16
Your progress · 0%
On this page
  1. Pods
  2. Deployments and ReplicaSets
  3. StatefulSets
  4. Jobs and CronJobs
↖ Course roadmap
Lesson 4 · Running applications

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.

30 min read · intermediate · hands-on

By the end of this lesson you'll be able to

0 of 5 complete
Lab status

Verified lab: every command here ran on the course's EKS 1.37 cluster. The output shown is real.
Code walkthrough: none.
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.

The Pod is the unit with the IP address. The sidecar here is an example; shop-web runs a single container.© Diagram: DevOps Academy

The Pod is the unit with the IP address. The sidecar here is an example; shop-web runs a single container.© Diagram: DevOps Academy

Here's the simplest one:

# 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
$ 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
kubectl apply -f 04-pod.yaml
  • kubectltalk to a Kubernetes cluster
  • applycreate or update from a file
  • -ffrom this file
kubectl get pod web -o wide
  • getlist objects
  • -ooutput format
kubectl delete pod web
  • deletedelete an object

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:

# 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.
$ 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>
kubectl apply -f 04-deployment.yaml
  • kubectltalk to a Kubernetes cluster
  • applycreate or update from a file
  • -ffrom this file
kubectl get deployment shop-web
  • getlist objects
kubectl get replicaset -l app=shop-web
  • -lonly objects with this label
kubectl get pods -l app=shop-web -o wide
  • -ooutput format

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).

Read the names right to left: Pod, ReplicaSet, Deployment.© Diagram: DevOps Academy

Read the names right to left: Pod, ReplicaSet, Deployment.© Diagram: DevOps Academy

Self-healing and scaling

Delete a Pod and watch the ReplicaSet put one back:

The ReplicaSet's loop: watch, compare desired with current, create or delete. The replacement starts while the old Pod is still shutting down.© Animation: DevOps Academy

The ReplicaSet's loop: watch, compare desired with current, create or delete. The replacement starts while the old Pod is still shutting down.© Animation: DevOps Academy
$ 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
kubectl delete pod shop-web-6c674ff8df-bsf2k
  • kubectltalk to a Kubernetes cluster
  • deletedelete an object
kubectl get pods -l app=shop-web
  • getlist objects
  • -lonly objects with this label

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:

$ 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 deployment shop-web --replicas=5
  • kubectltalk to a Kubernetes cluster
  • scalechange the number of replicas
  • --replicas=5how many copies
kubectl get deployment shop-web
  • getlist objects
kubectl scale deployment shop-web --replicas=3
  • --replicas=3how many copies

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.

A StatefulSet Pod keeps its name, its disk and its place in line, even when it's recreated.© Diagram: DevOps Academy

A StatefulSet Pod keeps its name, its disk and its place in line, even when it's recreated.© Diagram: DevOps Academy

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:

# 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())",
            ]
$ 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
kubectl get job report
  • kubectltalk to a Kubernetes cluster
  • getlist objects
kubectl get pods -l job-name=report
  • -lonly objects with this label
kubectl logs -l job-name=report --prefix
  • logsshow a Pod’s output

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:

# 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.

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.© Diagram: DevOps Academy

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.© Diagram: DevOps Academy
⌘
Mini 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.

Input: The YAML files from this lessonOutput: ~/workloads.txt
Reveal one safe solution
$ 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
kubectl apply -f 04-deployment.yaml && kubectl rollout status deployment/shop-web
  • kubectltalk to a Kubernetes cluster
  • applycreate or update from a file
  • -ffrom this file
  • &&run the next command only if this one worked
  • rolloutmanage a rollout
kubectl get pods -l app=shop-web -o name > ~/workloads.txt
  • getlist objects
  • -lonly objects with this label
  • -ooutput format
  • >write output to a file, replacing it
kubectl delete $(head -n 1 ~/workloads.txt) && kubectl get pods -l app=shop-web -o name >> ~/workloads.txt
  • deletedelete an object
  • $(head -n 1 ~/workloads.txt)the output of another command
  • >>append output to a file
kubectl logs -l job-name=report --prefix >> ~/workloads.txt
  • logsshow a Pod’s output

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 yourself

0 of 6 steps done

Run each task in your own account or terminal, then tick it off.

Knowledge check

Quick check

Question 1 of 3

You create a bare Pod and then delete it. What happens?

Go deeper

Official reading for this lesson

  • DocsWorkloads overviewKubernetes ↗
  • DocsDeploymentsKubernetes ↗
  • DocsLiveness, readiness and startup probesKubernetes ↗
  • DocsJobsKubernetes ↗
  • DocsStatefulSetsKubernetes ↗

Or get every quiz answer right and it completes itself.

Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.

← PreviousSetting up: a cluster, kubectl and your first deploymentNext lesson →Services, Ingress and load balancing