Zum Inhalt springen
Trainingslager IT-Trainingslager

Tag 10: Helm – das eigene Chart

Ziel: notes wird ein Helm-Chart mit Hook-Job, Test und Schema; der Release übernimmt die laufende Datenbank samt Daten. · Dauer: ca. 120 min · Voraussetzung: Tag 9

Briefing

  • Ein Chart ist ein Ordner: Chart.yaml (Name, Versionen), values.yaml (Standardwerte), templates/ (Manifeste mit Go-Templates), optional values.schema.json (Prüfung der Values).
  • Hooks sind Objekte mit Annotation, die Helm zu bestimmten Zeitpunkten anlegt – hier migrate nach install und vor jedem upgrade.
  • Das Chart erzeugt dieselben Objekte wie die Manifeste aus Tag 8, mit denselben Namen. Darum findet das neue StatefulSet den alten PVC data-db-0.
  • Namespace, PSA-Labels, Quota, ServiceAccount und Secrets bleiben bei kubectl.
 k8s/namespace.yaml, k8s/secrets.sh   (Plattform, kubectl)
 chart/notes/                          (Anwendung, helm)
   Chart.yaml  values.yaml  values.schema.json  .helmignore
   templates/ _helpers.tpl api web worker db configmap migrate-job NOTES.txt
              tests/test-api.yaml

Drill 1: helm create – ansehen und wegwerfen

source ~/k8s-lab/setup/env.sh
mkdir -p ~/k8s-lab/tag10 && cd ~/k8s-lab/tag10
cp -R "$LAB/code/notes/." . && cp -R "$LAB/code/tag09/notes/." .
helm create demo
find demo -type f | sort
wc -l demo/values.yaml demo/templates/deployment.yaml
helm template demo ./demo | grep -E '^kind:' | sort | uniq -c
rm -rf demo

Erwartet (gekürzt):

Creating demo
demo/.helmignore
demo/Chart.yaml
demo/templates/NOTES.txt
demo/templates/_helpers.tpl
demo/templates/deployment.yaml
demo/templates/hpa.yaml
demo/templates/httproute.yaml
demo/templates/ingress.yaml
demo/templates/service.yaml
demo/templates/serviceaccount.yaml
demo/templates/tests/test-connection.yaml
demo/values.yaml
 161 demo/values.yaml
  78 demo/templates/deployment.yaml
 239 total
      1 kind: Deployment
      1 kind: Pod
      1 kind: Service
      1 kind: ServiceAccount

Das Gerüst ist ein Chart für jede Anwendung: Ingress, HTTPRoute, Autoscaler, alles abschaltbar, 161 Zeilen Values. Für notes wäre das meiste Ballast. Du übernimmst nur die Idee – Struktur, Helfer, Labels – und baust das Chart aus deinen Manifesten.

Fortschritt speichern? Kostenlos registrieren

Drill 2: Chart.yaml und values.yaml

mkdir -p chart/notes/templates/tests
cat > chart/notes/Chart.yaml <<'EOF'
# chart/notes/Chart.yaml – Stand Ende Tag 10
apiVersion: v2
name: notes
description: Die notes-Anwendung aus dem Trainingslager (api, web, worker, Postgres)
type: application
version: 0.1.0
appVersion: "0.2.0"
EOF
cat > chart/notes/values.yaml <<'EOF'
# chart/notes/values.yaml – Stand Ende Tag 10
# Secrets legt das Chart nicht an: k8s/secrets.sh erzeugt notes-api und notes-db.
existingSecrets:
  api: notes-api   # Schlüssel api-key
  db: notes-db     # Schlüssel password, db-url

api:
  replicas: 3
  image:
    repository: notes-api
    tag: ""        # leer = appVersion aus Chart.yaml
  resources:
    requests: {cpu: 50m, memory: 32Mi}
    limits: {memory: 64Mi}

web:
  replicas: 2
  image:
    repository: notes-web
    tag: 0.1.0
  service:
    type: NodePort
    nodePort: 30080
  resources:
    requests: {cpu: 50m, memory: 96Mi}
    limits: {memory: 192Mi}

