Skip to content
Hands-on IT IT Drills

Appendix A: Cheat Sheet

The most important commands from all days, ordered by curriculum domain. The days are in parentheses. You replace the placeholders in angle brackets.

Setup (Day 1)

source <(kubectl completion bash)
alias k=kubectl
complete -o default -F __start_kubectl k
export do="--dry-run=client -o yaml"         # generate YAML instead of creating
export now="--force --grace-period=0"        # delete immediately

~/.vimrc for YAML: set expandtab, set tabstop=2, set shiftwidth=2.

k config get-contexts
k config use-context <context>                # first action of every task
k config set-context --current --namespace=<ns>
k explain cronjob.spec.jobTemplate.spec
k explain pod.spec.containers.securityContext --recursive
k api-resources | grep -i <name>              # short name, group, namespaced?
k create cronjob -h                           # examples for every command

Application Design and Build (Days 2–5)

podman build -t <name>:<tag> --build-arg VERSION=1.1 .
podman run --rm <name>:<tag>
podman image inspect <img> --format '{{.Config.User}} {{.Config.Entrypoint}}'
podman history <img>
podman save -o <file>.tar <img>                          # Docker archive
podman save --format oci-archive -o <file>.tar <img>     # OCI archive
podman push --tls-verify=false 172.16.0.126:30500/<name>:<tag>
k create deployment <d> --image=<img> --replicas=3 --port=8080 $do > d.yaml
k run <p> --image=busybox:1.37 $do --command -- sleep 3600 > p.yaml
k create job <j> --image=busybox:1.37 $do -- date > j.yaml
k create cronjob <cj> --image=busybox:1.37 --schedule="*/10 * * * *" -- date
k create job <j> --from=cronjob/<cj>          # run a CronJob once, right now
k patch cronjob <cj> -p '{"spec":{"suspend":true}}'
k logs <pod> -c <container>
k exec <pod> -c <container> -- <command>
k get pod <pod> -o jsonpath='{.spec.containers[*].name}{"\n"}'
  • DaemonSet and StatefulSet: generate Deployment YAML and change kind. For the DaemonSet, delete replicas and strategy; the StatefulSet needs serviceName and a headless Service (k create service clusterip <s> --clusterip=None --tcp=80:80).
  • The job fields completions, parallelism, backoffLimit, activeDeadlineSeconds go under the Job’s spec, for a CronJob under spec.jobTemplate.spec.
  • Native sidecar: under initContainers with restartPolicy: Always.

Application Deployment (Days 11–13)

k set image deploy/<d> <container>=<img>      # container name, not Deployment name
k annotate deploy <d> kubernetes.io/change-cause="<reason>" --overwrite
k rollout status deploy/<d>
k rollout history deploy/<d> [--revision=2]
k rollout undo deploy/<d> [--to-revision=2]
k rollout pause|resume|restart deploy/<d>
k scale deploy <d> --replicas=5
k set selector svc <s> 'app=<a>,version=green'           # switch blue/green
k get pods -l app=<a> --show-labels
helm repo add <repo> <url> && helm repo update
helm search repo <repo>/<chart> --versions
helm show values <repo>/<chart> --version <v>
helm install <rel> <repo>/<chart> -n <ns> --create-namespace --version <v> \
  --set replicaCount=2 -f values.yaml
helm upgrade <rel> <repo>/<chart> -n <ns> --version <new> --reset-then-reuse-values
helm list -A
helm history|rollback|uninstall <rel> -n <ns>
helm get values|manifest <rel> -n <ns>
helm template <rel> <repo>/<chart> | grep '^kind:'
k kustomize <overlay>                         # look at it first
k diff -k <overlay>
k apply -k <overlay>

Warning: helm upgrade --reuse-values with a new chart version keeps the default values of the old version – including the image tag. When changing versions, use --reset-then-reuse-values (Appendix B, Task 7).

Kustomize overlay with the most common fields:

resources:
- ../base
namespace: <ns>
namePrefix: prod-
labels:
- pairs:
    env: prod
images:
- name: 172.16.0.126:30500/notes-api
  newTag: "1.1"
replicas:
- name: notes
  count: 2
secretGenerator:
- name: notes-key
  literals:
  - api-key=lab-key-123

Application Observability and Maintenance (Days 14, 15)

