Zum Inhalt springen
Trainingslager IT-Trainingslager

Tag 15: Troubleshooting II – kaputte Apps und Netze

Ziel: Du erkennst an Status, Events und Logs in Sekunden, warum eine App nicht läuft oder nicht erreichbar ist – und behebst es. · Dauer: ca. 75 min · Voraussetzung: Tag 9

Briefing

CKA: Troubleshooting (30 %) – „Manage and evaluate container output streams”, „Troubleshoot services and networking”.

Status / Symptom Ursache meistens Werkzeug
CrashLoopBackOff, Error Befehl, Config, Absturz k logs
ImagePullBackOff Name, Tag, Registry-Zugang k describe pod
OOMKilled, Exit 137 Memory-Limit zu klein k describe pod
Service: Connection refused Selector, targetPort, Readiness k get endpointslices
bad address DNS CoreDNS prüfen
download timed out NetworkPolicy k get netpol
k create ns tag15
k config set-context --current --namespace=tag15

Drill 1: Drei kaputte Pods

k run crash --image=busybox:1.37 -- \
  sh -c 'echo starte; echo Konfiguration fehlt >&2; exit 1'
k run pull --image=nginx:1.299
cat <<'EOF' | k apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: hungry
spec:
  containers:
  - name: app
    image: polinux/stress:1.0.4
    command: ["stress", "--vm", "1", "--vm-bytes", "200M", "--vm-hang", "1"]
    resources:
      limits:
        memory: 100Mi
EOF
k get pods

Erwartet (nach etwa 45 s):

NAME     READY   STATUS             RESTARTS      AGE
crash    0/1     Error              3 (30s ago)   46s
hungry   0/1     OOMKilled          3 (26s ago)   45s
pull     0/1     ImagePullBackOff   0             46s

Der Status wechselt zwischen Error und CrashLoopBackOff – Kubernetes wartet zwischen den Neustarts immer länger (bis fünf Minuten).

Fortschritt speichern? Kostenlos registrieren

Drill 2: Logs eines abstürzenden Containers

k logs crash
k describe pod crash | grep -A3 'Last State'

Erwartet:

Konfiguration fehlt
starte
    Last State:     Terminated
      Reason:       Error
      Exit Code:    1

k logs zeigt stdout und stderr gemischt. Exit-Code 1 heißt: Das Programm selbst hat aufgegeben – die Ursache steht in seiner Ausgabe.

Für einen Container, der nach einem Neustart wieder läuft, gibt es k logs crash --previous. In unserem Labor (Kubernetes 1.37.2 mit containerd 2.4.2) antwortete der Befehl jedoch mit unable to retrieve container logs for containerd://…. Dann gehst du eine Ebene tiefer – auf den Node, auf dem der Pod läuft:

k get pod crash -o jsonpath='{.spec.nodeName}{"\n"}'

Auf diesem Node:

sudo sh -c 'ls /var/log/pods/tag15_crash_*/crash/'
sudo crictl ps -a --name crash
sudo crictl logs $(sudo crictl ps -a --name crash -q | head -1)

Erwartet (gekürzt):

3.log
CONTAINER       IMAGE           CREATED          STATE     NAME    ATTEMPT   ...
eb36c57c3e879   30ecbe1509090   38 seconds ago   Exited    crash   3         ...
starte
Konfiguration fehlt

Die Datei 3.log gehört zum vierten Lauf (gezählt ab 0). In diesem Labor hielt der Node nur den jüngsten beendeten Container vor – deshalb fand --previous nichts. Merke den Weg: --previous zuerst, sonst crictl und /var/log/pods auf dem Node.

Fortschritt speichern? Kostenlos registrieren

Drill 3: Image und Memory

k describe pod pull | grep -E 'Failed' | tail -2
k describe pod hungry | grep -A3 'Last State'

Erwartet (gekürzt):

  Warning  Failed  2s (x3 over 45s)  kubelet  spec.containers{pull}: Failed to pull
image
"nginx:1.299": rpc error: code = NotFound desc = failed to pull and unpack image ...
  Warning  Failed  2s (x3 over 45s)  kubelet  spec.containers{pull}: Error: ErrImagePull
    Last State:     Terminated
      Reason:       OOMKilled
      Exit Code:    137

Exit-Code 137 = 128 + 9: Der Kernel hat den Prozess mit SIGKILL beendet, weil er mehr als die 100Mi des Limits wollte. Reparieren heißt: Limit erhöhen oder die App sparsamer machen.

k delete pod crash pull hungry --now

Fortschritt speichern? Kostenlos registrieren

Drill 4: Ein Service ohne Endpoints

k create deployment shop --image=registry.k8s.io/e2e-test-images/agnhost:2.53 \
  --replicas=2 -- /agnhost netexec --http-port=8080
