Einstieg
kubectl-Grundlagen
kubectl ist die CLI für Kubernetes. get listet Ressourcen auf, create legt neue an, expose erzeugt Services, scale ändert die Replika-Zahl. describe liefert detaillierte Infos zu einer Ressource.
# cluster info
kubectl cluster-info
# list nodes
kubectl get nodes
# list pods (all namespaces)
kubectl get pods --all-namespaces
# create a deployment
kubectl create deployment nginx --image=nginx
# expose deployment as service
kubectl expose deployment nginx --port=80 --type=LoadBalancer
# scale deployment
kubectl scale deployment nginx --replicas=3
# get detailed info
kubectl describe pod <pod-name>
# view logs
kubectl logs <pod-name>Ausgabeformatierung
Der -o-Flag steuert die Ausgabe. yaml/json zeigen die vollständige Ressourcen-Spezifikation. jsonpath und custom-columns extrahieren einzelne Felder für Skripte. -w beobachtet Änderungen live. In Skripten --no-headers verwenden, um Spaltennamen zu unterdrücken.
# wide format (more columns)
kubectl get pods -o wide
# YAML output
kubectl get pod nginx -o yaml
# JSON output
kubectl get pod nginx -o json
# jsonpath (extract specific fields)
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
# custom columns
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase
# show labels
kubectl get pods --show-labels
# watch for changes
kubectl get pods -wKontext & Konfiguration
Ein Kontext bündelt Cluster-Adresse, Zugangsdaten und Namespace. kubeconfig-Dateien (Standard: ~/.kube/config) speichern diese. Mehrere Dateien lassen sich über die Umgebungsvariable KUBECONFIG kombinieren, um viele Cluster zu verwalten.
# view current config
kubectl config view
# list contexts
kubectl config get-contexts
# switch context
kubectl config use-context my-cluster
# set default namespace for current context
kubectl config set-context --current --namespace=dev
# show current context
kubectl config current-context
# KUBECONFIG with multiple files
export KUBECONFIG=~/.kube/config:~/.kube/prod-configExplain & API-Ressourcen
api-resources listet, was der Cluster unterstützt. explain zeigt das OpenAPI-Schema zu jeder Ressource — unbezahlbar, um YAML zu schreiben, ohne das Terminal zu verlassen. Mit --recursive die vollständige verschachtelte Struktur ausgeben.
# list all resource types
kubectl api-resources
# list namespaced vs cluster-scoped
kubectl api-resources --namespaced=true
kubectl api-resources --namespaced=false
# explain a resource's fields
kubectl explain pod
kubectl explain pod.spec.containers
kubectl explain deployment.spec.strategy
# explain with recursion (all nested fields)
kubectl explain pod --recursive
# include description
kubectl explain pod.spec.containers.resources --api-version=apps/v1Dry Run & YAML generieren
--dry-run=client -o yaml ist der Standardweg, um Manifeste aus imperativen Befehlen zu erzeugen. --dry-run=server validiert gegen den echten apiserver (Admission-Webhooks, Schema), ohne zu persistieren. Ideal, um deklaratives YAML zu bootstrappen.
# generate YAML without applying
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml
# pipe generated YAML straight to a file
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > nginx.yaml
# apply the generated manifest
kubectl apply -f nginx.yaml
# dry-run against the server (validates with apiserver)
kubectl apply -f nginx.yaml --dry-run=server
# generate a service from a deployment
kubectl create service clusterip my-svc --tcp=80:80 --dry-run=client -o yamlHilfe & Autocomplete
Jeder kubectl-Befehl unterstützt --help mit Beispielen. Shell-Completion spart enormes Tippen und zeigt Subcommands. Der Alias k=kubectl ist unter Praktikern nahezu universell — zusammen mit Completion das beste Erlebnis.
# top-level help
kubectl --help
# subcommand help
kubectl create --help
kubectl explain --help
# generate bash completion
kubectl completion bash > /etc/bash_completion.d/kubectl
# zsh completion
source <(kubectl completion zsh)
# alias k=kubectl with completion
alias k=kubectl
complete -o default -F __start_kubectl k
# shorthand: kubectl -> k
echo 'alias k=kubectl' >> ~/.bashrcPod
Pod-Manifest
Ein Pod ist die kleinste deploybare Einheit und enthält einen oder mehrere Container, die Netzwerk und Storage teilen. Container in einem Pod werden immer auf demselben Knoten co-scheduled. Pods legt man selten direkt an — stattdessen einen Deployment oder Job verwenden.
apiVersion: v1
kind: Pod
metadata:
name: nginx
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.25
ports:
- containerPort: 80
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 200m
memory: 256Mi
restartPolicy: AlwaysMulti-Container-Pod (Sidecar)
Multi-Container-Pods teilen Netzwerk (gleiche IP, gleicher Port-Bereich) und Volumes. Häufige Muster: sidecar (Helfer), adapter (wandelt Ausgabe um), ambassador (Proxy). Das gemeinsame emptyDir-Volume lässt den Sidecar die Logs des Hauptcontainers lesen.
apiVersion: v1
kind: Pod
metadata:
name: web-with-logs
spec:
containers:
- name: app
image: nginx
volumeMounts:
- name: shared-logs
mountPath: /var/log/nginx
- name: log-shipper
image: busybox
command: ["sh", "-c", "tail -f /var/log/nginx/access.log"]
volumeMounts:
- name: shared-logs
mountPath: /var/log/nginx
readOnly: true
volumes:
- name: shared-logs
emptyDir: {}Pod-Lebenszyklus & Phasen
Die Phase eines Pods ist grob (Pending, Running, Succeeded, Failed). Container-States (Waiting/Running/Terminated) liefern die echten Details — z. B. bedeutet CrashLoopBackOff, dass der Container immer wieder beendet wird. Restart-Zähler und Events zur Diagnose heranziehen.
# pod phases: Pending | Running | Succeeded | Failed | Unknown
kubectl get pod nginx
# show status including container states
kubectl get pod nginx -o jsonpath='{.status}'
# container states: Waiting | Running | Terminated
kubectl describe pod nginx
# common Waiting reasons: ImagePullBackOff, CrashLoopBackOff, CreateContainerConfigError
kubectl get pods --field-selector=status.phase=Pending
# restart count reveals crash loops
kubectl get pods -o jsonpath='{.items[*].status.containerStatuses[*].restartCount}'Pod-Status & Events
Events sind das Audit-Log des Clusters für eine Ressource — Scheduling, Image-Pulls, Pull-Fehler, Liveness-Failures. Sie laufen ab (standardmäßig ~1 Stunde), also beim Debuggen mitprotokollieren. describe bündelt Events mit der Ressourcen-Spezifikation für schnelle Triage.
# full describe (includes Events at the bottom)
kubectl describe pod nginx
# list cluster events sorted by time
kubectl get events --sort-by=.lastTimestamp
# events for a specific namespace
kubectl get events -n default
# watch events live
kubectl get events -w
# filter events by type
kubectl get events --field-selector type=Warning
# events for a specific pod
kubectl get events --field-selector involvedObject.name=nginxExec & Port-Forward
exec führt Befehle in einem Container aus; -it reserviert eine TTY für Shells. port-forward tunnelt einen lokalen Port zu einem Pod/Service, ohne ihn öffentlich zu exponieren — unverzichtbar, um Datenbanken oder Web-UIs vom Laptop aus zu debuggen.
# open an interactive shell
kubectl exec -it nginx -- sh
# run a one-off command
kubectl exec nginx -- ls /etc/nginx
# specify container in a multi-container pod
kubectl exec -it web-with-logs -c log-shipper -- sh
# forward a local port to a pod port
kubectl port-forward pod/nginx 8080:80
# forward to a service / deployment
kubectl port-forward svc/nginx 8080:80
kubectl port-forward deployment/nginx 8080:80
# forward to a random local port
kubectl port-forward pod/nginx :80Löschen & Erzwingen
Löscht man einen Pod, der von einem Deployment/StatefulSet kontrolliert wird, folgt sofort ein Ersatz. --force --grace-period=0 überspringt die TERM-Grace-Period und kann verwaiste Ressourcen hinterlassen — sparsam einsetzen. Hängende Terminating-Pods brauchen oft das Entfernen eines Finalizers.
# delete a pod (controller will recreate it)
kubectl delete pod nginx
# force delete immediately (bypasses graceful shutdown)
kubectl delete pod nginx --grace-period=0 --force
# delete by label
kubectl delete pods -l app=nginx
# delete all pods in a namespace
kubectl delete pods --all -n default
# delete a pod and wait for it to be gone
kubectl delete pod nginx --wait
# delete with a timeout
kubectl delete pod nginx --timeout=30sDeployment
Deployment-Manifest
Ein Deployment verwaltet ReplicaSets und bietet deklarative Rolling-Updates und Rollbacks. spec.selector muss spec.template.metadata.labels entsprechen. Das Template definiert die Pod-Spezifikation, die ausgerollt wird.
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.25
ports:
- containerPort: 80Rolling-Update-Strategie
RollingUpdate (Standard) ersetzt Pods schrittweise für null Downtime. maxSurge/maxUnavailable steuern Rollout-Tempo und Verfügbarkeit. Recreate killt alle Pods, bevor neue entstehen — wenn die App nicht zwei Versionen gleichzeitig laufen lassen kann (z. B. ein einzelner Volume-Writer).
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
replicas: 10
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 25% # extra pods above replicas during update
maxUnavailable: 25% # pods allowed down during update
# alternative: recreate (kills all, then starts new)
# strategy:
# type: Recreate
selector:
matchLabels:
app: nginx
template:Rollback
Jede Änderung am Pod-Template erzeugt eine ReplicaSet-Revision. undo schaltet den Traffic zurück auf ein früheres ReplicaSet. pause erlaubt mehrere Fixes zwischen Canary-Schritten. --record (deprecated) oder Annotations verwenden, um Änderungsurschen nachzuverfolgen.
# view rollout history
kubectl rollout history deployment/nginx
# see details of a specific revision
kubectl rollout history deployment/nginx --revision=2
# undo to the previous revision
kubectl rollout undo deployment/nginx
# undo to a specific revision
kubectl rollout undo deployment/nginx --to-revision=2
# pause/resume a rollout (for canary pauses)
kubectl rollout pause deployment/nginx
kubectl rollout resume deployment/nginx
# check rollout status
kubectl rollout status deployment/nginxScale & HPA
HPA skaliert Replikas anhand von CPU/Memory oder eigenen Metriken. Für CPU/Mem braucht er metrics-server. minReplicas und maxReplicas begrenzen die Skalierung. Die v2-API unterstützt mehrere Metriken und Verhaltensregeln (stabilisiertes Runterskalieren).
# scale manually
kubectl scale deployment/nginx --replicas=5
# horizontal pod autoscaler (CPU target)
kubectl autoscale deployment nginx --min=2 --max=10 --cpu-percent=80
# list HPA
kubectl get hpa
# HPA manifest (v2 with custom metrics)
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: nginx
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: nginx
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 80Image aktualisieren & Neustart
set image triggert ein neues ReplicaSet und ein Rolling-Update. rollout restart ist der sauberste Weg, das neueste Image zu laden oder die Konfiguration zu aktualisieren — es erzeugt ein neues ReplicaSet mit derselben Spezifikation. edit öffnet den $EDITOR für Ad-hoc-Fixes.
# update container image
kubectl set image deployment/nginx nginx=nginx:1.26
# update from a specific container
kubectl set image deployment/nginx container=nginx:1.26 --record
# trigger a rollout restart (same image, recreate pods)
kubectl rollout restart deployment/nginx
# edit a deployment in editor
kubectl edit deployment/nginx
# patch a single field
kubectl patch deployment/nginx -p '{"spec":{"replicas":5}}'
# apply a manifest change
kubectl apply -f nginx-deployment.yamlDeployment-Status
Ein Deployment besitzt ReplicaSets; nur eines ist aktiv (replicas>0). Alte ReplicaSets skalieren für Rollbacks auf null. pod-template-hash markiert jeden Pod mit seiner Revision. status.conditions auf Available, Progressing und ReplicaFailure prüfen.
# deployment status
kubectl get deployment nginx
# watch rollout
kubectl rollout status deployment/nginx
# show ReplicaSets owned by the deployment
kubectl get rs -l app=nginx
# show pods across all revisions
kubectl get pods -l app=nginx --show-labels
# pod-template-hash label distinguishes revisions
# kubectl get pods -l app=nginx,pod-template-hash=xxxx
# conditions: Available, Progressing, ReplicaFailure
kubectl get deployment nginx -o jsonpath='{.status.conditions}'Service
Service-Typen
Ein Service stellt eine stabile IP/DNS bereit, die über eine Gruppe von Pods lastverteilt. ClusterIP ist der Standard (nur im Cluster). NodePort und LoadBalancer exponieren nach außen. ExternalName ist ein DNS-Alias, kein Proxy.
# four service types:
# - ClusterIP (default): reachable inside the cluster
# - NodePort: exposed on each node's IP at a static port
# - LoadBalancer: cloud-provisioned external LB
# - ExternalName: DNS CNAME to an external host
# quick create
kubectl expose deployment nginx --port=80 --type=ClusterIP
kubectl expose deployment nginx --port=80 --type=NodePort
kubectl expose deployment nginx --port=80 --type=LoadBalancer
# external name (no proxying, pure DNS)
kubectl create service externalname my-svc --external-name=db.example.comClusterIP-Service
ClusterIP liefert eine stabile virtuelle IP und einen DNS-Namen innerhalb des Clusters. Der Selektor matcht Pod-Labels; kube-proxy programmiert iptables/IPVS zur Lastverteilung über die Endpoints. Auflösung über <svc>.<ns>.svc.cluster.local oder einfach <svc>.
apiVersion: v1
kind: Service
metadata:
name: nginx
spec:
type: ClusterIP
selector:
app: nginx
ports:
- name: http
port: 80 # service port
targetPort: 80 # container port
protocol: TCP
# DNS: nginx.default.svc.cluster.local
# short names also work: nginx, nginx.default
# kube-dns / CoreDNS resolves the service VIPNodePort-Service
NodePort öffnet denselben statischen Port (30000-32767) auf jedem Knoten. Traffic an knoten:nodePort erreicht einen Pod (kube-proxy leitet ggf. zu einem Pod auf anderem Knoten weiter). Nützlich, wenn man keine Cloud-LB bereitstellen kann; mit einem externen LB für HA kombinieren.
apiVersion: v1
kind: Service
metadata:
name: nginx
spec:
type: NodePort
selector:
app: nginx
ports:
- port: 80
targetPort: 80
nodePort: 30080 # optional, 30000-32767 range
# reachable at <any-node-ip>:30080
# also still reachable via clusterIP:80
# get assigned nodePort
kubectl get svc nginx -o jsonpath='{.spec.ports[*].nodePort}'LoadBalancer-Service
LoadBalancer lässt den Cloud-Provider einen externen Load Balancer bereitstellen, der auf die Knoten zeigt. externalTrafficPolicy: Local erhält die Client-Quell-IP (kein SNAT), verzichtet aber auf Knoten-übergreifende Lastverteilung. STATUS zeigt die zugewiesene externe IP, sobald alles bereit ist.
apiVersion: v1
kind: Service
metadata:
name: nginx
spec:
type: LoadBalancer
selector:
app: nginx
ports:
- port: 80
targetPort: 80
# cloud-specific annotations
# annotations:
# service.beta.kubernetes.io/aws-load-balancer-type: nlb
# service.beta.kubernetes.io/azure-load-balancer-internal: "true"
# externalTrafficPolicy: Local preserves client IP
externalTrafficPolicy: Local
# status.ingress shows the external IP/hostnameHeadless-Service
Ein headless service (clusterIP: None) hat keine VIP — DNS liefert direkt die Pod-IPs. Vom StatefulSet benötigt, damit jeder Pod einen stabilen DNS-Namen bekommt (pod-0.svc, pod-1.svc). Auch von Clients genutzt, die alle Backends selbst entdecken wollen.
apiVersion: v1
kind: Service
metadata:
name: nginx-headless
spec:
clusterIP: None # makes it headless
selector:
app: nginx
ports:
- port: 80
targetPort: 80
# DNS returns pod IPs directly (not a VIP)
# A records: nginx-headless.default.svc.cluster.local
# -> 10.1.0.5, 10.1.0.6, 10.1.0.7
# used by StatefulSet for stable pod DNS:
# <pod-name>.<svc-name>.default.svc.cluster.localEndpoints & EndpointSlices
Endpoints/EndpointSlices listen die Pod-IPs, die tatsächlich Traffic empfangen — nur Ready-Pods erscheinen. Hat ein Service keine Endpoints, matchen die Pods den Selektor nicht oder sind nicht Ready. EndpointSlices (v1) skalieren bei riesigen Services besser und sind der Standard.
# view endpoints backing a service
kubectl get endpoints nginx
# endpoint slices (newer, more scalable)
kubectl get endpointslices -l kubernetes.io/service-name=nginx
# endpoints track pods that match the selector
# AND pass readiness checks
kubectl describe endpoints nginx
# a service with no ready pods has no endpoints
# - check pod readiness if traffic is refused
# - EndpointSlices are grouped by address type (IPv4/IPv6)
# manually managed endpoints (selector-less service)ConfigMap
ConfigMap anlegen
ConfigMaps speichern nicht-sensible Konfiguration als Key-Value-Paare. --from-literal für Inline-Werte, --from-file für ganze Dateien (der Dateiname wird zum Key). Nützlich, um Konfiguration vom Image zu entkoppeln, ohne neu zu bauen.
# from literal values
kubectl create configmap app-config \
--from-literal=LOG_LEVEL=debug \
--from-literal=ENABLE_FEATURE=true
# from a file (key = filename, value = contents)
kubectl create configmap app-config --from-file=app.properties
# from a directory (one key per file)
kubectl create configmap app-config --from-file=configs/
# from an env file
kubectl create configmap app-config --from-env-file=app.env
# from a file with a custom key
kubectl create configmap app-config --from-file=custom-key=app.propertiesConfigMap-Manifest
data enthält String-Werte (jeder Key wird beim Mounten zu einer Env-Variablen oder einer Datei). Mehrzeilige Strings nutzen YAML-Block-Scalars (|). binaryData akzeptiert base64 für binäre Blobs. Gesamtgröße: maximal 1 MiB pro ConfigMap.
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
LOG_LEVEL: "debug"
ENABLE_FEATURE: "true"
application.yml: |
server:
port: 8080
logging:
level: debug
binaryData:
# base64-encoded binary values
logo.png: iVBORw0KGgoAAAANSUhEUg...Als Umgebungsvariablen nutzen
envFrom injiziert jeden ConfigMap-Key auf einen Schlag als Env-Variable. env mit configMapKeyRef wählt einzelne Keys. optional: true lässt den Pod starten, selbst wenn die ConfigMap fehlt. Updates der ConfigMap aktualisieren die Env-Variablen laufender Pods NICHT.
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
containers:
- name: app
image: myapp:1.0
env:
- name: LOG_LEVEL
valueFrom:
configMapKeyRef:
name: app-config
key: LOG_LEVEL
envFrom:
- configMapRef:
name: app-config # injects all keys as env vars
optional: true # pod starts even if CM missingAls Volume nutzen
Mountet man eine ConfigMap als Volume, projiziert jeder Key als Datei. Updates der ConfigMap finden zeitversetzt in die gemounteten Dateien (gesteuert von der kubelet-Sync-Periode) — die App muss sie aber neu lesen. subPath-Mounts pinnen einen einzelnen Key und aktualisieren NICHT.
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
containers:
- name: app
image: myapp:1.0
volumeMounts:
- name: config
mountPath: /etc/config
readOnly: true
volumes:
- name: config
configMap:
name: app-config
items: # optional: pick subset
- key: application.yml
path: app.yml # rename file
defaultMode: 0644
# each ConfigMap key becomes a file under /etc/configUpdate & Reload
Gemountete ConfigMap-Dateien aktualisieren sich automatisch (nach dem kubelet-Sync), aber Env-Variablen sind für die Lebensdauer des Pods unveränderlich — Pods neu starten, um Env-Änderungen zu übernehmen. rollout restart ist der sauberste Weg, Konfigurationsupdates an ein Deployment zu verteilen.
# edit the configmap
kubectl edit configmap app-config
# patch a single key
kubectl patch configmap app-config \
--type merge -p '{"data":{"LOG_LEVEL":"info"}}'
# mounted files update within ~kubelet sync period (default 60s)
# but env vars do NOT update in running pods
# force pods to pick up new config by rolling them
kubectl rollout restart deployment/app
# verify the new value on a pod
kubectl exec app -- printenv LOG_LEVELImmutable ConfigMap
immutable: true friert die ConfigMap ein — jede Änderung erfordert delete + recreate. Das reduziert den kubelet-apiserver-Watch-Traffic für große, stabile Konfigurationen drastisch (bei Scale ein echter Skalierungsgewinn). In Produktion üblich für App-Konfigurationen, die mit dem Image versioniert werden.
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
immutable: true
data:
LOG_LEVEL: "debug"
# once immutable, the only change allowed is delete + recreate
# benefits: kubelet does not watch it, lower apiserver load
# useful for large, stable configs in production
# make it mutable again
kubectl patch configmap app-config -p '{"immutable":false}'
# (this fails if currently immutable — must delete instead)Secret
Secret anlegen
Secrets speichern sensible Daten base64-kodiert (standardmäßig NICHT verschlüsselt im Ruhezustand — für Produktion Encryption at Rest aktivieren). generic/Opaque für beliebige Daten, docker-registry für Image-Pulls, tls für Ingress-TLS. Secret-YAML niemals in git committen.
# generic (opaque) from literals
kubectl create secret generic db-creds \
--from-literal=username=admin \
--from-literal=password='S3cur3!'
# from a file (e.g. SSH key, certificate)
kubectl create secret generic ssh-key --from-file=ssh-privatekey=~/.ssh/id_rsa
# docker registry secret (for private image registries)
kubectl create secret docker-registry regcred \
--docker-server=registry.example.com \
--docker-username=user \
--docker-password=pass \
[email protected]
# TLS secret from cert/key files
kubectl create secret tls my-tls \
--cert=fullchain.pem \
--key=privkey.pemSecret-Manifest
data-Werte müssen base64-kodiert sein (echo -n 'value' | base64). stringData ist eine Bequemlichkeit, die Klartext akzeptiert und beim apply in data eingemischt wird. type Opaque ist der Standard; spezialisierte Typen (kubernetes.io/tls, kubernetes.io/dockerconfigjson) validieren die Keys.
apiVersion: v1
kind: Secret
metadata:
name: db-creds
type: Opaque
data:
username: YWRtaW4= # base64 of "admin"
password: UzNjdXIzIQ== # base64 of "S3cur3!"
# stringData accepts plaintext (auto-encoded on apply)
stringData:
api-key: "live-key-xyz"
# encode on the command line:
# echo -n 'admin' | base64
# decode:
# echo 'YWRtaW4=' | base64 -dSecret als Umgebungsvariable nutzen
Secrets als Env-Variablen zu konsumieren funktioniert wie bei ConfigMaps, nur mit secretKeyRef/secretRef. Env-Variablen sind über /proc/1/environ und für jeden Prozess im Container sichtbar — für hochsensible Daten Volume-Mounts bevorzugen.
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
containers:
- name: app
image: myapp:1.0
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-creds
key: password
envFrom:
- secretRef:
name: db-creds # injects all keys
optional: trueSecret als Volume nutzen
Gemountete Secrets werden als Dateien in ein tmpfs-(Memory-)Volume projiziert — nie auf den Node-Disk geschrieben. defaultMode 0400 beschränkt den Zugriff. Gemountete Secrets AKTUALISIEREN sich, wenn sich das Secret ändert (nach dem kubelet-Sync) — anders als Env-Variablen-Secrets.
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
containers:
- name: app
image: myapp:1.0
volumeMounts:
- name: secrets
mountPath: /etc/secrets
readOnly: true
volumes:
- name: secrets
secret:
secretName: db-creds
defaultMode: 0400 # restrict permissions
items:
- key: password
path: db-password # written to /etc/secrets/db-password
# memory-backed tmpfs, never written to disk on the nodeImagePullSecret
imagePullSecrets authentifizieren gegenüber privaten Registries beim Image-Pull. An ein ServiceAccount angehängt gilt es für jeden Pod, der dieses SA nutzt — das bevorzugte Muster. Der Secret-Typ docker-registry erzeugt die richtige .dockerconfigjson-Payload automatisch.
# attach to a pod
apiVersion: v1
kind: Pod
metadata:
name: private-app
spec:
imagePullSecrets:
- name: regcred
containers:
- name: app
image: registry.example.com/myapp:1.0
# attach to a service account (auto-applied to all pods using it)
kubectl patch serviceaccount default \
-p '{"imagePullSecrets":[{"name":"regcred"}]}'
# verify
kubectl get sa default -o jsonpath='{.imagePullSecrets}'Secret-Typen
Spezialisierte Secret-Typen ermöglichen Validierung und Integration: tls für Ingress, dockerconfigjson für Image-Pulls, service-account-token wird automatisch in Pods gemountet. Der richtige Typ stellt sicher, dass die Keys validiert werden und die richtigen Controller sie konsumieren.
# Opaque (default) — arbitrary key-value
type: Opaque
# kubernetes.io/service-account-token — auto for SAs
type: kubernetes.io/service-account-token
# kubernetes.io/dockerconfigjson — registry auth
type: kubernetes.io/dockerconfigjson
data:
.dockerconfigjson: <base64>
# kubernetes.io/tls — for Ingress TLS
type: kubernetes.io/tls
data:
tls.crt: <base64>
tls.key: <base64>
# kubernetes.io/basic-auth
type: kubernetes.io/basic-auth
stringData:
username: admin
password: passNamespace
Namespace anlegen
Namespaces partitionieren einen Cluster für mehrere Teams oder Umgebungen (dev/stage/prod). Ressourcennamen müssen innerhalb eines Namespace eindeutig sein. Einige Ressourcen (Nodes, PVs, StorageClasses) sind cluster-scoped und nicht namespaced.
# imperative
kubectl create namespace dev
# declarative
apiVersion: v1
kind: Namespace
metadata:
name: dev
labels:
environment: development
team: platform
# apply
kubectl apply -f namespace.yaml
# list namespaces
kubectl get namespaces
# set default namespace for current context
kubectl config set-context --current --namespace=devResourceQuota
ResourceQuota begrenzt den aggregierten Ressourcenverbrauch in einem Namespace — Gesamt-CPU/Memory-Requests/Limits, Objektzahlen (Pods, PVCs, Services, Deployments). Unverzichtbar in Multi-Tenant-Clustern, damit ein Team den anderen nichts wegnimmt. Pods ohne explizite Requests werden abgelehnt, sobald Quota gesetzt ist.
apiVersion: v1
kind: ResourceQuota
metadata:
name: compute-quota
namespace: dev
spec:
hard:
requests.cpu: "10"
requests.memory: 20Gi
limits.cpu: "20"
limits.memory: 40Gi
pods: "50"
services.loadbalancers: "2"
persistentvolumeclaims: "10"
count/deployments.apps: "5"
# limits total aggregate resource use in the namespaceLimitRange
LimitRange setzt Default-Werte und Grenzen pro Ressource: default requests/limits für Pods, die keine angeben, plus min/max gegen absurde Werte. Passt zu ResourceQuota — ohne default requests würde das Quota jeden Pod ablehnen, der sie vergisst.
apiVersion: v1
kind: LimitRange
metadata:
name: default-limits
namespace: dev
spec:
limits:
- type: Container
default: # default limits (if unset)
cpu: 500m
memory: 512Mi
defaultRequest: # default requests (if unset)
cpu: 100m
memory: 128Mi
max: # max allowed limits
cpu: "2"
memory: 2Gi
min: # min allowed requests
cpu: 50m
memory: 64Mi
- type: PersistentVolumeClaim
max:
storage: 100Gi
min:
storage: 1GiNamespace löschen & Finalizers
Das Löschen eines Namespace kaskadiert alle seine Ressourcen. Ein Namespace, der in Terminating hängt, hat meist einen Finalizer, der nicht abschließen kann — eine nicht erreichbare APIService (z. B. metrics-server) oder eine CRD, deren Controller weg ist. Den Finalizer entfernen erzwingt den Abschluss, kann aber externe Ressourcen verlieren.
# delete a namespace (cascades all resources in it)
kubectl delete namespace dev
# if stuck in Terminating, inspect finalizers
kubectl get namespace dev -o yaml
# remove finalizer to force completion (DANGEROUS)
kubectl patch namespace dev -p '{"metadata":{"finalizers":null}}'
# resources that block deletion:
# - APIService unavailable (metrics-server removed)
# - custom resources whose CRD is gone
# - PVCs with attached PVs
# check what's still in the namespace
kubectl api-resources --verbs=list --namespaced -o name \
| xargs -n 1 kubectl get -n dev --ignore-not-foundStandard-Namespaces
kube-system betreibt Control Plane und Add-ons (DNS, kube-proxy, CNI). kube-public enthält Bootstrap-Daten, die unauthentifizierte Nutzer lesen können. kube-node-lease speichert Node-Heartbeats als Lease-Objekte für Performance. default ist das Ziel, wenn man keinen Namespace angibt.
# built-in namespaces
kubectl get namespaces
# NAME STATUS AGE
# default Active 30d <- user workloads land here
# kube-system Active 30d <- control plane / addons
# kube-public Active 30d <- publicly readable (bootstrap)
# kube-node-lease Active 30d <- node heartbeats (leases)
# kube-system holds:
# - kube-dns / CoreDNS
# - kube-proxy
# - metrics-server
# - CNI, CSI, cloud provider controllers
# kube-public is readable by all (used for cluster info discovery)Namespace-scoped vs. Cluster-scoped
Die meisten Workload-Ressourcen sind namespaced; Infrastruktur (Nodes, PVs, StorageClasses, ClusterRoles) ist cluster-scoped. Ein Service kann nur Pods im eigenen Namespace ansprechen. -A ist die Kurzfassung von --all-namespaces — essenziell für Cluster-weite Sichtbarkeit.
# which resources are namespaced?
kubectl api-resources --namespaced=true
kubectl api-resources --namespaced=false
# namespaced: pods, services, deployments, configmaps, secrets
# cluster-scoped: nodes, namespaces, PVs, StorageClasses, ClusterRoles
# access across namespaces:
# - a Service selector only matches pods in the SAME namespace
# - cross-namespace refs require special controllers (e.g. external-dns)
# list resources across all namespaces
kubectl get pods --all-namespaces
kubectl get pods -A # shorthandLabels & Selektoren
Label-Syntax
Labels sind Key-Value-Paare zum Identifizieren und Gruppieren von Ressourcen. Keys können einen optionalen Präfix tragen (DNS-Subdomain, z. B. app.kubernetes.io/). Labels dienen dem Abfragen/Filtern — anders als Annotations, die beliebige nicht-identifizierende Metadaten tragen.
# labels are key=value pairs
# key: prefix (optional DNS subdomain) + name
# value: string, up to 63 chars
metadata:
labels:
app: nginx
tier: frontend
env: prod
app.kubernetes.io/name: nginx
app.kubernetes.io/version: "1.25"
# view labels
kubectl get pods --show-labels
# add/overwrite a label
kubectl label pod nginx env=prod
kubectl label pod nginx env=staging --overwrite
# remove a label (trailing dash)
kubectl label pod nginx env-Gleichheits- & Set-Selektoren
Zwei Selektor-Arten: gleichheitsbasiert (=, ==, !=) und mengenbasiert (in, notin, exists, !exists). Mehrere kommaseparierte Bedingungen werden UND-verknüpft. Services und Deployments nutzen gleichheitsbasierte Selektoren im YAML; kubectl -l unterstützt beide.
# equality-based: = == !=
kubectl get pods -l app=nginx
kubectl get pods -l env!=dev
kubectl get pods -l 'app=nginx,env=prod' # AND of conditions
# set-based: in, notin, exists
kubectl get pods -l 'env in (prod,staging)'
kubectl get pods -l 'env notin (dev)'
kubectl get pods -l 'tier' # key exists
kubectl get pods -l '!canary' # key does not exist
# combine equality and set-based
kubectl get pods -l 'app=nginx,env in (prod,staging)'Ressourcen labeln
label verändert identifizierende Metadaten — für alles verwenden, worauf Selektoren matchen sollen. annotate ist für nicht-identifizierende Metadaten (Owner, Ticket, Beschreibung, Tooling-Hinweise). Nodes werden oft mit Topologie- oder Hardware-Hinweisen gelabelt, um das Scheduling zu steuern.
# label a pod
kubectl label pod nginx app=nginx tier=web
# label all pods matching a selector
kubectl label pods -l app=oldapp app=newapp --overwrite
# label a node (for scheduling hints)
kubectl label node node-1 disktype=ssd
# remove a node label
kubectl label node node-1 disktype-
# list nodes by label
kubectl get nodes -l disktype=ssd
# annotate (non-identifying metadata)
kubectl annotate pod nginx owner=alice
kubectl annotate pod nginx description="web server"Selektoren in Manifesten
Im YAML verwenden Selektoren matchLabels (Gleichheit) und matchExpressions (mengenbasiert mit In/NotIn/Exists/DoesNotExist). Beim Deployment ist der Selektor nach der Erstellung unveränderlich — und die Pod-Template-Labels müssen ihm entsprechen. Services unterstützen nur matchLabels.
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
selector:
matchLabels: # equality-based
app: nginx
matchExpressions: # set-based (optional)
- key: env
operator: In
values: [prod, staging]
- key: tier
operator: Exists
template:
metadata:
labels:
app: nginx # MUST match selector
env: prod
tier: webAnnotations
Annotations halten nicht-identifizierende Metadaten, die Tools nutzen — kubectl apply speichert die last-applied-Konfiguration, cert-manager liest Issuer-Hinweise, Prometheus liest die Scrape-Konfiguration, Controller speichern Rollout-Status. Anders als Labels dürfen Annotation-Werte große JSON-Blobs sein.
metadata:
annotations:
kubernetes.io/change-cause: "bump nginx to 1.26"
prometheus.io/scrape: "true"
prometheus.io/port: "9090"
kubectl.kubernetes.io/last-applied-configuration: |
{"apiVersion":"apps/v1",...}
cert-manager.io/cluster-issuer: "letsencrypt-prod"
# view annotations
kubectl get pod nginx -o jsonpath='{.metadata.annotations}'
# annotate
kubectl annotate pod nginx owner=team-platform
# remove an annotation (trailing dash)
kubectl annotate pod nginx owner-Empfohlene Labels
Die app.kubernetes.io/*-Labels sind ein gemeinsames Vokabular, damit Tools (Helm, Operatoren, Dashboards) alle Ressourcen einer Anwendung gruppieren können. name+instance identifizieren ein Release eindeutig; component/part-of beschreiben die Hierarchie; managed-by/created-by verfolgen die Eigentümerschaft.
# shared recommended labels (app.kubernetes.io/*)
metadata:
labels:
app.kubernetes.io/name: nginx
app.kubernetes.io/instance: nginx-prod
app.kubernetes.io/version: "1.25"
app.kubernetes.io/component: web
app.kubernetes.io/part-of: storefront
app.kubernetes.io/managed-by: helm
app.kubernetes.io/created-by: controller-manager
# Helm applies these automatically; kubectl doesn't.
# They unify how tooling identifies an application's resources
# across Deployments, Services, Ingresses, ConfigMaps, etc.ReplicaSet
ReplicaSet-Manifest
Ein ReplicaSet hält eine stabile Menge an Replika-Pods passend zu einem Selektor — es erzeugt Pods neu, wenn sie gelöscht werden oder fehlschlagen. Fast immer nutzt man stattdessen ein Deployment, das ein ReplicaSet ummantelt und Rolling-Updates und Rollbacks ergänzt.
apiVersion: apps/v1
kind: ReplicaSet
metadata:
name: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.25
# kubectl get rs
# kubectl describe rs nginxWie ein ReplicaSet funktioniert
Der ReplicaSet-Controller gleicht gewünschte und tatsächliche Pod-Zahl über den Selektor ab. Jeder Pod bekommt eine ownerReference auf das RS — deshalb zeigt kubectl get pod 'Owned by ReplicaSet/nginx'. Skalieren ändert nur die gewünschte Zahl.
# the controller loop:
# 1. count pods matching selector
# 2. if fewer than replicas -> create from template
# 3. if more than replicas -> delete excess (arbitrary order)
# owned-by reference on each pod
kubectl get pod -l app=nginx -o jsonpath='{.items[*].metadata.ownerReferences}'
# if you delete a pod, the RS creates a new one immediately
kubectl delete pod <pod-name>
kubectl get pods -l app=nginx
# scale by editing replicas
kubectl scale rs nginx --replicas=5ReplicaSet vs. ReplicationController
ReplicationController (die ursprüngliche v1-Primitiva) unterstützt nur Gleichheits-Selektoren und ist deprecated. ReplicaSet (apps/v1) ergänzt mengenbasierte Selektoren. In der Praxis verwendet man Deployment — es verwaltet ReplicaSets und liefert Rolling-Updates/Rollbacks.
# ReplicationController (v1, legacy): equality-only selectors
# ReplicaSet (apps/v1, modern): set-based selectors (in, notin, exists)
# ReplicationController is deprecated; do not use.
apiVersion: v1
kind: ReplicationController # legacy
# ...
# ReplicaSet is the successor:
apiVersion: apps/v1
kind: ReplicaSet # modern
# ...
# Deployment wraps ReplicaSet and is the recommended primitive:
apiVersion: apps/v1
kind: Deployment # use this in practiceManuelle Skalierung
kubectl scale ändert das replicas-Feld. Greift eine HPA auf dieselbe Ressource, überschreibt sie beim nächsten Reconcile die manuelle Skalierung. kubectl scale für Einmalaktionen, HPA für dauerhafte elastische Workloads.
# scale a replicaset directly
kubectl scale rs nginx --replicas=5
# scale via patch
kubectl patch rs nginx -p '{"spec":{"replicas":5}}'
# scale multiple resources at once
kubectl scale deployment nginx deployment web --replicas=3
# scale by referencing a file
kubectl scale --replicas=5 -f nginx.yaml
# the autoscaler (HPA) will override manual scaling
# if it targets the same resourceTemplate-Änderungen & Adoption
Anders als ein Deployment rollt ein nacktes ReplicaSet Änderungen am Pod-Template nicht aus — nur neu erzeugte Pods (nach delete/scale-up) bekommen die neue Spezifikation. Ein ReplicaSet adoptiert jeden verwaisten Pod, der zum Selektor passt — das kann überraschendes Verhalten verursachen.
# changing the pod template does NOT update existing pods
# (unlike a Deployment, a bare ReplicaSet won't roll out)
kubectl edit rs nginx # change image -> new pods use it, old ones don't
# delete old pods to force them onto the new template
kubectl delete pods -l app=nginx
# a ReplicaSet will ADOPT existing pods that match its selector
# even pods created independently — useful (and dangerous)
# orphaned pods (no owner) matching the selector are taken over
kubectl get pods -l app=nginx --show-kindPods aus einem ReplicaSet entfernen
Um einen Pod zu entfernen, ohne dass das ReplicaSet ihn neu erzeugt, entweder das RS erst auf 0 skalieren oder die ownerReferences vom Pod abziehen, damit das RS ihn nicht mehr besitzt. Nützlich, um eine konkrete Instanz zu debuggen oder vor dem Aufräumen Logs zu extrahieren.
# detaching a pod from its ReplicaSet (so it isn't replaced)
kubectl patch pod <pod-name> \
-p '{"metadata":{"ownerReferences":[]}}'
# now deleting this pod won't trigger a replacement,
# because the RS no longer owns it
# or scale the RS to 0 first, then delete
kubectl scale rs nginx --replicas=0
kubectl delete pod <pod-name>
# useful for debugging a specific failing pod instance
# without the RS immediately recreating itStatefulSet
StatefulSet-Manifest
StatefulSet gibt Pods eine stabile Identität (Name, Hostname, Storage) und geordnetes Deploy/Scale. Erfordert einen headless serviceName. volumeClaimTemplates erzeugt pro Pod eine eigene PVC — wird pod-0 neu eingeplant, hängt er sich wieder dasselbe Volume an.
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: mysql
spec:
serviceName: mysql # required: headless service
replicas: 3
selector:
matchLabels:
app: mysql
template:
metadata:
labels:
app: mysql
spec:
containers:
- name: mysql
image: mysql:8
ports:
- containerPort: 3306
volumeMounts:
- name: data
mountPath: /var/lib/mysql
volumeClaimTemplates: # one PVC per pod
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 10GiStabile Identität
Jeder Pod bekommt einen stabilen Ordinalnamen (mysql-0, mysql-1, …) und über den headless Service einen stabilen DNS-Namen. Fällt ein Knoten aus, wird pod-0 anderswo neu eingeplant, behält Name und hängt sein Volume wieder an — entscheidend für geclusterte Datenbanken mit stabiler Mitgliedschaft.
# pods are named <statefulset-name>-<ordinal>
# mysql-0, mysql-1, mysql-2
kubectl get pods -l app=mysql
# each pod has stable DNS (via the headless service):
# mysql-0.mysql.default.svc.cluster.local
# mysql-1.mysql.default.svc.cluster.local
# stable hostname inside the pod:
kubectl exec mysql-0 -- hostname
# -> mysql-0
# ordinal index also exposed:
kubectl exec mysql-0 -- sh -c 'echo $HOSTNAME'
# -> mysql-0
# pod identity persists across reschedulesStabiler Storage
volumeClaimTemplates erzeugt pro Pod eine PVC mit vorhersagbarem Namen (data-mysql-0, …). PVCs überleben Pod- und StatefulSet-Löschung — das verhindert Datenverlust, bedeutet aber, PVCs explizit löschen zu müssen, um Storage freizugeben. Dasselbe Volume hängt immer amselben Ordinal-Pod wieder an.
# one PVC per pod, named <volumeClaimTemplate-name>-<pod-name>
kubectl get pvc
# NAME STATUS VOLUME CAPACITY ...
# data-mysql-0 Bound pvc-aaa 10Gi
# data-mysql-1 Bound pvc-bbb 10Gi
# data-mysql-2 Bound pvc-ccc 10Gi
# when pod-0 is rescheduled, it re-binds data-mysql-0
# deleting the StatefulSet does NOT delete PVCs by default
# (protects from accidental data loss)
# to actually delete the data:
kubectl delete pvc data-mysql-0 data-mysql-1 data-mysql-2Geordnetes Deployment & Pod-Management
OrderedReady (Standard) erzeugt Pods strikt in Reihenfolge 0→1→2 und löscht in Umkehrung — nötig für Systeme, die einen Primary vor den Replikas bootstrappen brauchen. Parallel erzeugt/löscht alle Pods gleichzeitig — schneller für symmetrisch geshardete Stores (Cassandra, Elasticsearch).
spec:
podManagementPolicy: OrderedReady # default: strict order
# podManagementPolicy: Parallel # create/delete all at once
replicas: 3
# OrderedReady: create pod-0, then pod-1, then pod-2 (each waits for Ready)
# deletion is reverse: pod-2, pod-1, pod-0
# Parallel: all pods created/deleted simultaneously
# identity and storage remain stable either way
# check policy
kubectl get statefulset mysql -o jsonpath='{.spec.podManagementPolicy}'
# parallel is great for sharded stores that don't need bootstrap orderRolling-Updates
Rolling-Updates des StatefulSet laufen in umgekehrter Ordinal-Reihenfolge (N-1 bis 0). partition erlaubt Canary-Ausrollen der höchsten Ordinals zuerst. OnDelete pausiert Updates, bis man Pods manuell löscht — nützlich für kontrollierte Migrationen. Rollouts sind wegen der Reihenfolge langsamer als bei Deployments.
spec:
updateStrategy:
type: RollingUpdate
rollingUpdate:
partition: 2 # only pods with ordinal >= 2 update
maxUnavailable: 1 # (default 1) allowed down
# type: OnDelete -> only update when pod is manually deleted
# partition enables canaries: set partition=N to update
# only the top N pods; lower to 0 to roll out to all.
kubectl rollout status statefulset/mysql
# waits for all pods to be updated
# StatefulSets also support rollout history/undo,
# but only when the change is in the pod templateVerknüpfung mit Headless-Service
Der headless Service (clusterIP: None), den spec.serviceName referenziert, macht stabile DNS-Namen pro Pod überhaupt möglich. Ohne ihn erzeugt das StatefulSet keine Pods. Clients lösen den Service-Namen für Round-Robin auf oder pod-0.svc, um einen Primary zu pinnen. Den Service nicht vergessen anzulegen.
apiVersion: v1
kind: Service
metadata:
name: mysql
spec:
clusterIP: None # headless
selector:
app: mysql
ports:
- port: 3306
---
# StatefulSet references this service via spec.serviceName
# this gives each pod a stable DNS:
# mysql-0.mysql.default.svc.cluster.local
# clients can:
# - resolve mysql -> any pod IP (load-balanced by DNS round-robin)
# - resolve mysql-0.mysql -> pod-0's IP (pin to a specific replica)
# required: serviceName MUST match the headless service nameDaemonSet
DaemonSet-Manifest
Ein DaemonSet führt exakt einen Pod pro Knoten aus (unter Berücksichtigung seiner Scheduling-Constraints). Perfekt für Node-Level-Agents: Log-Sammler, Monitoring, Storage, CNI, Ingress-Controller. Neue Knoten bekommen automatisch einen Pod; bei gelöschten Knoten wird der Pod entsorgt.
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: log-agent
namespace: kube-system
labels:
app: log-agent
spec:
selector:
matchLabels:
app: log-agent
template:
metadata:
labels:
app: log-agent
spec:
containers:
- name: agent
image: fluent-bit:2.2
resources:
requests:
cpu: 100m
memory: 128Mi
# one pod per (matching) node automaticallyNode-Scheduling
nodeSelector ist der einfachste Constraint (alle key=value müssen matchen). nodeAffinity ergänzt In/NotIn/Exists-Operatoren sowie preferred/required-Regeln. DaemonSets beachten diese wie jeder Pod — kombiniert mit tolerations laufen Agents auch auf tainted Control-Plane-Knoten.
spec:
template:
spec:
nodeSelector: # simplest: must match all
disktype: ssd
# more flexible affinity
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/os
operator: In
values: [linux]
# only run on nodes labeled role=logging
nodeSelector:
role: logging
tolerations: # tolerate tainted nodes
- key: node-role.kubernetes.io/control-plane
operator: ExistsUpdate-Strategie
RollingUpdate (Standard) aktualisiert Pods Knoten für Knoten, begrenzt durch maxUnavailable (Zahl oder %). OnDelete pausiert Updates, bis man jeden Pod manuell löscht — nützlich, wenn Knoten-für-Knoten-Kontrolle nötig ist. maxSurge ist standardmäßig 0 (DaemonSets wollen selten zusätzliche Pods).
spec:
updateStrategy:
type: RollingUpdate # default
rollingUpdate:
maxUnavailable: 1 # how many nodes update at once
maxSurge: 0 # (default 0) no extra pods
# type: OnDelete # only update when old pod is deleted
# trigger an update (e.g. new image)
kubectl set image daemonset/log-agent agent=fluent-bit:2.3
# watch rollout
kubectl rollout status daemonset/log-agent -n kube-system
# rollout restart (recreate pods on every node)
kubectl rollout restart daemonset/log-agent -n kube-systemTaints & Tolerations
Taints stoßen Pods ab; tolerations erlauben bestimmten Pods, einen Taint zu ignorieren. Control-Plane-Knoten sind mit NoSchedule versehen, damit Nutzer-Workloads dort nicht landen — Node-Level-Agents tolerieren das, um überall zu laufen. NoExecute evigiert auch laufende Pods, die nicht tolerieren.
# inspect a node's taints
kubectl describe node node-1 | grep Taints
# Taints: node-role.kubernetes.io/control-plane:NoSchedule
# tolerate control-plane so the agent runs there too
spec:
template:
spec:
tolerations:
- key: node-role.kubernetes.io/control-plane
operator: Exists
effect: NoSchedule
- key: node.kubernetes.io/disk-pressure
operator: Exists
effect: NoExecute
# taint effects: NoSchedule | NoExecute | PreferNoScheduleDaemonSet-Anwendungsfälle
DaemonSets sind die Standard-Deployment-Form für Node-Level-Infrastruktur. Sie brauchen oft privilegierten Zugriff (hostNetwork, hostPID, hostPath), um ihre Arbeit zu tun — bewusst und nur für vertrauenswürdige Images gewähren. DaemonSet niemals für App-Workloads verwenden, die horizontal skalieren sollen.
# classic DaemonSet workloads (node-level agents):
# - log collection: fluent-bit, filebeat, promtail
# - monitoring: node-exporter, datadog-agent
# - networking: kube-proxy, CNI plugins, ingress controllers
# - storage: CSI node plugins, Rook/Ceph
# - security: Falco, Tetragon, runtime security
# - GPU/FPGA drivers: nvidia-device-plugin
# storage / device plugins often need:
spec:
template:
spec:
hostNetwork: true # use node network namespace
hostPID: true # see node processes
hostPath: # mount node paths
- path: /var/log
- path: /var/lib/docker/containersDaemonSet-Status
DESIRED entspricht der Zahl der Knoten, die die Scheduling-Constraints erfüllen; CURRENT/READY zeigen, wie viele Pods existieren und readiness bestehen. -o wide zeigt am einfachsten, auf welchem Knoten jeder Pod gelandet ist. DaemonSets unterstützen rollout history/undo wie Deployments.
# desired = number of matching nodes
kubectl get daemonset log-agent -n kube-system
# NAME DESIRED CURRENT READY UP-TO-DATE AVAILABLE
# log-agent 5 5 5 5 5
# show which nodes a DaemonSet pod landed on
kubectl get pods -n kube-system -l app=log-agent -o wide
# rollout history
kubectl rollout history daemonset/log-agent -n kube-system
# rollback
kubectl rollout undo daemonset/log-agent -n kube-system
# check a per-node pod's logs
kubectl logs -n kube-system log-agent-abcdeJob & CronJob
Job-Manifest
Ein Job führt Pods aus, bis eine festgelegte Zahl erfolgreich abgeschlossen ist (completions). restartPolicy muss Never oder OnFailure sein (nicht Always — das ist für langlaufende Workloads). backoffLimit begrenzt Retries; activeDeadlineSeconds begrenzt die Gesamtdauer.
apiVersion: batch/v1
kind: Job
metadata:
name: pi
spec:
completions: 1 # how many successful pods needed
parallelism: 1 # how many run concurrently
backoffLimit: 6 # retries before marking Failed
activeDeadlineSeconds: 600 # hard timeout
template:
spec:
restartPolicy: Never # OnFailure | Never
containers:
- name: pi
image: perl
command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(2000)"]
# kubectl get jobs
# kubectl logs job/piJob-Completions & Parallelism
completions = wie viele erfolgreiche Pods den Job erfüllen; parallelism = wie viele gleichzeitig laufen. Indexed Jobs geben jedem Pod ein Ordinal (Env-Variable JOB_COMPLETION_INDEX) — ideal für geshardete Batchverarbeitung, bei der jeder Pod eine Scheibe besitzt. NonIndexed (Standard) braucht einfach N Erfolge von irgendwo.
spec:
completions: 5 # 5 successful pods total
parallelism: 2 # 2 pods run at a time
backoffLimit: 4
# default completionMode: NonIndexed (any 5 successes)
completionMode: Indexed
# Indexed: pods get 0..N-1 in JOB_COMPLETION_INDEX env,
# useful for sharded work (each pod handles one shard)
template:
spec:
restartPolicy: OnFailure
containers:
- name: worker
image: worker:1.0
# set via kubectl
kubectl create job pi --image=perl -- perl -Mbignum=bpi -wle "print bpi(2000)"Job-Backoff & Timeouts
backoffLimit wiederholt fehlgeschlagene Pods (exponentieller Backoff). activeDeadlineSeconds ist die harte Obergrenze — wird sie erreicht, markiert der Job als Failed, selbst wenn Retries übrig sind. ttlSecondsAfterFinished räumt abgeschlossene Jobs automatisch auf. podFailurePolicy (1.31+) erlaubt schnelles Failern bei bestimmten Exit-Codes oder das Ignorieren freiwilliger Evictions.
spec:
backoffLimit: 6 # default 6, retries on failure
activeDeadlineSeconds: 3600 # hard wall, even if retries remain
ttlSecondsAfterFinished: 86400 # auto-delete Job 1 day after done
startingDeadlineSeconds: 300 # (CronJob only) miss window
# pod failure handling (v1.31+):
podFailurePolicy:
rules:
- action: FailJob
onExitCodes:
operator: In
values: [42] # exit 42 -> don't retry, fail fast
- action: Count
onPodConditions:
- type: DisruptionTarget # don't count voluntary evictions
template:CronJob-Manifest
Ein CronJob erzeugt Jobs nach cron-Zeitplan (5 Felder: minute hour day month weekday). concurrencyPolicy steuert überlappende Läufe: Forbid überspringt einen neuen Lauf, wenn der vorige noch läuft; Replace killt den alten und startet neu. timeZone (1.27+) erspart UTC-Umrechnungen.
apiVersion: batch/v1
kind: CronJob
metadata:
name: backup
spec:
schedule: "0 2 * * *" # 5-field cron: 02:00 daily
timeZone: "Asia/Shanghai"
concurrencyPolicy: Forbid # Allow | Forbid | Replace
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 1
startingDeadlineSeconds: 200
jobTemplate:
spec:
backoffLimit: 2
template:
spec:
restartPolicy: OnFailure
containers:
- name: backup
image: backup:1.0
# kubectl get cronjob
# kubectl get jobsCronJob-Suspend & Historie
suspend: true pausiert einen CronJob, ohne ihn zu löschen — praktisch während Incidents. History-Limits halten die Job-Liste überschaubar (Standard 3 Erfolge / 1 Fehler). kubectl create job --from=cronjob/X startet das Template sofort — perfekt für manuelle Trigger oder das Nachziehen verpasster Läufe.
spec:
schedule: "*/5 * * * *"
suspend: true # pause without deleting the CronJob
successfulJobsHistoryLimit: 3 # default 3
failedJobsHistoryLimit: 1 # default 1
# toggle suspend
kubectl patch cronjob backup -p '{"spec":{"suspend":true}}'
kubectl patch cronjob backup -p '{"spec":{"suspend":false}}'
# trigger a one-off run immediately
kubectl create job --from=cronjob/backup manual-backup
# clean up old jobs manually
kubectl delete jobs -l job-name=backupCronJob-Zeitplan & Randfälle
Standard-cron mit 5 Feldern. Sind sowohl day-of-month als auch day-of-week eingeschränkt, feuert cron bei EINEM Treffer (ODER-Semantik) — klassische Falle. Wird eine geplante Zeit um mehr als startingDeadlineSeconds verpasst, wird dieser Lauf übersprungen statt nachgeholt.
# cron syntax (5 fields):
# ┌───────────── minute (0-59)
# │ ┌───────────── hour (0-23)
# │ │ ┌───────────── day of month (1-31)
# │ │ │ ┌───────────── month (1-12)
# │ │ │ │ ┌───────────── day of week (0-6, Sun=0)
# "*/5 * * * *" every 5 minutes
# "0 2 * * *" daily at 02:00
# "0 0 * * 0" weekly Sunday midnight
# "0 0 1 * *" monthly on the 1st
# "30 3-5 * * *" 03:30, 04:30, 05:30
# gotchas:
# - day-of-month AND day-of-week both set => OR (not AND)
# - if startingDeadlineSeconds is missed, the run is skipped
# - control-plane restart can skip a tick if the schedule is missed
# - cron interprets literal fields; prefer timeZone over UTC mathIngress
Ingress-Manifest
Ingress exponiert HTTP/HTTPS-Routen von außerhalb des Clusters zu Services, verwaltet von einem Ingress-Controller (nginx, traefik, ALB, …). ingressClassName wählt, welcher Controller es behandelt. Jede Regel mappt host + path auf ein service+port-Backend.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
ingressClassName: nginx
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web
port:
number: 80
- path: /api
pathType: Prefix
backend:
service:
name: api
port:
number: 8080Ingress mit TLS
tls-Einträge binden ein TLS-Secret (Typ kubernetes.io/tls, mit tls.crt + tls.key) an einen oder mehrere Hosts. Der Ingress-Controller terminiert TLS und proxied plain HTTP zum Backend. cert-manager kann Let's-Encrypt-Zertifikate automatisch ausstellen und rotieren, gesteuert über die cluster-issuer-Annotation.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web-tls
spec:
ingressClassName: nginx
tls:
- hosts:
- app.example.com
- www.example.com
secretName: web-tls-secret # kubernetes.io/tls secret
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web
port:
number: 80
# auto-issue certs with cert-manager:
# annotations:
# cert-manager.io/cluster-issuer: letsencrypt-prodIngress-Regeln & Default-Backend
defaultBackend behandelt Traffic, auf den keine Regel passt (kein Host oder unpassender Pfad). Mehrere Regeln lassen ein Ingress viele virtuelle Hosts routen. Jede Regel kann mehrere Pfad-Backends haben — ein einzelnes Ingress kann die komplette Routing-Topologie einer Anwendung bedienen.
spec:
ingressClassName: nginx
defaultBackend: # catch-all for unmatched traffic
service:
name: default-svc
port:
number: 80
rules:
- host: app.example.com
http:
paths:
- path: /api
pathType: Prefix
backend:
service: { name: api, port: { number: 8080 } }
- host: blog.example.com # different host -> different svc
http:
paths:
- path: /
pathType: Prefix
backend:
service: { name: blog, port: { number: 80 } }IngressClass
Eine IngressClass deklariert einen Controller (z. B. k8s.io/ingress-nginx). Ingresses referenzieren sie über spec.ingressClassName, sodass mehrere Controller koexistieren können. Genau eine Klasse kann mit der Annotation is-default-class als Standard markiert sein — neue Ingresses ohne explizite Klasse nutzen sie.
apiVersion: networking.k8s.io/v1
kind: IngressClass
metadata:
name: nginx
annotations:
ingressclass.kubernetes.io/is-default-class: "true"
spec:
controller: k8s.io/ingress-nginx
# an Ingress picks a class via spec.ingressClassName
# (replaces the deprecated kubernetes.io/ingress.class annotation)
# multiple IngressClasses in one cluster:
# - nginx (community ingress-nginx)
# - traefik (Traefik controller)
# - alb (AWS ALB)
# only one IngressClass can be marked defaultPath-Typen
Exact matcht den Pfad wörtlich; Prefix matcht ganze Pfadsegmente (/api matcht /api und /api/foo, aber nicht /apix). ImplementationSpecific überlässt dem Controller — z. B. nginx-regex. Für portables Verhalten immer Prefix oder Exact vorziehen; ImplementationSpecific bindet an einen Controller.
spec:
rules:
- host: app.example.com
http:
paths:
- path: /api/v1
pathType: Exact # only /api/v1 (exact match)
backend: ...
- path: /api
pathType: Prefix # /api, /api/, /api/x (prefix match)
backend: ...
- path: /old
pathType: ImplementationSpecific # controller decides
backend: ...
# Prefix matches path segments, not raw string prefix:
# /api matches /api, /api/, /api/x but NOT /apix
# Exact matches the path verbatim
# ImplementationSpecific defers to the controllerAnnotations (Nginx-Controller)
Controller-spezifische Annotations konfigurieren Verhalten über den Standard-Ingress-Spec hinaus. ingress-nginx hat Dutzende: rewrite-target, ssl-redirect, body-size, Timeouts, CORS, basic auth, Configuration-Snippets. Sie sind controllerspezifisch — ein Wechsel zu anderem Controller bedeutet Umschreiben.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web
annotations:
kubernetes.io/ingress.class: nginx # legacy form
nginx.ingress.kubernetes.io/rewrite-target: /$2
nginx.ingress.kubernetes.io/ssl-redirect: "true"
nginx.ingress.kubernetes.io/proxy-body-size: "50m"
nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"
nginx.ingress.kubernetes.io/cors-allow-origin: "https://app.example.com"
nginx.ingress.kubernetes.io/auth-type: basic
nginx.ingress.kubernetes.io/auth-secret: basic-auth
nginx.ingress.kubernetes.io/configuration-snippet: |
more_set_headers "X-Frame-Options: DENY";
spec:
rules:
- host: app.example.com
http:
paths:
- path: /v1(/|$)(.*)
pathType: ImplementationSpecific
backend:
service: { name: api, port: { number: 8080 } }Volume (PV/PVC)
PersistentVolume-Manifest
Ein PersistentVolume (PV) ist eine cluster-scoped Storage-Einheit, bereitgestellt von einem Admin oder dynamisch über eine StorageClass. accessModes beschreiben, wie es gemountet werden kann. reclaimPolicy steuert, was mit dem Storage passiert, wenn die PVC freigegeben wird.
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv-1
spec:
capacity:
storage: 10Gi
accessModes:
- ReadWriteOnce # RWO: one node R/W
persistentVolumeReclaimPolicy: Retain # Retain | Delete | Recycle
storageClassName: manual
hostPath: # for dev only (single node)
path: /mnt/data
# nfs:
# server: 10.0.0.1
# path: /export/data
# csi:
# driver: ebs.csi.aws.com
# volumeHandle: vol-xxxxPersistentVolumeClaim-Manifest
Ein PersistentVolumeClaim (PVC) ist ein namespaced Request auf Storage. Der Controller bindet ihn an ein passendes PV (accessModes, ausreichende Kapazität, gleiche StorageClass). Mit einer Default-StorageClass löst ein leer gelassenes storageClassName die dynamische Bereitstellung aus.
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: data-claim
spec:
accessModes:
- ReadWriteOnce
storageClassName: manual
resources:
requests:
storage: 5Gi
volumeMode: Filesystem # Filesystem | Block
selector: # optional: filter PVs by labels
matchLabels:
disktype: ssd
# kubectl get pvc
# STATUS: Pending -> Bound once a matching PV is foundAccess Modes
AccessModes beschreiben Mount-Semantik — die tatsächliche Unterstützung hängt aber vom Storage-Backend ab. EBS/GCE PD/Azure Disk sind nur RWO. RWX (Multi-Node-Read/Write) braucht NFS, CephFS oder ein verteiltes Dateisystem. RWOP (1.27+) beschränkt auf einen Pod, selbst auf demselben Knoten.
# four access modes (support is driver-specific):
# - ReadWriteOnce (RWO): mounted R/W by ONE node
# - ReadOnlyMany (ROX): mounted R/O by MANY nodes
# - ReadWriteMany (RWX): mounted R/W by MANY nodes
# - ReadWriteOncePod (RWOP): mounted R/W by ONE pod (1.27+)
# examples by backend:
# AWS EBS, GCE PD, Azure Disk: RWO only
# NFS: RWO, ROX, RWX
# CephFS, Portworx: RWO, RWX
# Block volumes: RWO
# RWX is required for pods on different nodes
# to share the same volume (e.g. read-only assets)Reclaim Policy
Retain hält die Daten zu Sicherheit zurück — man muss PV manuell löschen und neu binden. Delete (Standard für dynamische Bereitstellung) löscht PV und zugrunde liegenden Storage, wenn die PVC verschwindet. Recycle ist deprecated. Ein Released-PV mit Retain braucht ein geleertes claimRef, bevor es neu gebunden wird.
# what happens when a PVC is deleted:
# - Retain: PV stays, data preserved; PV must be manually
# reclaimed (delete data, then delete PV) before reuse
# - Delete: PV and the underlying storage are deleted (dynamic only)
# - Recycle: deprecated; ran scrub on the volume
# change policy on an existing PV
kubectl patch pv pv-1 -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}'
# a released PV (PVC deleted, policy Retain) is stuck:
# phase=Released, claimRef still set
# to reuse: clear claimRef
kubectl patch pv pv-1 --type json -p '[{"op":"remove","path":"/spec/claimRef"}]'PVC in einem Pod
PVC mounten wie jedes Volume über persistentVolumeClaim.claimName. subPath mountet ein Unterverzeichnis — praktisch, um ein Volume über Pods/Pfade zu teilen. RWO-Volumes können von mehreren Pods gemountet werden, aber nur auf demselben Knoten; Knoten-übergreifendes Mounten erzeugt Multi-Attach-Fehler.
apiVersion: v1
kind: Pod
metadata:
name: db
spec:
volumes:
- name: data
persistentVolumeClaim:
claimName: data-claim
containers:
- name: db
image: postgres:16
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
subPath: pgdata # mount a subdirectory of the volume
# a PVC is namespaced and bound to ONE PV
# RWO PVCs can be mounted by multiple pods on the SAME node
# (e.g. one writer, several readers on that node)Statische vs. dynamische Bereitstellung
Statische Bereitstellung verlangt von Admins vorab angelegte PVs — für NFS okay, bei Scale mühsam. Dynamische Bereitstellung lässt eine PVC bedarfsgesteuert Volume-Erzeugung über den Provisioner einer StorageClass auslösen. Moderne Cluster nutzen fast immer dynamische Bereitstellung; statisch bleibt für gemeinsame/Legacy-Storage reserviert.
# STATIC: admin pre-creates PVs; PVCs bind to them.
# Good for: pre-existing NFS exports, manual capacity planning.
# DYNAMIC: PVC requests storage; StorageClass provisions a PV
# automatically (AWS EBS, GCE PD, Ceph, local-path, etc.)
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: dynamic-claim
spec:
storageClassName: ebs-sc # triggers dynamic provisioning
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 20Gi
# no PV exists -> provisioner creates one -> binds to PVC
# kubectl get pvc dynamic-claim -> Bound
# kubectl get pv -> shows the dynamically-created PVStorageClass
StorageClass-Manifest
Eine StorageClass beschreibt eine 'Sorte' dynamisch bereitgestellten Storage: den Provisioner (CSI-Treiber), Parameter (Disk-Typ, Verschlüsselung, fsType) und Policies. PVCs referenzieren sie über spec.storageClassName. Ein Cluster hat typischerweise mehrere Klassen (schnelle SSD, Massen-HDD, NFS, …).
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: ebs-sc
provisioner: ebs.csi.aws.com
parameters:
type: gp3
fsType: ext4
encrypted: "true"
reclaimPolicy: Delete # Retain | Delete
volumeBindingMode: WaitForFirstConsumer
allowVolumeExpansion: true
mountOptions:
- noatime
# kubectl get storageclassDefault-StorageClass
Genau eine StorageClass kann die Standard sein (Annotation is-default-class: true). PVCs ohne storageClassName nutzen sie automatisch — bequem für Nutzer, denen das Backend egal ist. Mit kubectl get sc sehen, welche Klasse als (default) markiert ist.
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: standard
annotations:
storageclass.kubernetes.io/is-default-class: "true"
provisioner: kubernetes.io/no-provisioner
volumeBindingMode: WaitForFirstConsumer
# a PVC with no storageClassName uses the default
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: auto
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 5Gi
# (no storageClassName set -> uses 'standard')Provisioner
kubernetes.io/no-provisioner bedeutet nur statisches Binding (keine dynamische Erzeugung). Echte dynamische Bereitstellung läuft über CSI-Treiber — Cloud-Provider liefern eigene (ebs.csi.aws.com usw.), selbst gehostete Optionen (Longhorn, Rook/Ceph, local-path) decken Bare Metal ab. Parameter sind komplett provisionerspezifisch.
# built-in (no external driver): only static binding
provisioner: kubernetes.io/no-provisioner
# cloud CSI drivers (dynamic):
provisioner: ebs.csi.aws.com # AWS EBS
provisioner: pd.csi.storage.gke.io # GCE PD
provisioner: disk.csi.azure.com # Azure Disk
provisioner: nfs.csi.k8s.io # NFS
# popular self-hosted:
provisioner: driver.longhorn.io # Longhorn
provisioner: rook-ceph.ceph.com # Rook/Ceph
provisioner: rancher.io/local-path # local-path (dev)
# parameters are provisioner-specific
# (e.g. AWS: type=gp3|iops=3000|encrypted=true)Volume Binding Mode
Immediate bindet die PVC sofort bei Erzeugung — riskant bei zonalen Disks, weil der Pod in einer anderen Zone landen kann. WaitForFirstConsumer schiebt das Binding auf, bis ein Pod die PVC tatsächlich konsumiert, damit das Volume in der richtigen Zone landet. Für zonale Cloud-Disks immer WaitForFirstConsumer verwenden.
spec:
volumeBindingMode: WaitForFirstConsumer
# ^ default for many CSI drivers
# alternatives:
# volumeBindingMode: Immediate
# Immediate: PVC binds/provisions as soon as created
# risk: volume created in zone A, pod scheduled in zone B
# -> multi-attach / cross-zone latency issues
# WaitForFirstConsumer: delays binding until a pod using the PVC
# is scheduled. The PV is then created in the pod's zone.
# REQUIRED for topology-constrained backends (EBS, etc.)
# topology constraints come from the CSI driver via
# AllowedTopologiesReclaim Policy pro StorageClass
StorageClass.reclaimPolicy setzt die Policy aller PVs, die sie dynamisch bereitstellt. Delete (Standard) zerstört das Volume, wenn die PVC gelöscht wird — effizient, aber gefährlich für Produktionsdaten. Um Daten zu retten, das PV auf Retain umstellen, bevor die PVC gelöscht wird, oder von Anfang an eine Retain-Klasse nutzen.
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: ebs-temp
provisioner: ebs.csi.aws.com
reclaimPolicy: Delete # default for dynamic volumes
# reclaimPolicy: Retain # keep data after PVC delete
# the StorageClass policy becomes the PV's policy
# when a PV is dynamically provisioned
# to preserve data, either:
# 1. use a Retain StorageClass
# 2. patch the dynamically-created PV to Retain before deleting PVC:
kubectl patch pv pvc-xxxx -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}'
# then delete PVC safely; data survivesVolume-Expansion
allowVolumeExpansion: true erlaubt, PVCs durch Bearbeiten von spec.resources.requests.storage zu vergrößern. Der CSI-Treiber vergrößert das zugrunde liegende Volume, danach das kubelet das Dateisystem beim nächsten Mount. Verkleinern wird nie unterstützt. Die meisten Cloud-CSI-Treiber unterstützen Online-Expansion (kein Unmount nötig).
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: ebs-sc
provisioner: ebs.csi.aws.com
allowVolumeExpansion: true # must be true to resize
# then resize by editing the PVC's requested size
kubectl patch pvc data-claim -p '{"spec":{"resources":{"requests":{"storage":"50Gi"}}}}'
# status.conditions shows Resizing / FileSystemResizePending
kubectl describe pvc data-claim
# requirements:
# - StorageClass.allowVolumeExpansion = true
# - driver supports online expansion (most CSI drivers do)
# - shrinking is NOT supported (only grow)
# - FilesystemResize happens after the PV is expandedHelm
Helm-Install & Release
Helm verpackt Kubernetes-Manifeste als 'Chart' und verwaltet sie als 'Release'. install erzeugt ein Release; upgrade wendet Änderungen an; upgrade --install ist idempotent. Releases werden über ein Secret/ConfigMap im Namespace nachverfolgt — so funktioniert rollback.
# add and update a chart repo
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo update
# search for charts
helm search repo nginx
helm search hub wordpress # searches Artifact Hub
# install a chart (creates a release)
helm install my-nginx bitnami/nginx --namespace web --create-namespace
# upgrade an existing release
helm upgrade my-nginx bitnami/nginx --set replicaCount=3
# upgrade + install in one idempotent command
helm upgrade --install my-nginx bitnami/nginx -f values.yaml
# uninstall
helm uninstall my-nginx -n web
# list releases
helm list -n web
helm list --all-namespacesChart-Struktur
Ein Chart ist ein Verzeichnis aus getemplatetem YAML plus Defaults. Chart.yaml enthält Metadaten; values.yaml die Defaults; templates/ die Go-Templates, die mit diesen Werten gerendert werden. helm create erzeugt ein lauffähiges Chart-Gerüst. helm lint findet Schema-/Template-Fehler vor dem Veröffentlichen.
my-chart/
├── Chart.yaml # chart metadata (name, version, apiVersion)
├── values.yaml # default values (overridable)
├── charts/ # chart dependencies (subcharts)
├── templates/ # Go-templated YAML
│ ├── deployment.yaml
│ ├── service.yaml
│ ├── _helpers.tpl # named templates (partials)
│ └── NOTES.txt # post-install notes
├── templates.yaml # (optional) CRDs to install before templates
└── README.md
# create a new chart skeleton
helm create my-chart
# lint a chart
helm lint my-chart
# package into a .tgz
helm package my-chartValues & Overrides
values.yaml enthält die Chart-Defaults. Überschreiben mit --set (für Skalare) oder -f (für ganze Dateien). helm show values listet jeden Key, den ein Chart akzeptiert. helm template rendert Manifeste, ohne den Cluster anzufassen — essenziell, um zu prüfen, was ein Release tatsächlich anwenden wird.
# values.yaml (chart defaults)
image:
repository: nginx
tag: "1.25"
replicaCount: 2
service:
type: ClusterIP
port: 80
# override on the command line
helm upgrade --install web my-chart \
--set replicaCount=5 \
--set image.tag=1.26 \
--set service.type=LoadBalancer
# override from a file
helm upgrade --install web my-chart -f prod-values.yaml
# see all values a chart supports
helm show values bitnami/nginx
# rendered output (debug, no install)
helm template web my-chart -f prod-values.yamlTemplates & eingebaute Objekte
Templates nutzen Go-Template-Syntax mit Sprig-Funktionen. .Release.Name macht jedes Install einzigartig; .Values exponiert Chart-Werte; .Chart zieht aus Chart.yaml. Die default-Funktion liefert Fallbacks. Render-sichere Benennung über .Release.Name lässt ein Chart viele Releases im selben Namespace betreiben.
# built-in template objects:
# .Values chart values (after overrides)
# .Release release metadata (Name, Namespace, Service, Revision, IsInstall, IsUpgrade)
# .Chart Chart.yaml contents
# .Files files in the chart
# .Capabilities cluster capabilities (KubeVersion, APIVersions)
# .Template current template info
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ .Release.Name }}-app
labels:
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
spec:
replicas: {{ .Values.replicaCount | default 1 }}
selector:
matchLabels:
app: {{ .Release.Name }}
template:
metadata:
labels:
app: {{ .Release.Name }}Helm-Repository
Helm 3 unterstützt sowohl klassische HTTP-Chart-Repos als auch OCI-Registries (helm push/pull oci://…). OCI ist der moderne, signature-freundliche Weg. helm repo update aktualisiert Indizes; vor jedem upgrade ausführen, um die neuesten Chart-Versionen zu bekommen. Artifact Hub (helm search hub) indexiert öffentliche Charts.
# add a chart repository
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo add jetstack https://charts.jetstack.io
# list configured repos
helm repo list
# update repo indexes
helm repo update
# remove a repo
helm repo remove bitnami
# push to OCI registry (Helm 3+)
helm registry login registry.example.com
helm package my-chart
helm push my-chart-0.1.0.tgz oci://registry.example.com/charts
# pull an OCI chart
helm pull oci://registry.example.com/charts/my-chart --version 0.1.0Rollback & Historie
Jedes install/upgrade erzeugt eine nummerierte Revision, gespeichert als Secret. helm rollback schaltet sofort auf eine frühere Revision um — Helms Killer-Feature gegenüber plain kubectl apply. helm get values zeigt, was tatsächlich deployed wurde — unbezahlbar, um abgedrifteten Zustand zu debuggen.
# view release history
helm history my-nginx -n web
# rollback to a previous revision
helm rollback my-nginx 1 -n web
# get rendered manifests of a deployed release
helm get manifest my-nginx -n web
# get the values used at install/upgrade
helm get values my-nginx -n web
helm get values my-nginx -n web --all # incl. chart defaults
# get all info (hooks, manifest, values, notes)
helm get all my-nginx -n web
# wait for resources to be ready on install/upgrade
helm upgrade --install my-nginx bitnami/nginx --wait --timeout 5mNetworkPolicy
NetworkPolicy-Manifest
Eine NetworkPolicy ist eine Firewall-Regel für Pods. Ein leerer podSelector wählt alle Pods im Namespace; eine leere Regelliste verbietet den gesamten Traffic dieser Art. NetworkPolicies sind additiv — ein Pod ist erlaubt, wenn IRGENDEINE Policy ihn erlaubt. Sie brauchen ein unterstützendes CNI; plain flannel ignoriert sie.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny
namespace: prod
spec:
podSelector: {} # selects ALL pods in the namespace
policyTypes:
- Ingress
- Egress
# no ingress/egress rules => deny all traffic of that type
# effect: pods in 'prod' can't send or receive ANY traffic
# until another policy explicitly allows it
# REQUIRES a CNI that supports NetworkPolicy
# (Calico, Cilium, Weave, kube-router; NOT flannel alone)Ingress-Regeln
Ingress-Regeln erlauben Traffic IN die ausgewählten Pods. from-Einträge werden ODER-verknüpft; Ports ebenso. podSelector matcht Pods im selben Namespace; namespaceSelector matcht ganze Namespaces (das automatisch ergänzte Label kubernetes.io/metadata.name verwenden). Beide in einem Eintrag werden UND-verknüpft.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-web
namespace: prod
spec:
podSelector:
matchLabels:
app: web
policyTypes:
- Ingress
ingress:
- from:
- podSelector: # pods in same namespace
matchLabels:
app: gateway
- namespaceSelector: # whole other namespace
matchLabels:
kubernetes.io/metadata.name: monitoring
- ipBlock: # external CIDR
cidr: 10.0.0.0/8
ports:
- protocol: TCP
port: 8080Egress-Regeln
Egress-Regeln steuern, WOHIN die ausgewählten Pods kommunizieren dürfen. Häufige Falle: ein default-deny egress bricht die DNS-Auflösung, und Pods erreichen kube-dns nicht. Immer UDP/TCP 53 zum Namespace kube-system erlauben, bevor alles andere verboten wird. ipBlock.except schneidet Ausnahmen heraus.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-egress-dns
namespace: prod
spec:
podSelector:
matchLabels:
app: web
policyTypes:
- Egress
egress:
- to:
- namespaceSelector: {} # any namespace (kube-dns)
ports:
- protocol: UDP
port: 53
- to:
- ipBlock:
cidr: 0.0.0.0/0
except:
- 10.0.0.0/8 # allow internet, deny internal
ports:
- protocol: TCP
port: 443
# WARNING: egress deny-all blocks DNS and breaks pods.
# Always allow kube-dns first.Selektoren & Namespace-Auswahl
Ein nackter podSelector matcht Pods im eigenen Namespace der Policy. Ein namespaceSelector matcht ganze Namespaces. Beide — podSelector UND namespaceSelector — in einem Eintrag werden UND-verknüpft (Pods mit Label X im Namespace Y) — als separate Einträge ODER-verknüpft. ipBlock matcht externe IPs.
spec:
podSelector: # selects pods in THIS namespace
matchLabels:
app: web
ingress:
- from:
# SAME namespace, matching pods
- podSelector:
matchLabels:
app: gateway
# DIFFERENT namespace (whole namespace)
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: monitoring
# BOTH: pods in another namespace with specific labels
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: backend
podSelector:
matchLabels:
app: api
# external IP range
- ipBlock:
cidr: 192.168.1.0/24Default-Policies (Deny/Allow All)
Default-deny-Policies (leere Regeln) sperren einen Namespace ab, sodass nur explizite Allow-Listen Löcher öffnen. Als Basis deny-all ingress + deny-all egress anwenden, dann gezielte Allow-Policies ergänzen. Ein leerer ingress: [{}]-Eintrag erlaubt allen ingress — die Notluke zum Ausnehmen.
# --- DEFAULT DENY INGRESS (in a namespace) ---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-ingress
namespace: prod
spec:
podSelector: {}
policyTypes: [Ingress]
---
# --- DEFAULT DENY EGRESS ---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-egress
namespace: prod
spec:
podSelector: {}
policyTypes: [Egress]
---
# --- ALLOW ALL INGRESS (whitelist opt-out) ---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-all-ingress
namespace: prod
spec:
podSelector: {}
policyTypes: [Ingress]
ingress:
- {} # allow from anywherePolicy-Typen & Standardverhalten
NetworkPolicies sind additiv — sobald irgendeine Policy einen Pod auswählt, wird dieser Traffic-Typ für den Pod default-deny, sofern keine explizite Regel ihn erlaubt. Ohne jede Policy ist alles offen. Policies, die zu den Labels eines Pods passen, auflisten, um zu sehen, was seinen Traffic regiert.
spec:
policyTypes:
- Ingress
- Egress
# if omitted, defaults are inferred:
# - Ingress is always present (a policy always affects ingress)
# - Egress is implied if any egress rule exists
# key behaviors:
# - policies are ADDITIVE: a pod is allowed if ANY matching
# policy permits the traffic
# - if NO policy selects a pod => all traffic allowed (default open)
# - if at least one policy selects a pod => default deny for that type
# unless an explicit rule allows it
# inspect effective policies for a pod
kubectl get networkpolicy -n prod -l app=webRBAC
Role (Namespaced)
Eine Role verleiht Rechte an namespaced Ressourcen innerhalb eines einzigen Namespace. rules listen apiGroups, resources und verbs. pods/log ist eine Subressource; pods/exec erfordert das Verb create (weil exec eine Subressource erzeugt). '*' als Wildcard für jeden Wert.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: pod-reader
namespace: dev
rules:
- apiGroups: [""]
resources: ["pods", "pods/log"]
verbs: ["get", "list", "watch"]
- apiGroups: [""]
resources: ["pods/exec"]
verbs: ["create"]
# a Role grants permissions WITHIN one namespace
# verbs: get, list, watch, create, update, patch, delete, deletecollection, "*"
# apiGroups: "" (core), "apps", "batch", "rbac.authorization.k8s.io", ...RoleBinding
Ein RoleBinding verleiht eine Role (oder eine ClusterRole, auf einen Namespace begrenzt) an Subjekte: Users, Groups oder ServiceAccounts. Das Binding liegt im Namespace, in dem die Rechte gelten. roleRef ist unveränderlich — um die referenzierte Role zu wechseln, das Binding löschen und neu anlegen.
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: read-pods
namespace: dev
subjects:
- kind: User
name: alice
apiGroup: rbac.authorization.k8s.io
- kind: ServiceAccount
name: my-sa
namespace: dev
- kind: Group
name: dev-team
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
# binds the Role to users, groups, or service accounts
# RoleBinding can also reference a ClusterRole (scoped to its namespace)ClusterRole & ClusterRoleBinding
Eine ClusterRole verleiht Rechte an cluster-scoped Ressourcen (Nodes, Namespaces, PVs) — Roles dürfen diese nicht anfassen. ClusterRoles lassen sich über RoleBindings in jedem Namespace wiederverwenden (einmal definieren, oft binden). Ein ClusterRoleBinding verleiht eine ClusterRole cluster-weit.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: node-reader
rules:
- apiGroups: [""]
resources: ["nodes"]
verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: read-nodes
subjects:
- kind: ServiceAccount
name: monitor
namespace: kube-system
roleRef:
kind: ClusterRole
name: node-reader
apiGroup: rbac.authorization.k8s.io
# ClusterRole grants cluster-scoped resources (nodes, PVs, namespaces)
# or can be reused across namespaces via a RoleBindingVerbs, Ressourcen & API-Gruppen
apiGroups gruppieren Ressourcen — core ist '' (leerer String); apps enthält Deployments/StatefulSets; batch enthält Jobs/CronJobs. Subressourcen (pods/log, pods/exec, pods/portforward) sind eigene Rechte. resourceNames beschränkt eine Regel auf konkrete Instanzen. nonResourceURLs deckt /healthz, /metrics usw. ab.
rules:
- apiGroups: [""] # core API group
resources: ["pods", "services", "configmaps", "secrets"]
verbs: ["get", "list", "watch"]
- apiGroups: ["apps"]
resources: ["deployments", "replicasets", "statefulsets"]
verbs: ["*"]
- apiGroups: ["batch"]
resources: ["jobs", "cronjobs"]
verbs: ["create", "delete", "get"]
- apiGroups: [""]
resources: ["pods/log", "pods/exec", "pods/portforward"]
verbs: ["get", "create"]
- nonResourceURLs: ["/healthz", "/healthz/*"] # non-resource URLs
verbs: ["get"]
# resourceNames: restrict to specific instances
- apiGroups: [""]
resources: ["configmaps"]
resourceNames: ["my-config"]
verbs: ["get"]ServiceAccount
Ein ServiceAccount ist eine Identität für Pods. Zuweisen über serviceAccountName; das Token wird automatisch unter /var/run/secrets/kubernetes.io/serviceaccount gemountet. Seit 1.24 haben SAs keine permanenten Token-Secrets mehr — kubectl create token für kurzlebige, zeitlich begrenzte Tokens. automountServiceAccountToken: false meldet sich ab.
# create a service account
kubectl create serviceaccount my-sa -n dev
# assign a RoleBinding (see RoleBinding example)
# mount the SA in a pod
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
serviceAccountName: my-sa
automountServiceAccountToken: false # opt out of token mount
containers:
- name: app
image: myapp:1.0
# short-lived tokens (1.24+) - no permanent secret
kubectl create token my-sa -n dev --duration=1h
# list SAs
kubectl get sa -n devkubectl auth can-i
kubectl auth can-i prüft RBAC-Rechte für den aktuellen (oder imitierten) Nutzer — essenziell beim Debuggen von 'forbidden'-Fehlern. --list zeigt jedes erlaubte Verb/Ressource. --as imitiert einen User/SA zum Testen. Eingebaute Rollen (view, edit, admin, cluster-admin) decken gängige Bedürfnisse ab.
# check if you can do something
kubectl auth can-i create pods -n dev
kubectl auth can-i delete deployments -n prod
# check on behalf of another user/SA
kubectl auth can-i list secrets --as=system:serviceaccount:dev:my-sa -n dev
# check all allowed verbs on a resource
kubectl auth can-i --list --as=alice -n dev
# whoami (1.25+)
kubectl auth whoami
# reconcile: detect over-privileged bindings
kubectl get rolebindings,clusterrolebindings --all-namespaces -o wide
# common built-in cluster roles:
# view, edit, admin, cluster-adminProbes (Liveness/Readiness/Startup)
Liveness-Probe
Eine liveness probe sagt dem kubelet, wann ein Container neu gestartet werden soll. Schlägt sie failureThreshold Male hintereinander fehl, killt das kubelet den Container und die Restart-Policy greift. Für die Erholung von Deadlocks oder nicht behebbaren Zuständen — nicht zum Prüfen von Abhängigkeiten (das ist Readiness).
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
containers:
- name: app
image: myapp:1.0
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 15
periodSeconds: 10
timeoutSeconds: 2
failureThreshold: 3
successThreshold: 1
# if the probe fails failureThreshold times in a row,
# kubelet kills and restarts the container (per restartPolicy)Readiness-Probe
Eine readiness probe steuert, ob der Pod Traffic von Services erhält. Eine fehlgeschlagene Readiness-Probe entfernt die Pod-IP aus den Endpoints — startet den Pod aber NICHT neu. Für Aufwärmphase verwenden (nicht routen, bis bereit) und um Traffic abzufließen bei transienten Fehlern oder sauberem Herunterfahren.
apiVersion: v1
kind: Pod
metadata:
name: app
spec:
containers:
- name: app
image: myapp:1.0
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
failureThreshold: 3
# a failing readiness probe REMOVES the pod from service endpoints,
# but does NOT restart the container.
# use to drain traffic during deploys, warm-up, or transient outages.Startup-Probe
Eine startup probe (1.18+) ist für langsam startende Apps (Java, Legacy-Server). Solange sie läuft, sind liveness und readiness deaktiviert — ein langsamer Boot wird also nicht von liveness gekillt. Danach aktivieren sich liveness/readiness. Für den Boot ein großes failureThreshold × periodSeconds-Fenster wählen.
apiVersion: v1
kind: Pod
metadata:
name: slow-app
spec:
containers:
- name: app
image: myapp:1.0
startupProbe:
httpGet:
path: /startup
port: 8080
failureThreshold: 30
periodSeconds: 10 # up to 300s to start
livenessProbe:
httpGet:
path: /healthz
port: 8080
periodSeconds: 10
# while the startup probe runs, liveness/readiness are disabled.
# once startup succeeds, liveness/readiness take over.Probe-Handler
Drei Handler-Typen: httpGet (Erfolg = HTTP 2xx/3xx), tcpSocket (Erfolg = TCP-Verbindung), exec (Erfolg = exit 0). Die gRPC-Probe (1.27+ GA) ist die sauberste Option für gRPC-Services. httpGet bevorzugen — die App kann 'gesund aber beschäftigt' (503) signalisieren, ohne Neustart. exec ist fragil (braucht Shell/Binaries im Image).
# three handler types:
# 1. HTTP GET (most common) - success = 200-399
livenessProbe:
httpGet:
path: /healthz
port: 8080
httpHeaders:
- name: X-Custom
value: probe
scheme: HTTP
# 2. TCP socket - success = port open
livenessProbe:
tcpSocket:
port: 3306
# 3. Exec - success = exit code 0
livenessProbe:
exec:
command:
- /bin/sh
- -c
- "pg_isready -h localhost"
# gRPC (1.24+, alpha -> GA): use grpc probe
livenessProbe:
grpc:
port: 9090
service: my.package.HealthProbe-Parameter
initialDelaySeconds verzögert die erste Probe — aber eine startup probe ist der sauberere Weg für langsame Boots. periodSeconds ist das Intervall; failureThreshold × periodSeconds ist, wie lange ein Pod unhealthy sein kann, bevor etwas passiert. Straff für schnelles Failover, locker für Toleranz. terminationGracePeriodSeconds begrenzt das Herunterfahren.
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 15 # wait before first probe (after start)
periodSeconds: 10 # probe every 10s
timeoutSeconds: 2 # max time per probe
successThreshold: 1 # consecutive successes to mark OK
failureThreshold: 3 # consecutive failures to mark failed
terminationGracePeriodSeconds: 30 # (liveness) grace before SIGKILL
# tuning tips:
# - set initialDelaySeconds > typical startup time
# - OR use a startup probe instead (cleaner)
# - shorter period = faster reaction, more load
# - higher failureThreshold = more tolerant of blipsProbe-Fehlverhalten
Liveness-Failure killt und startet den Container in place neu (kein Rescheduling). Readiness-Failure nimmt den Pod nur aus den Services — kein Neustart. Startup-Failure verhält sich wie liveness. Flatternde liveness stammt oft von Probes, die von langsamen Downstream-Services abhängen — Health-Checks lokal und billig halten.
# --- LIVENESS FAIL ---
# container killed -> restarted (per restartPolicy: Always/OnFailure)
# pod stays on the same node (NOT rescheduled)
# CrashLoopBackOff if it keeps failing
# --- READINESS FAIL ---
# pod stays running, but is REMOVED from Service endpoints
# no traffic until it succeeds again
# NOT restarted by kubelet
# --- STARTUP FAIL ---
# container killed and restarted (like liveness)
# liveness/readiness never activate
# after failureThreshold × periodSeconds, pod is stuck restarting
# check probe results:
kubectl describe pod app | grep -A5 "Last State"
kubectl get pod app -o jsonpath='{.status.containerStatuses[*].state}'
# common cause of flapping: liveness probe hitting a slow dependencyRessourcen & Fortgeschrittenes kubectl
Requests & Limits
requests reserviert der Scheduler (ein Pod wird nur eingeplant, wenn ein Knoten freie Requests hat) — auf den Dauerzustand setzen. limits sind harte Obergrenzen: CPU wird gedrosselt, Memory OOMKilled. cpu in Kernen (500m = 0,5), memory in Bytes (Mi/Gi). Für Produktion immer beides setzen.
spec:
containers:
- name: app
image: myapp:1.0
resources:
requests: # what the scheduler guarantees (reservation)
cpu: 250m # 250 millicores = 0.25 core
memory: 256Mi # 256 mebibytes
ephemeral-storage: 1Gi
limits: # hard ceiling (enforced)
cpu: "1" # 1 core
memory: 512Mi
ephemeral-storage: 2Gi
# cpu limit: throttled (cfs quota)
# memory limit: OOMKilled if exceeded
# ephemeral-storage limit: evicted if exceeded
# request only (no limit): best-effort burstLimitRange-Defaults
LimitRange wendet default requests/limits auf Pods an, die keine angeben — kritisch, wenn ein ResourceQuota Requests verlangt. max/min begrenzen, wie groß/klein ein einzelner Container sein darf. maxLimitRequestRatio kapppt, wie weit ein Container über seinen Request hinaus darf und verhindert laute Nachbarn.
apiVersion: v1
kind: LimitRange
metadata:
name: defaults
namespace: prod
spec:
limits:
- type: Container
default: # applied as LIMITS when not set
cpu: 500m
memory: 512Mi
defaultRequest: # applied as REQUESTS when not set
cpu: 100m
memory: 128Mi
max: # max allowed LIMITS
cpu: "4"
memory: 8Gi
min: # min allowed REQUESTS
cpu: 50m
memory: 64Mi
maxLimitRequestRatio: # limit/request ratio cap (burst cap)
cpu: "4"
# a pod with no resources gets default/defaultRequest applied
# a pod with limit=4cpu, request=50m would breach maxLimitRequestRatioHorizontal Pod Autoscaler
HPA skaliert Replikas anhand von Metriken (CPU/Memory über metrics-server, oder custom/external über den Prometheus Adapter). behavior (v2) stimmt die Aggressivität ab: stabilizationWindowSeconds verhindert Flattern, policies begrenzen das Tempo pro Minute. Runterskalieren ist bewusst langsam.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
minReplicas: 3
maxReplicas: 50
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization # avg across pods
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
behavior: # (v2) scale up/down tuning
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 50 # max 50% down per minute
periodSeconds: 60
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 60
# requires metrics-server for CPU/memory
kubectl get hpa web -wPod Disruption Budget
Ein PodDisruptionBudget begrenzt, wie viele Pods einer Gruppe freiwillig gleichzeitig evigiert werden dürfen — schützt die Verfügbarkeit bei Node-Drains und Cluster-Autoscaler-Aktionen. minAvailable oder maxUnavailable (nicht beides). Es schützt NICHT vor unfreiwilligen Störungen (Hardware-Ausfall) — nur Replikas tun das.
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: web-pdb
namespace: prod
spec:
minAvailable: 2 # at least 2 pods always available
# OR
# maxUnavailable: 1 # at most 1 down at a time
selector:
matchLabels:
app: web
# PDB protects against VOLUNTARY disruptions:
# - kubectl drain (node maintenance)
# - cluster autoscaler evictions
# - kubectl delete pod (controller-managed)
# It does NOT prevent INVOLUNTARY disruptions (node failure, kernel panic).
# check PDB status
kubectl get pdb -n prod
kubectl describe pdb web-pdb -n prodTaints, Tolerations & Affinity
Taints stoßen Pods ab; tolerations erlauben bestimmten Pods, sie zu ignorieren — um Knoten zu widmen (GPU, Ingress, Control-Plane). nodeAffinity bevorzugt/verlangt bestimmte Knoten. podAntiAffinity verteilt Replikas über Topologie-Domänen (Hosts, Zonen) für HA. Taint entfernen mit nachgestelltem Bindestrich auf gleichem key+effect.
# taint a node
kubectl taint nodes node-1 dedicated=gpu:NoSchedule
# tolerate the taint so a pod can schedule there
spec:
tolerations:
- key: dedicated
operator: Equal
value: gpu
effect: NoSchedule
# prefer specific nodes
spec:
affinity:
nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
preference:
matchExpressions:
- key: disktype
operator: In
values: [ssd]
podAntiAffinity: # spread replicas across nodes
requiredDuringSchedulingIgnoredDuringExecution:
- topologyKey: kubernetes.io/hostname
labelSelector:
matchLabels:
app: web
# remove a taint
kubectl taint nodes node-1 dedicated=gpu:NoSchedule-Fortgeschrittenes kubectl (patch/wait/top/debug)
patch unterstützt JSON-, strategic-merge- und merge-Typen. wait blockt, bis eine Bedingung erfüllt ist — perfekt für Skripte. top zeigt live CPU/Memory (braucht metrics-server). kubectl debug hängt einen ephemeren Container an einen laufenden Pod (ideal für distroless-Images) oder öffnet eine Shell auf einem Node.
# JSON patch (precise field ops)
kubectl patch deployment web --type json -p \
'[{"op":"replace","path":"/spec/replicas","value":3}]'
# strategic merge patch (default for k8s objects)
kubectl patch svc web -p '{"spec":{"type":"NodePort"}}'
# wait for a condition
kubectl wait --for=condition=Ready pod/web --timeout=60s
kubectl wait --for=delete pod/web --timeout=30s
# resource usage (needs metrics-server)
kubectl top nodes
kubectl top pods -n prod
kubectl top pod web --containers
# ephemeral debug container (1.25+)
kubectl debug -it web --image=busybox --target=web
# debug a node
kubectl debug node/node-1 -it --image=ubuntu
# run a one-off pod
kubectl run tmp --rm -it --image=alpine -- sh
# explain a field
kubectl explain pod.spec.containers.resourcesVerwandte Kubernetes-Snippets
Copy-paste ready code for common tasks.
Pod Manifest
Define a standalone Pod with a container, env, and probe.
Deployment & Rollout
Manage a replicated, rolling-updated workload.
Service Types
Expose Pods via ClusterIP, NodePort, and LoadBalancer services.
ConfigMap & Secret
Inject configuration and sensitive data into containers.
Ingress Routing
Route external HTTP traffic to services by host and path.
Labels & Selectors
Tag resources and query them with selectors.
kubectl Basics
Common kubectl commands for everyday operations.
Namespaces
Partition a cluster into isolated virtual clusters.
Was this helpful?