worker:
  replicas: 1
  interval: 10
  image:
    repository: notes-worker
    tag: 0.1.0
  resources:
    requests: {cpu: 20m, memory: 64Mi}
    limits: {memory: 128Mi}

db:
  image:
    repository: postgres
    tag: 18.6-alpine
  storage: 1Gi
  storageClassName: ""   # leer = Standard-StorageClass des Clusters
  resources:
    requests: {cpu: 100m, memory: 128Mi}
    limits: {memory: 256Mi}
EOF
  • version ist die Version des Charts, appVersion die der Anwendung. Ein leerer api.image.tag nimmt appVersion – ein Upgrade der App ist dann eine Zeile in Chart.yaml.
  • Nur was sich zwischen Umgebungen unterscheidet, wird zum Value: Repliken, Images, Ressourcen, Service-Typ, Speicher. Probes und Ports bleiben fest im Template.
  • Die Secrets legt das Chart nicht an, es verweist nur auf ihre Namen. So landen keine Passwörter in Values und Release-Secrets (Tag 9, Enterprise-Notiz).

Fortschritt speichern? Kostenlos registrieren

Drill 3: Helfer und das erste Template

Wiederkehrende Blöcke kommen in _helpers.tpl. Dateien mit _ am Anfang rendert Helm nicht als Manifest, sie liefern nur define-Blöcke:

cat > chart/notes/templates/_helpers.tpl <<'EOF'
{{/* chart/notes/templates/_helpers.tpl – Stand Ende Tag 10 */}}

{{/* Labels für Komponente: include "notes.labels" (dict "ctx" $ "name" "api") */}}
{{- define "notes.labels" -}}
app.kubernetes.io/name: {{ .name }}
app.kubernetes.io/part-of: notes
app.kubernetes.io/instance: {{ .ctx.Release.Name }}
app.kubernetes.io/version: {{ .ctx.Chart.AppVersion | quote }}
app.kubernetes.io/managed-by: {{ .ctx.Release.Service }}
helm.sh/chart: {{ printf "%s-%s" .ctx.Chart.Name .ctx.Chart.Version }}
{{- end }}

{{- define "notes.selector" -}}
app.kubernetes.io/name: {{ . }}
{{- end }}

{{/* Image: include "notes.image" (dict "ctx" $ "image" .Values.api.image) */}}
{{- define "notes.image" -}}
{{ .image.repository }}:{{ .image.tag | default .ctx.Chart.AppVersion }}
{{- end }}

{{/* Pod-securityContext (restricted); optional mit fester UID */}}
{{- define "notes.podSecurity" -}}
serviceAccountName: notes
securityContext:
  runAsNonRoot: true
  {{- with .uid }}
  runAsUser: {{ . }}
  runAsGroup: {{ . }}
  {{- end }}
  {{- with .fsGroup }}
  fsGroup: {{ . }}
  {{- end }}
  seccompProfile:
    type: RuntimeDefault
{{- end }}

{{- define "notes.containerSecurity" -}}
securityContext:
  allowPrivilegeEscalation: false
  readOnlyRootFilesystem: true
  capabilities:
    drop: [ALL]
{{- end }}

{{/* Secrets als Dateien unter /etc/notes */}}
{{- define "notes.secretVolume" -}}
- name: secrets
  projected:
    sources:
      - secret:
          name: {{ .Values.existingSecrets.api }}
          items:
            - key: api-key
              path: api-key
      - secret:
          name: {{ .Values.existingSecrets.db }}
          items:
            - key: db-url
              path: db-url
{{- end }}
EOF
  • include "name" ARG ruft einen Block auf, nindent 4 rückt ihn ein und beginnt mit einem Zeilenumbruch. {{- und -}} schlucken Leerraum davor bzw. danach.
  • dict baut ein Argument aus mehreren Werten; $ ist der Wurzel-Kontext mit .Values, .Release und .Chart.
  • Der Selektor bleibt bei app.kubernetes.io/name – Selektoren sind unveränderlich, zusätzliche Labels darin würden jedes spätere Upgrade blockieren.

Jetzt api, gebaut aus k8s/api.yaml von Tag 8:

