Table of Contents

K9s: Kubernetes CLI

https://k9scli.io

Kubernetes CLI To Manage Your Clusters In Style!

img-20260326.png

Download
https://github.com/derailed/k9s/releases

Install on RHEL

sudo rpm -i k9s_linux_amd64.rpm

CronJob

https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/

One CronJob object is like one line of a crontab (cron table) file. It runs a job periodically on a given schedule, written in Cron format.

More about cron on guru: https://crontab.guru/

disk-free-cron.yaml

apiVersion: batch/v1
kind: CronJob
metadata:
  name: diskfree
spec:
  schedule: "*/2 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: diskfree
            image: busybox
            imagePullPolicy: IfNotPresent
            command: ["/bin/sh", "-c", "df", "-h"]
          restartPolicy: OnFailure
kubectl apply -f disk-free-cron.yaml

DamonSet

https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/

A DaemonSet ensures that all (or some) Nodes run a copy of a Pod. As nodes are added to the cluster, Pods are added to them. As nodes are removed from the cluster, those Pods are garbage collected. Deleting a DaemonSet will clean up the Pods it created.

Some typical uses of a DaemonSet are:

  • running a cluster storage daemon on every node
  • running a logs collection daemon on every node
  • running a node monitoring daemon on every node

fluentd-daemonset.yaml

apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: fluentd
  namespace: logging
  labels:
    app: fluentd
spec:
  selector:
    matchLabels:
      app: fluentd
  template:
    metadata:
      labels:
        app: fluentd
    spec:
      tolerations:
        # Allow scheduling on control-plane nodes 
        # (useful for single-node Minikube)
        - key: node-role.kubernetes.io/control-plane
          effect: NoSchedule
      containers:
        - name: fluentd
          image: fluent/fluentd:v1.16-debian
          env:
            - name: FLUENT_UID
              value: "0"
            - name: FLUENTD_SYSTEMD_CONF
              value: "disable"
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: 500m
              memory: 256Mi
          volumeMounts:
            - name: varlog
              mountPath: /var/log
            - name: varlibdockercontainers
              mountPath: /var/lib/docker/containers
              readOnly: true
      volumes:
        - name: varlog
          hostPath:
            path: /var/log
        - name: varlibdockercontainers
          hostPath:
            path: /var/lib/docker/containers
kubectl create namespace logging
kubectl apply -f fluentd-daemonset.yaml

Confirm running daemonset

kubectl get all -n logging
NAME                READY   STATUS    RESTARTS   AGE
pod/fluentd-6946b   1/1     Running   0          14s
pod/fluentd-kp2h5   1/1     Running   0          14s
pod/fluentd-z4gnr   1/1     Running   0          14s
 
NAME                     DESIRED   CURRENT   READY   UP-TO-DATE   AVAILABLE   NODE SELECTOR   AGE
daemonset.apps/fluentd   3         3         3       3            3           <none>          14s
 

StatefulSet

https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/

A StatefulSet provides stable, unique network identifiers and stable persistent storage for applications that require ordered deployment, scaling, and deletion (like databases). Unlike Deployments, StatefulSets maintain a sticky identity for each Pod.

Redis StatefulSet Example

redis-statefulset.yaml

---
apiVersion: v1
kind: Namespace
metadata:
  name: redis-ns
  labels:
    app: redis
 
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: redis-sts
  namespace: redis-ns
spec:
  serviceName: "redis-service"
  replicas: 3
  selector:
    matchLabels:
      app: redis
  template:
    metadata:
      labels:
        app: redis
    spec:
      containers:
      - name: redis
        image: redis:alpine
        ports:
        - containerPort: 6379
          name: redis
        resources:
          requests:
            cpu: 100m
            memory: 256Mi
          limits:
            cpu: 200m
            memory: 512M
 
---
apiVersion: v1
kind: Service
metadata:
  name: redis-service
  namespace: redis-ns
spec:
  clusterIP: None  # Headless service
  ports:
  - port: 6379
    name: redis
  selector:
    app: redis
 

Key Components Explained

  1. Stable Network Identity

    • Pods are named sequentially: redis-sts-0, redis-sts-1, etc.
    • DNS follows pattern: {pod-name}.{service-name}.{namespace}.svc.cluster.local
    • Example: redis-sts-0.redis-service.redis-ns.svc.cluster.local
  2. Persistent Storage

    • Each Pod gets its own PersistentVolumeClaim
    • Data persists across Pod restarts
    • Volume naming: {pvc-name}-{pod-name}
  3. Ordered Operations

    • Pods are created in order (0, 1, 2…)
    • Scaling up happens sequentially
    • Scaling down happens in reverse order
  4. Headless Service

    • Enables DNS resolution for individual Pods
    • No ClusterIP allocated (clusterIP: None)
  5. Redis Configuration

    • Persistent data stored in /data
    • Password protection via Secret
    • Resource limits set