k get events --sort-by=.lastTimestamp
k get events --field-selector type=Warning
k get events --field-selector reason=Unhealthy
k describe pod <p> | tail -20
k logs <p> [-c <c>] --tail=20 --since=5m
k logs <p> -p                                 # previous run after a restart
k logs -l app=<a> --prefix --all-containers --tail=3
k logs deploy/<d> > /path/file.log            # result into a file, then cat
k top pod --containers --sort-by=memory
k top node
k debug <p> -it --image=busybox:1.37 --target=<container> -- sh
k port-forward deploy/<d> 8080:8080
k cp <file> <p>:/tmp/<file>
k api-versions | grep -E '^(apps|batch|networking)'
k explain hpa --api-version=autoscaling/v1
k convert -f old.yaml --output-version batch/v1 > new.yaml   # kubectl-convert plugin
Symptom First command
ImagePullBackOff, ErrImagePull Events: tag, registry, name
CrashLoopBackOff, Error k logs, k logs -p
CreateContainerConfigError ConfigMap, Secret or key missing
OOMKilled, exit 137 Memory limit
Pending k describe pod: resources, PVC, taints
0/1 Running Readiness probe
many restarts without log errors Liveness probe
Deployment 0/3, no Pods ReplicaSet events: quota, PodSecurity
Service without endpoints Selector vs. --show-labels, targetPort

Application Environment, Configuration and Security (Days 6–10)

k create configmap <cm> --from-literal=K=V --from-file=<file> --from-env-file=<.env>
k create secret generic <s> --from-literal=K=V
k create secret tls <s> --cert=tls.crt --key=tls.key
k create secret docker-registry <s> --docker-server=<reg> --docker-username=<u> \
  --docker-password=<pw>
k get secret <s> -o jsonpath='{.data.K}' | base64 -d; echo
k set env deploy/<d> --from=secret/<s> [--prefix=NOTES_]
k set env deploy/<d> K=V
k set resources deploy/<d> -c <c> --requests=cpu=50m,memory=32Mi \
  --limits=cpu=100m,memory=64Mi
k create quota <q> --hard=pods=4,requests.cpu=1,requests.memory=512Mi
k describe quota <q>
k create sa <sa>
k set serviceaccount deploy/<d> <sa>
k create token <sa> --duration=1h
k create role <r> --verb=get,list,watch --resource=pods,pods/log
k create rolebinding <rb> --role=<r> --serviceaccount=<ns>:<sa>
k create rolebinding <rb> --clusterrole=view --serviceaccount=<ns>:<sa>
k auth can-i list deployments.apps -n <ns> --as=system:serviceaccount:<ns>:<sa>
k auth can-i get pods --subresource=log -n <ns> --as=system:serviceaccount:<ns>:<sa>
k label ns <ns> pod-security.kubernetes.io/enforce=restricted
k get crd
k explain <kind>.spec
  • k create role with several --verb/--resource gives all resources all verbs. Different permissions per resource → Role as YAML with several rules.
  • capabilities and readOnlyRootFilesystem exist only on the container, fsGroup only on the Pod.

Services and Networking (Days 16, 17)

k expose deploy <d> --port=80 --target-port=8080 [--type=NodePort]
k create service clusterip <s> --tcp=80:8080            # selector app=<s>
k create service nodeport <s> --tcp=80:8080 --node-port=30080
k get endpointslices -l kubernetes.io/service-name=<s>
k patch svc <s> --type=json \
  -p '[{"op":"replace","path":"/spec/ports/0/targetPort","value":8080}]'
k create ingress <i> --class=traefik --rule="host.lab/*=<svc>:80"
k create ingress <i> --class=traefik --rule="host.lab/api*=<svc>:80,tls=<secret>"
curl -s -H 'Host: host.lab' http://172.16.0.126:30080/
k run t --rm -i --image=busybox:1.37 --restart=Never -- wget -qO- -T 3 <svc>:<port>
k get netpol

DNS names: <svc>, <svc>.<ns>, <svc>.<ns>.svc.cluster.local.

from:                           from:
- namespaceSelector: {...}      - namespaceSelector: {...}
- podSelector: {...}              podSelector: {...}
  -> OR (two entries)             -> AND (one entry)

Default deny: podSelector: {} and only policyTypes. With egress rules, allow DNS (UDP and TCP 53). Policies add up – there is no “deny” as a rule.

Filtering output (Day 1)

k get pod <p> -o jsonpath='{.spec.nodeName}{" "}{.status.podIP}{"\n"}'
J='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}'
k get pods -o jsonpath="$J"
k get pods -o jsonpath='{.items[?(@.metadata.labels.role=="frontend")].metadata.name}'
k get pods -A -o jsonpath='{.items[*].spec.containers[*].image}' | tr ' ' '\n' | sort -u
C='NAME:.metadata.name,IMAGE:.spec.template.spec.containers[*].image'
k get deploy -o custom-columns="$C"
k get pods --no-headers -o custom-columns=:.metadata.name,:.spec.nodeName
k get pods --sort-by=.metadata.creationTimestamp
k get pods --sort-by=.status.containerStatuses[0].restartCount
k get pods -L app,track                       # labels as columns
k get pods -l 'app=notes,track!=canary' -o name