cat > chart/notes/templates/api.yaml <<'EOF'
# chart/notes/templates/api.yaml – Stand Ende Tag 10
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
  labels:
    {{- include "notes.labels" (dict "ctx" $ "name" "api") | nindent 4 }}
spec:
  replicas: {{ .Values.api.replicas }}
  revisionHistoryLimit: 5
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  selector:
    matchLabels:
      {{- include "notes.selector" "api" | nindent 6 }}
  template:
    metadata:
      labels:
        {{- include "notes.labels" (dict "ctx" $ "name" "api") | nindent 8 }}
    spec:
      {{- include "notes.podSecurity" dict | nindent 6 }}
      terminationGracePeriodSeconds: 30
      containers:
        - name: api
          image: {{ include "notes.image" (dict "ctx" $ "image" .Values.api.image) }}
          {{- include "notes.containerSecurity" . | nindent 10 }}
          env:
            - name: NOTES_API_KEY_FILE
              value: /etc/notes/api-key
            - name: NOTES_DB_URL_FILE
              value: /etc/notes/db-url
          ports:
            - containerPort: 8080
          resources:
            {{- toYaml .Values.api.resources | nindent 12 }}
          startupProbe:
            httpGet: {path: /healthz, port: 8080}
            periodSeconds: 1
            failureThreshold: 30
          readinessProbe:
            httpGet: {path: /healthz, port: 8080}
            periodSeconds: 5
          livenessProbe:
            httpGet: {path: /version, port: 8080}
            periodSeconds: 10
            failureThreshold: 3
          lifecycle:
            preStop:
              sleep:
                seconds: 5
          volumeMounts:
            - name: secrets
              mountPath: /etc/notes
              readOnly: true
      volumes:
        {{- include "notes.secretVolume" . | nindent 8 }}
---
apiVersion: v1
kind: Service
metadata:
  name: api
  labels:
    {{- include "notes.labels" (dict "ctx" $ "name" "api") | nindent 4 }}
spec:
  selector:
    {{- include "notes.selector" "api" | nindent 4 }}
  ports:
    - name: http
      port: 8080
      targetPort: 8080
EOF
helm lint chart/notes
helm template notes chart/notes -n notes -s templates/api.yaml \
  | sed -n '/^    spec:/,/^          env:/p'

Erwartet:

==> Linting chart/notes
[INFO] Chart.yaml: icon is recommended

1 chart(s) linted, 0 chart(s) failed
    spec:
      serviceAccountName: notes
      securityContext:
        runAsNonRoot: true
        seccompProfile:
          type: RuntimeDefault
      terminationGracePeriodSeconds: 30
      containers:
        - name: api
          image: notes-api:0.2.0
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: [ALL]
          env:

Stimmt das mit dem überein, was im Cluster läuft? kubectl diff vergleicht:

helm template notes chart/notes -n notes -s templates/api.yaml | kubectl diff -f - \
  | grep -E '^[-+] ' | grep -v generation | sort | uniq -c

Erwartet:

      1 +        app.kubernetes.io/instance: notes
      1 +        app.kubernetes.io/managed-by: Helm
      1 +        app.kubernetes.io/version: 0.2.0
      1 +        helm.sh/chart: notes-0.1.0
      2 +    app.kubernetes.io/instance: notes
      2 +    app.kubernetes.io/managed-by: Helm
      2 +    app.kubernetes.io/version: 0.2.0
      2 +    helm.sh/chart: notes-0.1.0

Nur Labels kommen dazu (Deployment, Service, Pod-Template) – sonst ist das Template identisch mit Tag 8. Diese Probe lohnt sich bei jedem Umbau von Manifesten zu Templates.

Fortschritt speichern? Kostenlos registrieren

Drill 4: Die übrigen Templates

web, worker, db und die ConfigMap folgen demselben Muster. Kopier sie aus dem Begleitcode und sieh dir die neuen Stellen an:

C="$LAB/code/tag10/notes/chart/notes"
cp "$C"/templates/{web,worker,db,configmap}.yaml chart/notes/templates/
grep -n -E 'if eq|with \.Values|checksum' chart/notes/templates/*.yaml | cut -c1-88

Erwartet:

chart/notes/templates/db.yaml:71:        {{- with .Values.db.storageClassName }}
chart/notes/templates/web.yaml:61:      {{- if eq .Values.web.service.type "NodePort" }}
chart/notes/templates/worker.yaml:19:        checksum/config: {{ $config | sha256sum }}
  • if eq … "NodePort" setzt nodePort nur, wenn der Service-Typ es erlaubt (Tag 11 stellt auf ClusterIP um).
  • with gibt den Block nur aus, wenn der Wert nicht leer ist; ohne storageClassName nimmt der PVC die Standard-StorageClass.
  • checksum/config ist eine Annotation am Pod-Template von worker mit dem SHA-256 der gerenderten ConfigMap. Ändert sich die ConfigMap, ändert sich das Pod-Template – und worker startet neu. Ohne diesen Trick bliebe er beim alten INTERVAL, denn envFrom liest nur beim Start.
helm template notes chart/notes -n notes -s templates/worker.yaml | grep checksum
helm template notes chart/notes -n notes | grep -E '^kind:' | sort | uniq -c

Erwartet (gekürzt):

        checksum/config: 8641aae49cf2e02889d1453b8ce37222f6390c4…
      1 kind: ConfigMap
      3 kind: Deployment
      3 kind: Service
      1 kind: StatefulSet

Fortschritt speichern? Kostenlos registrieren

Drill 5: Hook-Job, Test und NOTES.txt

migrate wird ein Hook. Der Kopf der Datei (vollständig: code/tag10/notes/chart/notes/templates/migrate-job.yaml):

# chart/notes/templates/migrate-job.yaml – Stand Ende Tag 10
# Hook: läuft nach install und vor jedem upgrade; der alte Job wird vorher gelöscht.
apiVersion: batch/v1
kind: Job
metadata:
  name: migrate
  labels:
    {{- include "notes.labels" (dict "ctx" $ "name" "migrate") | nindent 4 }}
  annotations:
    helm.sh/hook: post-install,pre-upgrade
    helm.sh/hook-weight: "0"
    helm.sh/hook-delete-policy: before-hook-creation
spec:
  backoffLimit: 4
  # …
  • post-install: nach dem ersten Anlegen aller Objekte. pre-upgrade: vor jedem Upgrade, also bevor neue api-Pods mit neuem Schema-Bedarf starten.
  • before-hook-creation löscht den Job vom letzten Lauf, bevor Helm ihn neu anlegt – die Lösung für den unveränderlichen Job aus Tag 8. ttlSecondsAfterFinished fällt weg, der Job bleibt bis zum nächsten Lauf zum Nachlesen stehen.
  • Hooks gehören nicht zum Manifest des Release: helm uninstall lässt einen Hook-Job stehen, wenn keine Delete-Policy greift.

Dazu ein Test-Pod, den helm test startet, und die Notiz nach der Installation:

cp "$C"/templates/migrate-job.yaml "$C"/templates/NOTES.txt chart/notes/templates/
cp "$C"/templates/tests/test-api.yaml chart/notes/templates/tests/
cat chart/notes/templates/NOTES.txt
helm template notes chart/notes -s templates/tests/test-api.yaml \
  | grep -E -A2 'hook|curl -fsS'
helm template notes chart/notes -s templates/tests/test-api.yaml \
  | sed -n '/^spec:/,/^  containers:/p'

Erwartet:

notes {{ .Chart.AppVersion }} ist im Namespace {{ .Release.Namespace }} installiert.
{{- if eq .Values.web.service.type "NodePort" }}
Weboberfläche: http://localhost:{{ .Values.web.service.nodePort }}
{{- end }}
Test: helm test {{ .Release.Name }} -n {{ .Release.Namespace }}
    helm.sh/hook: test
    helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded
spec:
  serviceAccountName: notes
--
        - curl -fsS http://api:8080/healthz && curl -fsS http://web:3000/healthz
      resources:
        requests: {cpu: 10m, memory: 16Mi}
spec:
  serviceAccountName: notes
  securityContext:
    runAsNonRoot: true
    runAsUser: 100
    runAsGroup: 100
    seccompProfile:
      type: RuntimeDefault
  restartPolicy: Never
  containers:

Der Test prüft beide Dienste von innen. curlimages/curl hat USER curl_user – ein Name, also dieselbe Falle wie bei web an Tag 8; darum uid 100.

Fortschritt speichern? Kostenlos registrieren

Drill 6: Values prüfen mit values.schema.json

cp "$C"/values.schema.json "$C"/.helmignore chart/notes/
cat chart/notes/.helmignore
grep -A8 '"web": {' chart/notes/values.schema.json
helm template notes chart/notes --set api.replicas=0
helm template notes chart/notes --set web.service.type=LoadBalancer \
  --set db.storage=1G
helm lint chart/notes --set worker.interval=zehn | head -3

Erwartet (gekürzt):

# .helmignore – nicht ins Chart-Paket
.DS_Store
*.tgz
values-*.yaml
    "web": {
      "type": "object",
      "properties": {
        "replicas": {"type": "integer", "minimum": 1},
        "service": {
          "type": "object",
          "properties": {
            "type": {"enum": ["ClusterIP", "NodePort"]},
            "nodePort": {"type": "integer", "minimum": 30000, "maximum": 32767}
Error: values don't meet the specifications of the schema(s) in the following chart(s):
notes:
- at '/api/replicas': minimum: got 0, want 1
Error: values don't meet the specifications of the schema(s) in the following chart(s):
notes:
- at '/web/service/type': value must be one of 'ClusterIP', 'NodePort'
- at '/db/storage': '1G' does not match pattern '^[0-9]+(Mi|Gi)$'
==> Linting chart/notes
[INFO] Chart.yaml: icon is recommended
[ERROR] values.yaml: - at '/worker/interval': got string, want integer
Error: 1 chart(s) linted, 1 chart(s) failed

Helm prüft das Schema bei lint, template, install und upgrade – bevor irgendetwas das Cluster erreicht. 1G wäre für Kubernetes gültig (Gigabyte statt Gibibyte), das Schema erzwingt hier die Schreibweise des Buchs. .helmignore hält Dateien aus dem Chart-Paket fern, etwa deine eigenen values-*.yaml.

Zum Schluss die Probe gegen den API-Server:

helm lint chart/notes
helm template notes chart/notes -n notes | kubectl apply --dry-run=server -f -

Erwartet:

==> Linting chart/notes
[INFO] Chart.yaml: icon is recommended

1 chart(s) linted, 0 chart(s) failed
configmap/notes-config configured (server dry run)
service/api configured (server dry run)
service/db configured (server dry run)
service/web configured (server dry run)
deployment.apps/api configured (server dry run)
deployment.apps/web configured (server dry run)
deployment.apps/worker configured (server dry run)
statefulset.apps/db configured (server dry run)
pod/notes-test-api created (server dry run)
job.batch/migrate created (server dry run)

Liegt der Job migrate aus Tag 8 noch im Cluster (TTL 600 s), endet die Ausgabe mit The Job "migrate" is invalid: … field is immutable – harmlos: helm template rendert den Hook wie ein normales Objekt, Helm selbst löscht ihn vorher per before-hook-creation.

Fortschritt speichern? Kostenlos registrieren

Drill 7: Umstieg – von kubectl apply zu Helm

Erst der naive Versuch:

curl -s localhost:30080/api/notes | jq -r '.[].text'
helm install notes chart/notes -n notes

Erwartet (gekürzt, die Notizen hängen davon ab, was du angelegt hast):

Postgres eins
Postgres zwei
Postgres drei
Kontrollpunkt 8
Error: INSTALLATION FAILED: unable to continue with install: ConfigMap "notes-config"
in namespace "notes" exists and cannot be imported into the current release: invalid
ownership metadata; label validation error: missing key
"app.kubernetes.io/managed-by": must be set to "Helm"; annotation validation error: …

Helm übernimmt keine Objekte, die es nicht selbst angelegt hat. Also: die App-Objekte löschen, Plattform und Daten behalten. Die Datenbank ist dabei kurz weg.

cd k8s && kubectl delete --ignore-not-found -f api.yaml -f web.yaml \
  -f worker.yaml -f db.yaml -f migrate.yaml -f config.yaml && cd ..
kubectl wait --for=delete pod --all --timeout 90s >/dev/null
kubectl get pvc,secret,sa
rm k8s/{api,web,worker,db,migrate,config}.yaml && ls k8s

Erwartet (gekürzt, Namen, IPs und Zeiten weichen bei dir ab):

deployment.apps "api" deleted from notes namespace
service "api" deleted from notes namespace
deployment.apps "web" deleted from notes namespace
service "web" deleted from notes namespace
deployment.apps "worker" deleted from notes namespace
service "db" deleted from notes namespace
statefulset.apps "db" deleted from notes namespace
configmap "notes-config" deleted from notes namespace
NAME                              STATUS   VOLUME        CAPACITY   ACCESS MODES   …
persistentvolumeclaim/data-db-0   Bound    pvc-4464ba68…   1Gi        RWO            …
NAME               TYPE     DATA   AGE
secret/notes-api   Opaque   1      21m
secret/notes-db    Opaque   2      21m
NAME                     AGE
serviceaccount/default   21m
serviceaccount/notes     16m
namespace.yaml
secrets.sh

Der PVC überlebt wie an Tag 7 (Drill 7). --ignore-not-found fängt den Job migrate ab, falls ihn der TTL-Controller schon entfernt hat. Jetzt das Chart:

helm install notes chart/notes -n notes --wait
kubectl get pods,jobs
curl -s localhost:30080/api/notes | jq -r '.[].text'

Erwartet (gekürzt):

NAME: notes
LAST DEPLOYED: Fri Oct 30 14:53:22 2026
NAMESPACE: notes
STATUS: deployed
REVISION: 1
DESCRIPTION: Install complete
NOTES:
notes 0.2.0 ist im Namespace notes installiert.
Weboberfläche: http://localhost:30080
Test: helm test notes -n notes
NAME                        READY   STATUS      RESTARTS      AGE
pod/api-86c7f84667-gpcwg    1/1     Running     0             15s
pod/api-86c7f84667-ljbg8    1/1     Running     0             15s
pod/api-86c7f84667-snvqt    1/1     Running     1 (11s ago)   15s
pod/db-0                    1/1     Running     0             15s
pod/migrate-9kq6k           0/1     Completed   0             5s
pod/web-6c667549-6rtvp      1/1     Running     0             15s
pod/web-6c667549-tslrz      1/1     Running     0             15s
pod/worker-784866df-gr97p   1/1     Running     0             15s
NAME                STATUS     COMPLETIONS   DURATION   AGE
job.batch/migrate   Complete   1/1           4s         5s
Postgres eins
Postgres zwei
Postgres drei
Kontrollpunkt 8

Rund 15 s, und die Notizen sind wieder da: Das neue StatefulSet db heißt wie das alte, sein Pod db-0 fordert data-db-0 an – und den gibt es schon. Ein api-Pod war schneller als die Datenbank und wurde einmal neu gestartet (Tag 7). Der Hook lief nach den anderen Objekten (post-install, mit --wait erst, als sie bereit waren).

Tipp: Helm 4 kennt --take-ownership, um vorhandene Objekte zu übernehmen. Für den Umstieg ist der saubere Schnitt hier einfacher nachzuvollziehen – und der unveränderliche Job hätte ohnehin im Weg gestanden.

Jetzt der Test:

helm test notes -n notes --logs

Erwartet (gekürzt):

NAME: notes
…
TEST SUITE:     notes-test-api
Last Started:   Fri Oct 30 14:53:45 2026
Last Completed: Fri Oct 30 14:53:53 2026
Phase:          Succeeded

POD LOGS: notes-test-api (curl)
ok
ok

Warum bleibt der Plattform-Teil bei kubectl? Helm installiert in einen Namespace, der vorher existieren muss – samt PSA-Labels, Quota und ServiceAccount, die für alle Releases darin gelten. Ein helm uninstall darf nie den Namespace, die Quota oder die Secrets mitnehmen. Und Secrets gehören nicht in Values, die Helm im Release-Secret aufhebt. Im Betrieb ist der Plattform-Teil Aufgabe des Cluster-Teams.

Fortschritt speichern? Kostenlos registrieren

Drill 8: Upgrade, Hook und Rollback

helm upgrade notes chart/notes -n notes --set api.image.tag=0.1.0 --wait \
  | grep -E '^(STATUS|REVISION)'
kubectl get deploy -o wide | cut -c1-88
kubectl exec deploy/web -- wget -qO- http://api:8080/version; echo
kubectl get job migrate \
  -o 'custom-columns=NAME:.metadata.name,IMAGE:.spec.template.spec.containers[0].image'

Erwartet (gekürzt):

STATUS: deployed
REVISION: 2
NAME     READY   UP-TO-DATE   AVAILABLE   AGE   CONTAINERS   IMAGES               SELEC…
api      3/3     3            3           92s   api          notes-api:0.1.0      app.k…
web      2/2     2            2           92s   web          notes-web:0.1.0      app.k…
worker   1/1     1            1           92s   worker       notes-worker:0.1.0   app.k…
0.1.0
NAME      IMAGE
migrate   notes-api:0.1.0

Der Hook nimmt dasselbe Image wie api – Migration und Code passen zusammen. Zurück:

helm rollback notes 1 -n notes --wait
kubectl exec deploy/web -- wget -qO- http://api:8080/version; echo
kubectl get job migrate \
  -o 'custom-columns=NAME:.metadata.name,IMAGE:.spec.template.spec.containers[0].image'
helm history notes -n notes

Erwartet (gekürzt):

Rollback was a success! Happy Helming!
0.2.0
NAME      IMAGE
migrate   notes-api:0.1.0
REVISION UPDATED                  STATUS     CHART          APP VERSION DESCRIPTION
1        Fri Oct 30 14:53:22 2026 superseded notes-0.1.0    0.2.0       Install complete
2        Fri Oct 30 14:54:33 2026 superseded notes-0.1.0    0.2.0       Upgrade complete
3        Fri Oct 30 14:55:04 2026 deployed   notes-0.1.0    0.2.0       Rollback to 1

Der Job zeigt noch 0.1.0: Ein Rollback startet pre-upgrade-Hooks nicht (dafür gäbe es pre-rollback). Das ist richtig so – eine Migration läuft nur vorwärts; ein Schema-Rückbau wäre eine eigene, bewusste Migration.

Dass der Hook vor den neuen Pods läuft, siehst du an einer Änderung, die worker neu startet:

helm upgrade notes chart/notes -n notes --set worker.interval=20 --wait \
  | grep REVISION
kubectl get job migrate \
  -o jsonpath='Job migrate: {.status.startTime} bis {.status.completionTime}{"\n"}'
kubectl get pods -l app.kubernetes.io/name=worker -o jsonpath=\
'{range .items[*]}Pod {.metadata.name}: {.metadata.creationTimestamp}{"\n"}{end}'

Erwartet (gekürzt):

REVISION: 4
Job migrate: 2026-10-30T14:55:28Z bis 2026-10-30T14:55:32Z
Pod worker-6b5455b8cb-w6x7z: 2026-10-30T14:55:33Z
Pod worker-784866df-gr97p: 2026-10-30T14:53:24Z

Erst die Migration, dann der neue worker-Pod (der alte beendet sich gerade). Neu gestartet hat ihn die checksum/config-Annotation. Jetzt wieder auf die Werte des Charts – und denk an die Falle aus Tag 9:

helm upgrade notes chart/notes -n notes --wait | grep REVISION
helm get values notes -n notes
helm upgrade notes chart/notes -n notes --reset-values --wait | grep REVISION
helm get values notes -n notes

Erwartet:

REVISION: 5
USER-SUPPLIED VALUES:
worker:
  interval: 20
REVISION: 6
USER-SUPPLIED VALUES:
null

Ohne --set/-f übernimmt Helm die alten Values; erst --reset-values kehrt zu values.yaml zurück.

Fortschritt speichern? Kostenlos registrieren

Kontrollpunkt

helm template notes chart/notes --set api.replicas=0

Erwartet: Das Schema lehnt 0 Repliken ab.

Error: values don't meet the specifications of the schema(s) in the following chart(s):
notes:
- at '/api/replicas': minimum: got 0, want 1
ls k8s

Erwartet: Im Ordner k8s bleibt nur der Plattform-Teil.

namespace.yaml
secrets.sh
helm list

Erwartet: Release notes mit Chart notes-0.1.0, deployed.

NAME    NAMESPACE   REVISION   UPDATED   STATUS     CHART         APP VERSION
notes   notes       1          2026-…    deployed   notes-0.1.0   0.2.0
helm test notes

Erwartet: Der Test-Pod erreicht die api, Phase: Succeeded.

NAME: notes
…
TEST SUITE:     notes-test-api
Last Started:   …
Last Completed: …
Phase:          Succeeded
curl -s localhost:30080/api/notes

Erwartet: die Notizen aus der Zeit vor Helm (Inhalt weicht ab), der PVC wurde übernommen.

[{"id":"c74b85b6-…","text":"bleibt in Postgres"}]

Challenge

Leg eine Datei chart/notes/values-klein.yaml an, mit der notes auf einem schwachen Notebook mit je einer api- und web-Replik läuft. Spiel sie ein, beweise, dass sie nicht im Chart-Paket landet, und kehr zu den Standardwerten zurück.

Hinweis: helm package baut das .tgz, tar -tzf listet den Inhalt.

Lösung

cat > chart/notes/values-klein.yaml <<'EOF'
# values-klein.yaml – Challenge Tag 10: sparsame Variante fürs Notebook
api:
  replicas: 1
web:
  replicas: 1
EOF
helm upgrade notes chart/notes -n notes -f chart/notes/values-klein.yaml --wait \
  | grep REVISION
kubectl get deploy
helm package chart/notes -d /tmp/pkg
tar -tzf /tmp/pkg/notes-0.1.0.tgz | grep -c values-klein
rm -rf /tmp/pkg
helm upgrade notes chart/notes -n notes --reset-values --wait | grep REVISION
kubectl get deploy api web
rm chart/notes/values-klein.yaml

Erwartet (gekürzt):

REVISION: 7
NAME     READY   UP-TO-DATE   AVAILABLE   AGE
api      1/1     1            1           3m11s
web      1/1     1            1           3m11s
worker   1/1     1            1           3m11s
Successfully packaged chart and saved it to: /tmp/pkg/notes-0.1.0.tgz
0
REVISION: 8
NAME   READY   UP-TO-DATE   AVAILABLE   AGE
api    3/3     3            3           3m23s
web    2/2     2            2           3m23s

Der Eintrag values-*.yaml in .helmignore hält die Datei aus dem Paket. Umgebungs-Values gehören zur Umgebung, nicht ins Chart – im Paket stehen nur values.yaml und values.schema.json.

Fortschritt speichern? Kostenlos registrieren

Enterprise-Notiz

  • Echte Charts präfixen Objektnamen mit dem Release-Namen ({{ .Release.Name }}-api), damit mehrere Releases in einem Namespace laufen können. Hier sind die Namen fest, damit der PVC data-db-0 beim Umstieg erhalten bleibt – ein Release pro Namespace.
  • Charts versionieren (SemVer in Chart.yaml), per helm package und helm push in eine OCI-Registry legen und in CI mit helm lint, helm template | kubeconform und helm test in einem Wegwerf-Cluster prüfen.
  • Datenbank-Migrationen als Hook sind bequem, aber riskant bei großen Tabellen: Timeout (--timeout) bewusst setzen, Migrationen rückwärtskompatibel schreiben (Expand/Contract), Backups vor jedem Upgrade.
  • Postgres im eigenen Chart ist fürs Lernen gut. Im Betrieb übernimmt ein Operator (z. B. CloudNativePG) Backups, Failover und Upgrades – siehe „Kubernetes-Operatoren zum Anfassen”.
  • Secrets kommen aus einem Secret-Store (External Secrets, OpenBao) statt aus einem Skript – siehe „OpenBao-Secrets zum Anfassen”.