Tag 4: Multi-Container-Pods
Ziel: Du baust Pods mit Init-Containern, Sidecars, Adaptern und Ambassadors und steuerst gezielt einzelne Container an. · Dauer: ca. 60 min · Voraussetzung: Tag 3
Briefing
CKAD: Application Design and Build (20 %) – „Understand
multi-container Pod design patterns (e.g. sidecar, init and others)“.
Alle Container eines Pods teilen sich Netzwerk (localhost)
und Volumes, laufen aber als getrennte Prozesse mit eigenen Logs.
Pod ────────────────────────────────────────────────────────────
| init-1 -> init-2 -> [native Sidecar] -> app + klassischer Sidecar |
| nacheinander, läuft bis zum gemeinsames emptyDir, |
| jeder bis Ende Schluss localhost |
─────────────────────────────────────────────────────────────────
Muster: Init (vorbereiten), Sidecar (ergänzen, z. B. Logs verschicken), Adapter (Ausgabe umformen), Ambassador (Verbindung nach außen vermitteln).
Drill 1: Init-Container
k create ns tag04
k config set-context --current --namespace=tag04
mkdir -p ~/ckad/tag04 && cd ~/ckad/tag04
cat > init.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: web
spec:
initContainers:
- name: wait-db
image: busybox:1.37
command:
- sh
- -c
- until nslookup db.tag04.svc.cluster.local; do echo warte auf db; sleep 2; done
- name: content
image: busybox:1.37
command: ["sh", "-c", "echo 'Hallo aus dem Init-Container' > /work/index.html"]
volumeMounts:
- name: html
mountPath: /work
containers:
- name: nginx
image: nginx:1.29
volumeMounts:
- name: html
mountPath: /usr/share/nginx/html
volumes:
- name: html
emptyDir: {}
EOF
k apply -f init.yaml
k get pod web
k logs web -c wait-db --tail=2Erwartet:
pod/web created
NAME READY STATUS RESTARTS AGE
web 0/1 Init:0/2 0 8s
warte auf db
Init:0/2: Keiner der zwei Init-Container ist fertig. Den
Service anlegen, auf den wait-db wartet:
k create service clusterip db --tcp=5432:5432
k get pod web
curl -s $(k get pod web -o jsonpath='{.status.podIP}')Erwartet:
service/db created
NAME READY STATUS RESTARTS AGE
web 1/1 Running 0 17s
Hallo aus dem Init-Container
Achtung:
nslookup dbmit Kurznamen endet in busybox 1.37 mit Exit-Code 1, auch wenn der Name aufgelöst wird – die Suchdomains liefern NXDOMAIN. Im Init-Container deshalb den vollen Namen verwenden.
Fortschritt speichern? Kostenlos registrieren
Drill 2: Init-Container untersuchen
J='{range .status.initContainerStatuses[*]}'
J+='{.name}{" "}{.state.terminated.reason}{"\n"}{end}'
k get pod web -o jsonpath="$J"
k logs web | head -1Erwartet:
wait-db Completed
content Completed
Defaulted container "nginx" out of: nginx, wait-db (init), content (init)
Ohne -c nimmt kubectl den ersten regulären Container und
sagt es dir. Solange ein Init-Container läuft, scheitert
k logs web mit „is waiting to start: PodInitializing” –
dann gezielt -c wait-db.
Fortschritt speichern? Kostenlos registrieren
Drill 3: Klassischer Sidecar mit emptyDir
Die Anwendung schreibt in eine Datei, der Sidecar gibt sie auf stdout
aus, damit k logs sie sieht:
cat > logger.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: logger
spec:
containers:
- name: app
image: busybox:1.37
command:
- sh
- -c
- while true; do date '+%T GET /notes 200' >> /log/access.log; sleep 5; done
volumeMounts:
- name: logs
mountPath: /log
- name: log-shipper
image: busybox:1.37
command: ["tail", "-n+1", "-F", "/log/access.log"]
volumeMounts:
- name: logs
mountPath: /log
readOnly: true
volumes:
- name: logs
emptyDir: {}
EOF
k apply -f logger.yaml
k get pod logger
k logs logger -c log-shipper --tail=2Erwartet:
pod/logger created
NAME READY STATUS RESTARTS AGE
logger 2/2 Running 0 14s
15:48:51 GET /notes 200
15:48:56 GET /notes 200
Fortschritt speichern? Kostenlos registrieren
Drill 4: In einzelne Container hinein
k exec logger -c app -- ls -l /log
k exec logger -c log-shipper -- sh -c 'echo x >> /log/access.log'
k logs logger --all-containers --prefix --tail=1Erwartet:
total 4
-rw-r--r-- 1 root root 72 Nov 18 15:48 access.log
sh: can't create /log/access.log: Read-only file system
command terminated with exit code 1
[pod/logger/log-shipper] 15:48:56 GET /notes 200
Gleiches Volume, unterschiedliche Rechte: readOnly: true
gilt pro volumeMount, also pro Container. app
schreibt nur in die Datei, daher liefert --all-containers
nur Zeilen vom Sidecar.
Fortschritt speichern? Kostenlos registrieren
Drill 5: Adapter
Ein Adapter formt die Ausgabe der Anwendung in ein Format um, das ein
anderes System erwartet – hier key=value statt Freitext.
Pods sind unveränderlich, also in logger.yaml einen dritten
Container unter containers: ergänzen:
- name: adapter
image: busybox:1.37
command:
- sh
- -c
- |
tail -n+1 -F /log/access.log \
| awk '{print "time=" $1, "path=" $3, "status=" $4; fflush()}'
volumeMounts:
- name: logs
mountPath: /log
readOnly: truek replace -f logger.yaml $now
k get pod logger
k logs logger -c adapter --tail=2
k get pod logger -o jsonpath='{.spec.containers[*].name}{"\n"}'Erwartet (gekürzt):
pod "logger" force deleted from tag04 namespace
pod/logger replaced
NAME READY STATUS RESTARTS AGE
logger 3/3 Running 0 21s
time=15:51:38 path=/notes status=200
time=15:51:43 path=/notes status=200
app log-shipper adapter
Warum fflush()? Schreibt awk in eine Pipe statt ins
Terminal, puffert es – ohne Flush siehst du in k logs lange
nichts.
Fortschritt speichern? Kostenlos registrieren
Drill 6: Ambassador
Ein Ambassador nimmt der Anwendung die Verbindung nach außen ab. Hier
spricht die App nur mit localhost:8001,
kubectl proxy im Ambassador kümmert sich um API-Server,
Token und TLS:
cat > amb.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: client
spec:
containers:
- name: app
image: busybox:1.37
command:
- sh
- -c
- while true; do wget -qO- -T 2 localhost:8001/version | grep gitV; sleep 10; done
- name: api-ambassador
image: registry.k8s.io/kubectl:v1.37.2
args: ["proxy", "--port=8001"]
EOF
k apply -f amb.yaml
k logs client -c app
k logs client -c api-ambassadorErwartet:
pod/client created
wget: can't connect to remote host (127.0.0.1): Connection refused
"gitVersion": "v1.37.2",
Starting to serve on 127.0.0.1:8001
Die erste Anfrage geht ins Leere: Beide Container starten gleichzeitig, der Proxy war noch nicht bereit. Das löst Drill 7.
Fortschritt speichern? Kostenlos registrieren
Drill 7: Native Sidecar
Ein Init-Container mit restartPolicy: Always ist ein
nativer Sidecar: Er startet vor den regulären Containern (in der
Reihenfolge der Liste), läuft aber bis zum Schluss weiter. Den
Ambassador in amb.yaml umziehen:
cat > amb.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: client
spec:
initContainers:
- name: api-ambassador
image: registry.k8s.io/kubectl:v1.37.2
args: ["proxy", "--port=8001"]
restartPolicy: Always
containers:
- name: app
image: busybox:1.37
command:
- sh
- -c
- while true; do wget -qO- -T 2 localhost:8001/version | grep gitV; sleep 10; done
EOF
k replace -f amb.yaml $now
k get pod client
k logs client -c appErwartet (gekürzt):
pod/client replaced
NAME READY STATUS RESTARTS AGE
client 2/2 Running 0 15s
"gitVersion": "v1.37.2",
"gitVersion": "v1.37.2",
READY 2/2 zählt den nativen Sidecar mit. Brauchst du
eine echte Bereitschaftsgarantie, gib dem Sidecar eine
startupProbe – die regulären Container starten erst, wenn
sie erfolgreich ist.
Achtung: Eine
tcpSocket-Probe auf Port 8001 scheitert hier mit „connect: connection refused”: Das kubelet prüft die Pod-IP,kubectl proxylauscht nur auf127.0.0.1.
Fortschritt speichern? Kostenlos registrieren
Drill 8: Reihenfolge beim Stoppen
Der eigentliche Gewinn nativer Sidecars zeigt sich bei Jobs: Ist die Anwendung fertig, beendet das kubelet die Sidecars – ein klassischer Sidecar würde den Job ewig am Laufen halten.
cat > export.yaml <<'EOF'
apiVersion: batch/v1
kind: Job
metadata:
name: export
spec:
template:
spec:
restartPolicy: Never
initContainers:
- name: prep
image: busybox:1.37
command: ["sh", "-c", "echo prep fertig; sleep 2"]
- name: log-shipper
image: busybox:1.37
restartPolicy: Always
command:
- sh
- -c
- trap 'exit 0' TERM; tail -n+1 -F /log/job.log & wait
volumeMounts:
- name: logs
mountPath: /log
containers:
- name: app
image: busybox:1.37
command:
- sh
- -c
- for i in 1 2 3; do echo Export Teil $i >> /log/job.log; sleep 3; done
volumeMounts:
- name: logs
mountPath: /log
volumes:
- name: logs
emptyDir: {}
EOF
k apply -f export.yaml
k wait --for=condition=complete job/export --timeout=60s
k get job exportErwartet:
job.batch/export created
job.batch/export condition met
NAME STATUS COMPLETIONS DURATION AGE
export Complete 1/1 18s 18s
Start- und Endzeiten aller Container:
S='{.name} {.state.terminated.startedAt} {.state.terminated.finishedAt} '
S="$S"'{.state.terminated.exitCode}{"\n"}'
P=$(k get pods -l job-name=export -o name)
k get $P -o jsonpath="{range .status.initContainerStatuses[*]}$S{end}"
k get $P -o jsonpath="{range .status.containerStatuses[*]}$S{end}"Erwartet:
prep 2026-11-18T15:50:17Z 2026-11-18T15:50:19Z 0
log-shipper 2026-11-18T15:50:19Z 2026-11-18T15:50:29Z 0
app 2026-11-18T15:50:20Z 2026-11-18T15:50:29Z 0
Start: prep bis zum Ende, dann der Sidecar, dann
app. Stopp: erst app, danach der Sidecar
(mehrere Sidecars in umgekehrter Reihenfolge). Warum der
trap? Eine Shell als PID 1 ignoriert SIGTERM. Ohne ihn
wartet das kubelet die 30 Sekunden Grace Period ab und beendet den
Sidecar mit Exit-Code 137 – der Job dauerte im Test 49 statt 18
Sekunden.
Fortschritt speichern? Kostenlos registrieren
Übung: Speed-Drills
- Pod
twomit Containerweb(nginx:1.29) und Containersh(busybox:1.37,sleep 3600). Zeitziel: 90 s - Zeige die letzten zwei Zeilen des Containers
adapterim Podlogger. Zeitziel: 15 s - Liste im Container
log-shippervonloggerdas Verzeichnis/log. Zeitziel: 15 s
Lösung
k run two --image=nginx:1.29 $do > two.yaml
vim two.yamlDen Container-Teil so ändern:
containers:
- image: nginx:1.29
name: web
- image: busybox:1.37
name: sh
command: ["sleep", "3600"]k apply -f two.yaml
k logs logger -c adapter --tail=2
k exec logger -c log-shipper -- ls /logErwartet (gekürzt):
pod/two created
time=15:52:28 path=/notes status=200
time=15:52:33 path=/notes status=200
access.log
Fortschritt speichern? Kostenlos registrieren
Kontrollpunkt
k get pod two -o jsonpath='{.spec.containers[*].name}'Erwartet: web sh
k get pod client -o jsonpath='{.spec.initContainers[0].restartPolicy}'Erwartet: Always
k get pod loggerErwartet: READY 3/3,
STATUS Running
Challenge
Ein Deployment notes mit notes-api:1.0 soll
den API-Key nicht als Umgebungsvariable bekommen: Ein Init-Container
schreibt ihn in ein emptyDir im Arbeitsspeicher, notes-api liest ihn
über NOTES_API_KEY_FILE.
Hinweis: emptyDir.medium: Memory legt
das Volume als tmpfs an.
Lösung
cat > notes.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: notes
name: notes
spec:
replicas: 1
selector:
matchLabels:
app: notes
template:
metadata:
labels:
app: notes
spec:
initContainers:
- name: write-key
image: busybox:1.37
command: ["sh", "-c", "echo lab-key-123 > /secrets/api-key"]
volumeMounts:
- name: secrets
mountPath: /secrets
containers:
- image: 172.16.0.126:30500/notes-api:1.0
name: notes-api
env:
- name: NOTES_API_KEY_FILE
value: /secrets/api-key
volumeMounts:
- name: secrets
mountPath: /secrets
readOnly: true
volumes:
- name: secrets
emptyDir:
medium: Memory
EOF
k apply -f notes.yaml
k rollout status deployment/notes
k logs deployment/notes | head -1Erwartet (gekürzt):
deployment.apps/notes created
deployment "notes" successfully rolled out
Defaulted container "notes-api" out of: notes-api, write-key (init)
time=2026-11-18T15:52:39.722Z level=INFO msg="api key loaded" source=file
source=file bestätigt den Weg über die Datei. Ein Key im
Klartext im Init-Container ist natürlich nur ein Lab-Wert – in Tag 6
kommt er aus einem Secret.
Aufräumen:
k config set-context --current --namespace=default
k delete ns tag04Fortschritt speichern? Kostenlos registrieren
Prüfungstipp
- Native Sidecars stehen unter
initContainersmitrestartPolicy: Always– nicht untercontainers. In der Doku unter „Sidecar Containers” (Concepts → Workloads → Pods). - Bei mehreren Containern immer
-c <name>beik logsundk exec; Containernamen liefertk get pod <p> -o jsonpath='{.spec.containers[*].name}'. - Container zu einem laufenden Pod hinzufügen geht nicht: Datei
ändern,
k replace -f … $now. Bei Deployments genügtk apply.
Enterprise-Notiz
- Service Meshes (Istio, Linkerd) injizieren Proxy-Sidecars automatisch per Admission Webhook; Istio nutzt dafür inzwischen native Sidecars.
- Log-Sidecars sind teuer (Container pro Pod). Üblicher ist ein DaemonSet-Agent (Fluent Bit, Vector), der die Container-Logs der Nodes liest.
- Jeder Sidecar braucht Requests und Limits – sie zählen zum Pod und damit zu Quotas und Scheduling (Tag 7).