cat <<'EOF' | k apply -f -
apiVersion: v1
kind: Service
metadata:
  name: shop
spec:
  selector:
    app: webshop
  ports:
  - port: 80
    targetPort: 8080
EOF
k run client --image=busybox:1.37 -- sleep 3600
k exec client -- wget -qO- -T3 shop/hostname

Erwartet:

wget: can't connect to remote host (10.105.116.134): Connection refused
command terminated with exit code 1

DNS funktioniert (die IP ist aufgelöst), aber niemand antwortet:

k get endpointslices -l kubernetes.io/service-name=shop
k get svc shop -o jsonpath='{.spec.selector}{"\n"}'
k get pods --show-labels | grep shop | head -1

Erwartet:

NAME         ADDRESSTYPE   PORTS     ENDPOINTS   AGE
shop-d4xtk   IPv4          <unset>   <unset>     4s
{"app":"webshop"}
shop-d9fdd5c8b-c5lll   1/1   Running   0   7s   app=shop,pod-template-hash=d9fdd5c8b

Der Selector sucht app=webshop, die Pods heißen app=shop:

k set selector svc shop app=shop
k exec client -- wget -qO- -T3 shop/hostname; echo

Erwartet: shop-d9fdd5c8b-c5lll

Fortschritt speichern? Kostenlos registrieren

Drill 5: Endpoints da – und trotzdem tot

k patch svc shop -p '{"spec":{"ports":[{"port":80,"targetPort":9090}]}}'
k exec client -- wget -qO- -T3 shop/hostname
k get endpointslices -l kubernetes.io/service-name=shop

Erwartet:

wget: can't connect to remote host (10.105.116.134): Connection refused
command terminated with exit code 1
NAME         ADDRESSTYPE   PORTS   ENDPOINTS                        AGE
shop-d4xtk   IPv4          9090    192.168.189.96,192.168.235.177   7s

Diesmal stehen Pods dahinter, aber auf dem falschen Port – die Spalte PORTS verrät es. Der Container lauscht auf 8080:

k patch svc shop -p '{"spec":{"ports":[{"port":80,"targetPort":8080}]}}'

Fortschritt speichern? Kostenlos registrieren

Drill 6: Keine Namensauflösung

k scale deployment coredns -n kube-system --replicas=0
k exec client -- wget -qO- -T3 shop/hostname
k exec client -- nslookup shop.tag15.svc.cluster.local

Erwartet:

wget: bad address 'shop'
command terminated with exit code 1
nslookup: write to '10.96.0.10': Connection refused
command terminated with exit code 1

bad address ist immer DNS. Den DNS-Dienst prüfen wie jeden anderen Service:

k get svc,endpointslices -n kube-system -l k8s-app=kube-dns
k get deployment coredns -n kube-system

Erwartet (gekürzt):

NAME               TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)
service/kube-dns   ClusterIP   10.96.0.10   <none>        53/UDP,53/TCP,9153/TCP
NAME                                            ADDRESSTYPE   PORTS     ENDPOINTS
endpointslice.discovery.k8s.io/kube-dns-5xj56   IPv4          <unset>   <unset>
NAME      READY   UP-TO-DATE   AVAILABLE   AGE
coredns   0/0     0            0           105m
k scale deployment coredns -n kube-system --replicas=2
k rollout status deployment coredns -n kube-system
k exec client -- wget -qO- -T3 shop/hostname; echo

Erwartet: wieder ein Podname.

Fortschritt speichern? Kostenlos registrieren

Drill 7: Eine Policy, die niemand kannte

cat <<'EOF' | k apply -f -
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: lockdown
spec:
  podSelector:
    matchLabels:
      app: shop
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          role: frontend
EOF
k exec client -- wget -qO- -T3 shop/hostname

Erwartet:

wget: download timed out
command terminated with exit code 1

timed out statt refused: Die Pakete verschwinden. Das riecht nach NetworkPolicy:

k get netpol
k describe netpol lockdown | grep -A4 'Allowing ingress'

Erwartet (gekürzt):

NAME       POD-SELECTOR   AGE
lockdown   app=shop       4s
  Allowing ingress traffic:
    To Port: <any> (traffic allowed to all ports)
    From:
      PodSelector: role=frontend

Der Client ist kein Frontend. Wenn er hineindarf, bekommt er das Label:

k label pod client role=frontend
k exec client -- wget -qO- -T3 shop/hostname; echo

Erwartet: wieder ein Podname.

Fortschritt speichern? Kostenlos registrieren

Übung: Speed-Drills

Eine App mit Sidecar – der native Sidecar läuft als Init-Container mit restartPolicy: Always:

cat <<'EOF' | k apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: app-with-sidecar
spec:
  initContainers:
  - name: log-shipper
    image: busybox:1.37
    restartPolicy: Always
    command: ["sh", "-c", "tail -F /var/log/app/app.log"]
    volumeMounts:
    - name: logs
      mountPath: /var/log/app
  containers:
  - name: app
    image: busybox:1.37
    command: ["sh", "-c", "i=0; while true; do i=$((i+1));
      echo Bestellung $i >> /var/log/app/app.log; sleep 2; done"]
    volumeMounts:
    - name: logs
      mountPath: /var/log/app
  volumes:
  - name: logs
    emptyDir: {}
EOF
  1. Zeige die letzten zwei Zeilen des Sidecars log-shipper. Zeitziel: 20 s
  2. Zeige von allen shop-Pods die jeweils letzte Logzeile, mit Podnamen davor. Zeitziel: 30 s
  3. Zeige alle Container von app-with-sidecar, nur die letzten 4 Sekunden. Zeitziel: 20 s

Lösung

k logs app-with-sidecar -c log-shipper --tail=2
k logs -l app=shop --prefix --tail=1
k logs app-with-sidecar --all-containers --since=4s

Erwartet (Ausschnitt):

Bestellung 3
Bestellung 4
[pod/shop-d9fdd5c8b-c5lll/agnhost] I1117 22:57:25.389930  1 log.go:245] GET /hostname
[pod/shop-d9fdd5c8b-qqplx/agnhost] I1117 22:58:05.147661  1 log.go:245] GET /hostname
Bestellung 3
Bestellung 4

Ohne -c nimmt k logs den ersten normalen Container und sagt es dir: Defaulted container "app" out of: app, log-shipper (init).

Fortschritt speichern? Kostenlos registrieren

Kontrollpunkt

k get endpointslices -l kubernetes.io/service-name=shop \
  -o jsonpath='{.items[0].ports[0].port}{"\n"}'

Erwartet: 8080

k get deploy coredns -n kube-system -o jsonpath='{.status.readyReplicas}{"\n"}'

Erwartet: 2

k get pod app-with-sidecar

Erwartet: READY 2/2, Running.

Challenge

Die API ist Running, aber nie bereit, und der Service antwortet nicht. Baue das nach und finde den Fehler:

cat <<'EOF' | k apply -f -
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
spec:
  replicas: 1
  selector:
    matchLabels:
      app: api
  template:
    metadata:
      labels:
        app: api
    spec:
      containers:
      - name: agnhost
        image: registry.k8s.io/e2e-test-images/agnhost:2.53
        command: ["/agnhost", "netexec", "--http-port=8080"]
        readinessProbe:
          httpGet:
            path: /healthz
            port: 8081
          periodSeconds: 3
EOF
k expose deployment api --port=80 --target-port=8080

Hinweis: Ein Endpoint, der nicht ready ist, bekommt keinen Verkehr.

Lösung

k get pods -l app=api
k get endpointslices -l kubernetes.io/service-name=api \
  -o jsonpath='{.items[0].endpoints[0].conditions}{"\n"}'
k describe pod -l app=api | grep 'Readiness probe failed' | tail -1

Erwartet (gekürzt):

NAME                   READY   STATUS    RESTARTS   AGE
api-7bcb94444d-hnhwm   0/1     Running   0          26s
{"ready":false,"serving":false,"terminating":false}
  Warning  Unhealthy  1s (x10 over 26s)  kubelet  spec.containers{agnhost}: Readiness
probe
failed: Get "http://192.168.189.106:8081/healthz": dial tcp 192.168.189.106:8081:
connect:
connection refused

Die Probe fragt Port 8081, die App lauscht auf 8080:

k patch deployment api --type=json -p='[{"op":"replace",
  "path":"/spec/template/spec/containers/0/readinessProbe/httpGet/port","value":8080}]'
k rollout status deployment api
k exec client -- wget -qO- -T3 api/hostname; echo

Erwartet:

deployment "api" successfully rolled out
api-697bfbbbcf-xqncz

Aufräumen:

k config set-context --current --namespace=default
k delete ns tag15

Fortschritt speichern? Kostenlos registrieren

Prüfungstipp

  • Fehlermeldung genau lesen: refused (niemand lauscht), timed out (Pakete verschwinden), bad address (DNS) – drei Ursachen, drei Werkzeuge.
  • k get endpointslices beantwortet in einem Befehl, ob Selector, Port und Readiness stimmen.
  • k describe pod und die Events darunter zuerst, Logs danach.

Enterprise-Notiz

  • Logs gehören zentral gesammelt (Loki, Elasticsearch); auf dem Node rotieren sie weg.
  • Readiness- und Liveness-Probes auf eigene Endpunkte, nicht auf die Startseite der App.
  • Für Netzwerkfehler Flow-Logs nutzen (Calico Whisker, Cilium Hubble) statt zu raten.