Deployment Process

  1. Create namespace:
kubectl apply -f redis-statefulset.yaml -n redis-ns
  1. Verify StatefulSet:
kubectl get statefulset -n redis-ns
  1. Check Pods:
kubectl get pods -n redis-ns -w

Accessing Redis Pods

# Access specific Pod
kubectl exec -it redis-sts-0 -n redis-ns -- redis-cli
 
# Access via DNS from another Pod
kubectl run redis-client -n redis-ns --rm -it --image=redis:alpine \
  -- redis-cli -h redis-sts-0.redis-service.redis-ns.svc.cluster.local

Scaling Operations

# Scale up
kubectl scale statefulset redis-sts --replicas=5 -n redis-ns
 
# Scale down
kubectl scale statefulset redis-sts --replicas=2 -n redis-ns

Deletion Process

kubectl delete -f redis-statefulset.yaml -n redis-ns

Maintenance

Kubernetes Node Management: cordon, taint, and drain

kubectl cordon

Marks a node as unschedulable — no new pods will be placed on it, but existing pods keep running.

kubectl cordon <node-name>

  • Sets node.spec.unschedulable = true
  • Existing workloads are not affected
  • Use when you want to prepare a node for maintenance without disrupting running pods
  • Undo with: kubectl uncordon <node-name>

kubectl drain

Safely evicts all pods from a node and cordons it, preparing it for maintenance or decommissioning.

kubectl drain <node-name> --ignore-daemonsets --delete-emptydir-data

  • Implicitly cordons the node first
  • Evicts pods gracefully (respects PodDisruptionBudgets)

Common flags

FlagPurpose
--ignore-daemonsetsSkip DaemonSet pods (they’ll respawn anyway)
--delete-emptydir-dataAllow eviction of pods using emptyDir volumes
--forceEvict pods not managed by a controller (they won’t be rescheduled)
--grace-period=<s>Override the pod’s termination grace period

Typical maintenance workflow

# Start new deployment  
kubectl create deploy nginx --image nginx
 
# Establish a cordon node3  
kubectl cordon minikube-m03  
 
# See node status  
$ kubectl get nodes
 
NAME           STATUS                     ROLES           AGE   VERSION
minikube       Ready                      control-plane   29h   v1.35.1
minikube-m02   Ready                      <none>          29h   v1.35.1
minikube-m03   Ready,SchedulingDisabled   <none>          29h   v1.35.1
 
# Remove all from node3  
kubectl drain minikube-m03 --ignore-daemonsets --delete-emptydir-data
 
# Now node can be deleted from cluster    
minikube node delete minikube-m03
 
# Add another node  to cluster  
minikube node add
 
# Redistribute pods  
kubectl rollout restart deployment nginx

kubectl taint

Applies a key=value:effect label to a node that repels pods unless they explicitly tolerate it.

kubectl taint nodes <node-name> key=value:effect

Three effects

EffectBehavior
NoScheduleNew pods without a toleration won’t be scheduled here
PreferNoScheduleScheduler tries to avoid this node, but not guaranteed
NoExecuteNew pods are rejected and existing pods without toleration are evicted

Example use cases:

  • Dedicate a node to specific workloads (e.g., GPU nodes, spot instances)
  • Mark a node as degraded or special-purpose

Add taint