YAML snippets

Environment from ConfigMap and Secret (Day 6):

    envFrom:
    - configMapRef:
        name: <cm>
    env:
    - name: NOTES_API_KEY
      valueFrom:
        secretKeyRef:
          name: <s>
          key: api-key

Volumes (Days 5, 6):

    volumeMounts:
    - name: data
      mountPath: /data
    - name: key
      mountPath: /etc/notes
      readOnly: true
  volumes:
  - name: data
    persistentVolumeClaim:
      claimName: <pvc>
  - name: key
    secret:
      secretName: <s>
  - name: scratch
    emptyDir:
      sizeLimit: 100Mi
  - name: cfg
    configMap:
      name: <cm>

PVC (Day 5):

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: data
spec:
  accessModes: ["ReadWriteOnce"]
  storageClassName: local-path
  resources:
    requests:
      storage: 200Mi

Init container and native sidecar (Day 4):

  initContainers:
  - name: prep
    image: busybox:1.37
    command: ["sh", "-c", "echo bereit > /work/status"]
  - name: shipper
    image: busybox:1.37
    restartPolicy: Always
    command: ["sh", "-c", "tail -F /logs/access.log"]

Probes (Day 14):

        startupProbe:
          tcpSocket:
            port: 8080
          periodSeconds: 2
          failureThreshold: 30
        readinessProbe:
          httpGet:
            path: /healthz
            port: 8080
          periodSeconds: 5
        livenessProbe:
          exec:
            command: ["notes-api", "healthcheck"]
          periodSeconds: 10

SecurityContext for restricted (Days 8, 9):

spec:
  automountServiceAccountToken: false
  securityContext:
    runAsNonRoot: true
    runAsUser: 65532
    runAsGroup: 65532
    seccompProfile:
      type: RuntimeDefault
  containers:
  - name: app
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      capabilities:
        drop: ["ALL"]

Rolling update strategy (Day 11):

spec:
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0

LimitRange with default values (Day 7):

apiVersion: v1
kind: LimitRange
metadata:
  name: defaults
spec:
  limits:
  - type: Container
    defaultRequest:
      cpu: 100m
      memory: 64Mi
    default:
      memory: 128Mi

NetworkPolicy: access only from specific Pods (Day 17):

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-allow-frontend
spec:
  podSelector:
    matchLabels:
      app: api
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          role: frontend
    ports:
    - protocol: TCP
      port: 8080

Docs paths on kubernetes.io

All paths start with https://kubernetes.io/docs/.

Topic Path
kubectl commands, jsonpath reference/kubectl/quick-reference/
jsonpath syntax reference/kubectl/jsonpath/
Init containers concepts/workloads/pods/init-containers/
Sidecar containers concepts/workloads/pods/sidecar-containers/
Deployment, strategy concepts/workloads/controllers/deployment/
Job concepts/workloads/controllers/job/
CronJob concepts/workloads/controllers/cron-jobs/
Volumes (all types) concepts/storage/volumes/
PV and PVC concepts/storage/persistent-volumes/
ConfigMap in a Pod tasks/configure-pod-container/configure-pod-configmap/
Secrets concepts/configuration/secret/
Secret in a Pod tasks/inject-data-application/distribute-credentials-secure/
SecurityContext tasks/configure-pod-container/security-context/
ServiceAccounts tasks/configure-pod-container/configure-service-account/
Pod Security Standards concepts/security/pod-security-standards/
RBAC reference/access-authn-authz/rbac/
ResourceQuota concepts/policy/resource-quotas/
LimitRange concepts/policy/limit-range/
CRDs tasks/extend-kubernetes/custom-resources/custom-resource-definitions/
Probes tasks/configure-pod-container/configure-liveness-readiness-startup-probes/
Debugging running Pods tasks/debug/debug-application/debug-running-pod/
API deprecations reference/using-api/deprecation-guide/
Kustomize tasks/manage-kubernetes-objects/kustomization/
Service concepts/services-networking/service/
Ingress concepts/services-networking/ingress/
NetworkPolicy concepts/services-networking/network-policies/

Helm commands are documented under https://helm.sh/docs/ – helm <command> -h is faster.