`kubectl taint nodes key=value:effect

Remove a taint

kubectl taint nodes <node> key=value:effect- (trailing dash)

taint example

kubectl taint nodes minikube-m03 class=premium:NoExecute
$ kubectl describe node minikube-m03 | grep -A 1 Taint

Taints:             class=premium:NoExecute
Unschedulable:      false

INFO

Expected behavior: The pod will be scheduled on a different node (if available). If minikube-m03 is the only node, the pod remains in Pending state

hello-deploy.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: hello
  name: hello
spec:
  replicas: 3
  selector:
    matchLabels:
      app: hello
  strategy: {}
  template:
    metadata:
      labels:
        app: hello
    spec:
      tolerations:                # add toleration
      - key: "class"
        value: "premium"
        effect: "NoExecute"
      containers:
      - image: docker.io/nginxdemos/hello:plain-text
        name: hello
        resources: {}
status: {}
 
kubectl apply -f hello-deploy.yaml
 
# apply taint
kubectl taint nodes minikube-m03 class=premium:NoExecute
 

INFO

Expected behavior: The pod executes successfully on minikube-m03 despite the taint

Cleanup

Remove the taint and delete test pods:

kubectl taint nodes minikube-m03 class=premium:NoExecute-
kubectl delete all -l app=hello

INFO

Experiment with NoSchedule and PreferNoSchedule to see the difference

How they relate

  • cordon → node is unschedulable (pods stay)
  • drain → cordon + evict all pods (node is empty)
  • taint → flexible repulsion rules (with toleration support)

Persistent Volumes

https://kubernetes.io/docs/concepts/storage/volumes/

Persistent Volumes (PVs) in Kubernetes provide a way to manage storage that outlives individual Pods. They represent a piece of storage in the cluster—like a virtual disk—that has been provisioned by an administrator or dynamically created via a StorageClass. The key abstraction is the separation of concerns: PersistentVolume is the actual storage resource in the cluster, while PersistentVolumeClaim (PVC) is a request for storage by a user or application. A PVC binds to a suitable PV based on size, access mode, and storage class, allowing developers to request storage without needing to know the underlying infrastructure details.

Types of volumes

Local Storage

  • local (recommended) - Directly attached storage (SSD/HDD) on a specific node. Uses nodeAffinity to bind to a node. High performance but not portable.
  • hostPath (single-node testing only) - Uses a path on the node’s filesystem. Not for production with multi-node clusters.
$ kubectl get sc
 
NAME                 PROVISIONER                RECLAIMPOLICY   VOLUMEBINDINGMODE   ALLOWVOLUMEEXPANSION   AGE
standard (default)   k8s.io/minikube-hostpath   Delete          Immediate           false                  8m11s

Network File Systems

  • nfs - Network File System. Supports ReadWriteMany (multiple pods can read/write simultaneously).
  • cifs - Common Internet File System (SMB/Windows shares).

Cloud Provider Block Storage (typically ReadWriteOnce)

  • awsElasticBlockStore (EBS) - AWS block storage
  • gcePersistentDisk - Google Compute Engine persistent disks
  • azureDisk - Azure managed disks
  • azureFile - Azure Files (SMB, supports ReadWriteMany)
  • cinder - OpenStack Block Storage
  • vsphereVolume - VMware vSphere volumes

Distributed/Container Storage Interfaces (CSI)

Modern, extensible framework replacing in-tree plugins:

  • csi - Generic CSI driver (most third-party storage systems use this)

    • Examples: csi-driver-host-path (for testing), vendor-specific drivers (Portworx, Longhorn, Rancher Longhorn, etc.)
  • rbd (Ceph RBD) - Ceph block storage (RADOS Block Device)

  • cephFS - Ceph distributed file system (supports ReadWriteMany)

  • flexVolume (legacy) - Older plugin system, being phased out in favor of CSI

    Other/Specialized

  • iscsi - iSCSI targets (SCSI over IP)

  • fc (Fibre Channel) - Fibre Channel storage area networks

  • photonPersistentDisk - Photon OS persistent disks

  • portworxVolume (legacy) - Portworx (now uses CSI)

  • scaleIO (legacy) - Dell EMC ScaleIO (now uses CSI)

  • storageos (legacy) - StorageOS (now uses CSI)

local-storage example

Info

Typical created by platform team

admin-volume.yaml

---
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: local-storage
provisioner: kubernetes.io/no-provisioner
volumeBindingMode: WaitForFirstConsumer
reclaimPolicy: Retain
 
---
apiVersion: v1
kind: PersistentVolume
metadata:
  name: local-pv-ssd1
spec:
  capacity:
    storage: 1Gi
  volumeMode: Filesystem
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  storageClassName: local-storage
  local:
    path: /mnt/disks/ssd1
  nodeAffinity:
    required:
      nodeSelectorTerms:
        - matchExpressions:
            - key: kubernetes.io/hostname
              operator: In
              values:
                - minikube

Info

Typical created by application team

usage-volume.yaml

---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: nginx-pvc
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: local-storage
  resources:
    requests:
      storage: 1Gi
 
---
apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod
spec:
  volumes:
    - name: html-volume
      persistentVolumeClaim:
        claimName: nginx-pvc
  containers:
    - name: nginx
      image: nginx
      volumeMounts:
        - mountPath: /usr/share/nginx/html
          name: html-volume
      resources: 
        limits:
          cpu: "100m"
          memory: "64Mi"
        requests:
          cpu: "100m"
          memory: "64Mi" 
  
 

Start application and monitor persistence

kubectl apply -f admin-volume.yaml
kubectl apply -f usage-volume.yaml
 
$ kubectl get sc
 
NAME                 PROVISIONER                    RECLAIMPOLICY   VOLUMEBINDINGMODE      ALLOWVOLUMEEXPANSION   AGE
local-storage        kubernetes.io/no-provisioner   Retain          WaitForFirstConsumer   false                  11s
standard (default)   k8s.io/minikube-hostpath       Delete          Immediate              false                  39m
 
$ kubectl get pv
NAME            CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM               STORAGECLASS    VOLUMEATTRIBUTESCLASS   REASON   AGE
local-pv-ssd1   1Gi        RWO            Retain           Bound    default/nginx-pvc   local-storage   <unset>                          15s
 
 
$ kubectl get pvc
NAME        STATUS   VOLUME          CAPACITY   ACCESS MODES   STORAGECLASS    VOLUMEATTRIBUTESCLASS   AGE
nginx-pvc   Bound    local-pv-ssd1   1Gi        RWO            local-storage   <unset>                 33s
 
$ kubectl get po -o wide
NAME        READY   STATUS    RESTARTS   AGE     IP           NODE       NOMINATED NODE   READINESS GATES
nginx-pod   1/1     ContainerCreating   0          7m13s   10.244.0.3   minikube   <none>           <none>
 
 
$ kubectl get events
(...)
3m30s                   Normal    Pulling                   Pod/nginx-pod                     Pulling image "nginx"
3m29s                   Normal    Started                   Pod/nginx-pod                     Container started
3m29s                   Normal    Created                   Pod/nginx-pod                     Container created
3m29s                   Normal    Pulled                    Pod/nginx-pod                     Successfully pulled image "nginx" in 956ms (956ms including waiting). Image size: 161294340 bytes.
2m3s                    Normal    Killing                   Pod/nginx-pod                     Stopping container nginx
119s                    Normal    WaitForFirstConsumer      PersistentVolumeClaim/nginx-pvc   waiting for first consumer to be created before binding
117s                    Normal    Scheduled                 Pod/nginx-pod                     Successfully assigned default/nginx-pod to minikube
54s (x8 over 117s)      Warning   FailedMount               Pod/nginx-pod                     MountVolume.NewMounter initialization failed for volume "local-pv-ssd1" : path "/mnt/disks/ssd1" does not exist
 
 
minikube ssh
  $ sudo mkdir -p /mnt/disks/ssd1
  $ sudo chmod 777 /mnt/disks/ssd1
  $ echo "Hello, World" > /mnt/disks/ssd1/index.html
  $ curl 10.244.0.3
  $ exit
  
kubectl get events
kubectl delete -f 
kubectl delete -f persistence-admin.yaml persistence-usage.yaml

host-path

Dynamically creating Persistent

Activate extension on minikube

minikube addons enable storage-provisioner

No need for storageClass or persistentVolume

nginx-deploy-volume.yaml

---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: nginx-pvc
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: standard  # <--- change here
  resources:
    requests:
      storage: 1Gi
 
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      initContainers:
      - name: init-html
        image: busybox
        command: 
        - sh 
        - -c
        - |
          echo "Hello from Storage" > /data/index.html
        volumeMounts:
        - name: web-data
          mountPath: /data
 
      containers:
      - name: nginx
        image: nginx:latest
        ports:
        - containerPort: 80
        volumeMounts:
        - name: web-data
          mountPath: /usr/share/nginx/html
        resources:
          limits:
            cpu: "100m"
            memory: "64Mi"
          requests:
            cpu: "100m"
            memory: "64Mi" 
 
      volumes:
      - name: web-data
        persistentVolumeClaim:
          claimName: nginx-pvc
 
kubectl appy -f nginx-deploy-volume.yaml
kubectl describe pvc
minikube ssh
# cd /tmp/hostpath-provisioner/default/nginx-pvc

NFS storage example

Install nfs-utils

sudo dnf install nfs-utils
# example: 
sudo vi /etc/exports
 
"/mnt 172.31.0.0/16(rw,sync,no_wdelay,no_root_squash,insecure)"
# sudo chmod 777 /mnt
 
showmount -e localhost

Create the PV

nginx-nfs-pv.yaml

---
apiVersion: v1
kind: PersistentVolume
metadata:
  name: nginx-nfs-pv
  labels:
    app: nginx
spec:
  capacity:
    storage: 1Gi
  accessModes:
    - ReadWriteMany
  persistentVolumeReclaimPolicy: Retain
  storageClassName: nfs
  nfs:
    server: 172.31.100.100  # Server IP Addr
    path: /mnt
    readOnly: false
    

Create a Sample Pod Using the PVC

nginx-nfs-pod.yaml

---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: nginx-nfs-pvc
  labels:
    app: nginx
spec:
  accessModes:
    - ReadWriteMany
  storageClassName: nfs
  resources:
    requests:
      storage: 1Gi
  volumeName: nginx-nfs-pv
  
---
apiVersion: v1
kind: Pod
metadata:
  name: nfs-pod-example
  labels:
    app: nginx
spec:
  containers:
    - name: app
      image: nginx
      volumeMounts:
        - name: nfs-data
          mountPath: /usr/share/nginx/html
      resources: 
        limits:
          cpu: "100m"
          memory: "64Mi"
        requests:
          cpu: "100m"
          memory: "64Mi"   
  volumes:
    - name: nfs-data
      persistentVolumeClaim:
        claimName: nginx-nfs-pvc
  

Apply it:

kubectl apply -f nginx-nfs-pv.yaml
kubectl apply -f nginx-nfs-pod.yaml

Verify:

kubectl get pv nginx-nfs-pv
kubectl get pvc nginx-nfs-pvc

Configmap

https://kubernetes.io/docs/concepts/configuration/configmap/

A ConfigMap provides a way to inject configuration data into pods. The data stored in a ConfigMap can be referenced in a volume of type configMap and then consumed by containerized applications running in a pod.

configmap.yaml

---
apiVersion: v1
kind: ConfigMap
metadata:
  name: game-demo
data:
  # property-like keys; each key maps to a simple value
  player_initial_lives: "3"
  ui_properties_file_name: "user-interface.properties"
 
  # file-like keys
  game.properties: |
    enemy.types=aliens,monsters
    player.maximum-lives=5    
  user-interface.properties: |
    color.good=purple
    color.bad=yellow
    allow.textmode=true   
 
kubectl apply -f configmap.yaml

Example using a configmap usage

configmap-pod.yaml

---
apiVersion: v1
kind: Pod
metadata:
  name: configmap-demo-pod
spec:
  containers:
    - name: demo
      image: alpine
      resources: 
        limits:
          cpu: "100m"
          memory: "64Mi"
        requests:
          cpu: "100m"
          memory: "64Mi"   
      command: ["sleep", "3600"]
      env:
        - name: PLAYER_INITIAL_LIVES 
          valueFrom:
            configMapKeyRef:
              name: game-demo          
              key: player_initial_lives 
        - name: UI_PROPERTIES_FILE_NAME
          valueFrom:
            configMapKeyRef:
              name: game-demo
              key: ui_properties_file_name
      volumeMounts:
      - name: config
        mountPath: "/config"
        readOnly: true
  volumes:
    - name: config
      configMap:
        name: game-demo
        items:
        - key: "game.properties"
          path: "game.properties"
        - key: "user-interface.properties"
          path: "user-interface.properties"
kubectl apply -f configmap.yaml
kubectl apply -f configmap-pod.yaml

Secrets

https://kubernetes.io/docs/concepts/configuration/secret/

A Secret is an object that contains a small amount of sensitive data such as a password, a token, or a key.

Encode a password

echo -n "your-password" | base64
echo -n "password=123456" > secret.txt
kubectl create secret generic my-secret --from-file=secret.txt
$ kubectl describe secret my-secret

Name:         my-secret
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  Opaque

Data
====
secret.txt:  15 bytes
$ kubectl get secret my-secret -o yaml
 
apiVersion: v1
data:
  secret.txt: cGFzc3dvcmQ9MTIzNDU2
kind: Secret
metadata:
  creationTimestamp: "2026-03-26T08:25:22Z"
  name: my-secret
  namespace: default
  resourceVersion: "11697"
  uid: c19493ae-c1ed-4ef1-b2ce-c7f98ab6aff3
type: Opaque
 
echo 'cGFzc3dvcmQ9MTIzNDU2' | base64 --decode
 
password=123456

Creating a pod that uses secret as a file

pod-secret.yaml

apiVersion: v1
kind: Pod
metadata:
  name: test-secret
spec:
  containers:
  - name: alpine
    image: alpine
    command:
      - sleep
      - "3600"
    volumeMounts:
    - mountPath: /tmp/data
      name: my-volume-secret
  volumes:
  - name: my-volume-secret
    secret:
      secretName: my-secret
kubectl apply -f pod-secret.yaml
 
# Let us list /tmp/data  
kubectl exec -it test-secret -- ls /tmp/data
 
# And display contents
kubectl exec -it test-secret -- cat /tmp/data/secret.txt

Creating secret from cmd line

kubectl create secret generic my-literal-secret \
  --from-literal user=cfreire \
  --from-literal password=123456

pod-secret-env.yaml

apiVersion: v1
kind: Pod
metadata:
  name: teste-secret-env
  namespace: default
spec:
  containers:
  - name: alpine
    image: alpine
    command:
      - sleep
      - "3600"
    env:
    - name: USERNAME
      valueFrom:
        secretKeyRef:
          name: my-literal-secret
          key: user
    - name: PASSWORD
      valueFrom:
        secretKeyRef:
          name: my-literal-secret
          key: password
kubectl apply -f pod-secret-env.yaml
 
# And print en environment  
kubectl exec teste-secret-env -it -- printenv

Create secret from yaml resource

---
apiVersion: v1
kind: Secret
metadata:
  name: redis-secret
  labels:
    app: redis
type: Opaque
data:
  redis_pass: "MTIzNDU2"  # base64 encoded "123456"

Ingress

https://kubernetes.io/docs/concepts/services-networking/ingress/

Ingress exposes HTTP and HTTPS routes from outside the cluster to services within the cluster. Traffic routing is controlled by rules defined on the Ingress resource.

  • Node: A worker machine in Kubernetes, part of a cluster.
  • Cluster: A set of Nodes that run containerized applications managed by Kubernetes. For this example, and in most common Kubernetes deployments, nodes in the cluster are not part of the public internet.

Edge router: A router that enforces the firewall policy for your cluster. This could be a gateway managed by a cloud provider or a physical piece of hardware.

  • Cluster network: A set of links, logical or physical, that facilitate communication within a cluster according to the Kubernetes networking model.
  • Service: A Kubernetes Service that identifies a set of Pods using label selectors. Unless mentioned otherwise, Services are assumed to have virtual IPs only routable within the cluster network.

Activate ingress addon

minikube addons enable ingress
mkdir ingress
cd ingress

apple.yaml

---
kind: Pod
apiVersion: v1
metadata:
  name: apple-app
  labels:
    app: apple
spec:
  containers:
    - name: apple-app
      image: hashicorp/http-echo
      args:
        - "-text=apple"
 
---
kind: Service
apiVersion: v1
metadata:
  name: apple-service
spec:
  selector:
    app: apple
  ports:
    - port: 5678
 

android.yaml

---
kind: Pod
apiVersion: v1
metadata:
  name: android-app
  labels:
    app: android
spec:
  containers:
    - name: android-app
      image: hashicorp/http-echo
      args:
        - "-text=android"
 
---
kind: Service
apiVersion: v1
metadata:
  name: android-service
spec:
  selector:
    app: android
  ports:
    - port: 5678
 

ingress.yaml

---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: example-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$1
spec:
  rules:
    - host: test.info
      http:
        paths:
          - path: /apple
            pathType: Prefix
            backend:
              service:
                name: apple-service
                port: 
                  number: 5678
          - path: /android
            pathType: Prefix
            backend:
              service:
                name: android-service
                port: 
                  number: 5678
 
# Verify incress running
$ kubectl get pods -n ingress-nginx
 
💡  ingress is an addon maintained by Kubernetes. For any concerns contact minikube on GitHub.
You can view the list of minikube maintainers at: https://github.com/kubernetes/minikube/blob/master/OWNERS
    ▪ Using image registry.k8s.io/ingress-nginx/controller:v1.14.3
    ▪ Using image registry.k8s.io/ingress-nginx/kube-webhook-certgen:v1.6.7
    ▪ Using image registry.k8s.io/ingress-nginx/kube-webhook-certgen:v1.6.7
🔎  Verifying ingress addon...
🌟  The 'ingress' addon is enabled
$ kubectl apply -f ingress/

pod/apple-app created
service/apple-service created
pod/android-app created
service/android-service created

$ minikube ip
192.168.49.2

$ kubectl get ingress
NAME              CLASS   HOSTS              ADDRESS     PORTS   AGE
example-ingress   nginx   test.info   localhost   80      4m27s

$ sudo vi /etc/hosts
192.168.49.2 test.info

$ curl -kL http://test.info/apple
apple

$ curl -kL http://test.info/android
android

$ curl -kL http://localhost/notfound
default backend - 404

Accessing from external DNS

# Get minikube IP
MINIKUBE_IP=$(minikube ip)
echo $MINIKUBE_IP   # e.g. 192.168.49.2
 
# Get your public-facing interface
PUBLIC_IF=$(ip route get 1.1.1.1 | awk '{print $5; exit}')
echo $PUBLIC_IF     # e.g. eth0, ens3, enp3s0
 
# Get endpoints 80, 443
minikube service -n ingress-nginx ingress-nginx-controller
 
# Forward port 80 → minikube NodePort
sudo nft add rule ip nat PREROUTING \
  iif "$PUBLIC_IF" tcp dport 80 \
  dnat to $MINIKUBE_IP:<port_80>
 
# Forward port 443 → minikube NodePort
sudo nft add rule ip nat PREROUTING \
  iif "$PUBLIC_IF" tcp dport 443 \
  dnat to $MINIKUBE_IP:<port_443>
  
# Masquerade outgoing
sudo nft add rule ip nat POSTROUTING \
  ip daddr $MINIKUBE_IP masquerade
 
# Allow forward 
sudo sysctl -w net.ipv4.ip_forward=1
 
# Make it permanent
echo "net.ipv4.ip_forward = 1" | sudo tee /etc/sysctl.d/99-ip-forward.conf
sudo sysctl -p /etc/sysctl.d/99-ip-forward.conf
 
# persist rules
sudo nft list ruleset | sudo tee /etc/nftables.conf
 
# enable service
sudo systemctl enable --now nftables
 
# Check rules are loaded
sudo nft list table ip nat
 
# Test locally first
curl -H http://<public_ip>/apple

Extract information from yaml/json files

Using yaml query tool and json query tool

# Start a nginx deployment with 3 replicas
kubectl create deploy nginx --image=nginx --replicas=3
 
# Extract number of replicas via yaml
kubectl get deploy/nginx -o yaml | yq .spec.replicas
 
# Extract number of replicas via json
kubectl get deploy/nginx -o json | jq .spec.replicas
 
# Show all labels
kubectl get all --show-labels
kubectl get all -o yaml | yq .items[].metadata.labels
 
# extract image using jsonpath
kubectl get deployments.apps/nginx \
  -o jsonpath='{.spec.template.spec.containers[].image}'

Showing events

# By default, events are not sorted by any specific field
kubectl get events
 
# sort by timestamp
kubectl get events --sort-by='.lastTimestamp'
 
# manage columns and sort
kubectl get events --sort-by='.lastTimestamp' -o custom-columns='TIME:.lastTimestamp,KIND:.involvedObject.kind,REASON:.reason,MESSAGE:.message'
 

Resource types

https://kubernetes.io/docs/reference/kubectl/#resource-types

kubectl api-resources
 

Troubleshooting k8s

  • Events kubectl get events
  • Inspect object logs kubectl logs <resource>/<name>
  • Describe object kubectl describe <resource>/<name>
  • Inspect yaml of object kubectl get <resource>/<name> -o yaml
  • Inspect k8s nodes kubectl get nodes
  • Inspect cluster kubectl cluster-info

Exercise: Webcounter improved

Git REPO: https://gitlab.com/form-cfreire/webcounter.git

Improve the exercise webcounter with the following:

  • Create and add a webcounter-project namespace for all objects
  • Add resources limits to webcounter deployment to limit the pod usage of CPU and memory to 200m cores and 128Mi. Requests are equal to limits.
  • Change redis de Deployment of to a StatefulSet and create 2 replicas.
  • Create a ConfigMap that stores redis service: redis-0.redis-service.webcounter-project.svc.cluster.local
  • Create a Secret to store a password on base64 encryption
  • Change Environment variable REDIS_URL to get values from ConfigMap
  • Add Enviroment variable REDIS_PASS that come from a secret on redis deployment and webcounter deployment

webcounter-deploy-original.yaml

---
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: webcounter
  name: webcounter
spec:
  replicas: 3
  selector:
    matchLabels:
      app: webcounter
  strategy: {}
  template:
    metadata:
      labels:
        app: webcounter
    spec:
      containers:
      - image: cfreire70/webcounter
        env:
        - name: REDIS_URL
          value: redis-service
        name: webcounter
        resources: {}
 
---
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: redis
  name: redis
spec:
  replicas: 1
  selector:
    matchLabels:
      app: redis
  strategy: {}
  template:
    metadata:
      labels:
        app: redis
    spec:
      containers:
      - image: redis:alpine
        name: redis
        resources: {}
 
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: webcounter  
  name: webcounter
  namespace: default
spec:
  ports:
  - port: 5000
    protocol: TCP
    targetPort: 5000
  selector:
    app: webcounter  
  type: NodePort 
  
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: redis
  name: redis-service
  namespace: default
spec:
  ports:
  - port: 6379
    protocol: TCP
    targetPort: 6379
  selector:
    app: redis
  type: ClusterIP
 

Exercise solution

webcounter-improved.yaml

---
apiVersion: v1
kind: Namespace
metadata:
  name: webcounter-project
  labels:
    project: webcounter
 
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: webcounter-config
  namespace: webcounter-project
  labels:
    app: webcounter
data:
  redis_url: "redis-0.redis-service.webcounter-project.svc.cluster.local"
 
---
apiVersion: v1
kind: Secret
metadata:
  name: redis-secret
  namespace: webcounter-project
  labels:
    app: redis
type: Opaque
data:
  redis_pass: "MTIzNDU2"  # base64 encoded "123456"
 
---
apiVersion: v1
kind: Service
metadata:
  name: redis-service
  namespace: webcounter-project
  labels:
    app: redis
spec:
  clusterIP: None  # Headless service for StatefulSet DNS
  ports:
  - port: 6379
    targetPort: 6379
    name: redis
  selector:
    app: redis
 
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: redis
  namespace: webcounter-project
  labels:
    app: redis
spec:
  serviceName: "redis-service"
  replicas: 2
  selector:
    matchLabels:
      app: redis
  template:
    metadata:
      labels:
        app: redis
    spec:
      containers:
      - name: redis
        image: redis:alpine
        ports:
        - containerPort: 6379
          name: redis
        command: ["redis-server"]
        args: ["--appendonly", "yes", "--requirepass", "$(REDIS_PASS)"]
        env:
        - name: REDIS_PASS
          valueFrom:
            secretKeyRef:
              name: redis-secret
              key: redis_pass
        resources:
          requests:
            cpu: "100m"
            memory: "128Mi"
          limits:
            cpu: "200m"
            memory: "256Mi"
 
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: webcounter
  namespace: webcounter-project
  labels:
    app: webcounter
spec:
  replicas: 3
  selector:
    matchLabels:
      app: webcounter
  template:
    metadata:
      labels:
        app: webcounter
    spec:
      containers:
      - name: webcounter
        image: cfreire70/webcounter
        ports:
        - containerPort: 5000
        env:
        - name: REDIS_URL
          valueFrom:
            configMapKeyRef:
              name: webcounter-config
              key: redis_url
        - name: REDIS_PASS
          valueFrom:
            secretKeyRef:
              name: redis-secret
              key: redis_pass
        resources:
          requests:
            cpu: "200m"
            memory: "128Mi"
          limits:
            cpu: "200m"
            memory: "128Mi"
 
---
apiVersion: v1
kind: Service
metadata:
  name: webcounter-service
  namespace: webcounter-project
  labels:
    app: webcounter
spec:
  type: NodePort
  ports:
  - port: 5000
    targetPort: 5000
    nodePort: 30080
  selector:
    app: webcounter
 

Deployment

# Apply all resources
kubectl apply -f webcounter-improved.yaml
 
# Verify namespace and resources
kubectl get all -n webcounter-project
kubectl get pvc -n webcounter-project  # Should show 2 PVCs for redis
kubectl get pods -n webcounter-project -o wide
 
 
# Access via minikube
minikube service webcounter-service -n webcounter-project --url
curl http://192.168.49.2:30000
curl http://192.168.49.2:30000/hits

Verification Steps

# Check StatefulSet pods are running with stable names
kubectl get pods -n webcounter-project -l app=redis
# Expected: redis-0, redis-1
 
# Check redis connectivity from webcounter pod
kubectl exec -it redis-1 -n redis-0 -- sh
  # redis-cli -h redis-0.redis-service.webcounter-project.svc.cluster.local -a <password>
# ping
# keys *
# get hits

Cleanup

kubectl delete namespace webcounter-project
# PVCs will remain if reclaimPolicy is Retain (default for many StorageClasses)
# Check with: kubectl get pvc --all-namespaces