Zum Inhalt

kubectl Cheatsheet

generieren

kubectl ist das Kommandozeilen-Tool zur Interaktion mit Kubernetes Clustern. Sie können Anwendungen bereitstellen, Clusterressourcen inspizieren und verwalten und Protokolle anzeigen.

Installation und Konfiguration

Installation

```bash

Linux installation

curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl" sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl

macOS installation

brew install kubectl

Windows installation (PowerShell)

curl.exe -LO "https://dl.k8s.io/release/v1.28.0/bin/windows/amd64/kubectl.exe"

Verify installation

kubectl version --client ```_

Konfiguration

```bash

View current configuration

kubectl config view

Get current context

kubectl config current-context

List all 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=my-namespace

Create new context

kubectl config set-context my-context --cluster=my-cluster --user=my-user --namespace=my-namespace

Delete context

kubectl config delete-context my-context ```_

Zugriff auf das Unternehmen

```bash

Set cluster credentials

kubectl config set-cluster my-cluster --server=https://k8s-cluster.example.com --certificate-authority=ca.crt

Set user credentials

kubectl config set-credentials my-user --client-certificate=client.crt --client-key=client.key

Set credentials with token

kubectl config set-credentials my-user --token=bearer_token_here

Merge kubeconfig files

KUBECONFIG=~/.kube/config:~/.kube/config2 kubectl config view --merge --flatten > ~/.kube/merged_config ```_

Grundlegende Befehle

Ressourcen nutzen

```bash

Get all resources

kubectl get all kubectl get all --all-namespaces

Get specific resources

kubectl get pods kubectl get services kubectl get deployments kubectl get nodes kubectl get namespaces

Get with additional information

kubectl get pods -o wide kubectl get pods --show-labels kubectl get pods --sort-by=.metadata.creationTimestamp

Get resources in specific namespace

kubectl get pods -n kube-system kubectl get pods --all-namespaces

Get resources with custom columns

kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName ```_

Ressourcen abmelden

```bash

Describe resources for detailed information

kubectl describe pod kubectl describe service kubectl describe node kubectl describe deployment

Describe with namespace

kubectl describe pod -n ```_

Erstellen und anwenden

```bash

Create resources from file

kubectl create -f manifest.yaml kubectl create -f https://raw.githubusercontent.com/example/manifest.yaml

Apply resources (create or update)

kubectl apply -f manifest.yaml kubectl apply -f directory/ kubectl apply -R -f directory/ # Recursive

Create resources imperatively

kubectl create deployment nginx --image=nginx kubectl create service clusterip nginx --tcp=80:80 kubectl create configmap app-config --from-literal=key=value kubectl create secret generic app-secret --from-literal=password=secret ```_

Löschen von Ressourcen

```bash

Delete resources

kubectl delete pod kubectl delete service kubectl delete deployment

Delete from file

kubectl delete -f manifest.yaml

Delete all resources of a type

kubectl delete pods --all kubectl delete deployments --all

Delete with label selector

kubectl delete pods -l app=nginx

Force delete (use with caution)

kubectl delete pod --force --grace-period=0 ```_

Podest Management

Podeste Operationen

```bash

List pods

kubectl get pods kubectl get pods -o wide kubectl get pods --field-selector=status.phase=Running

Create pod from image

kubectl run nginx --image=nginx kubectl run busybox --image=busybox --rm -it -- /bin/sh # Interactive pod

Get pod logs

kubectl logs kubectl logs -c # Multi-container pod kubectl logs -f # Follow logs kubectl logs --previous # Previous container logs kubectl logs -l app=nginx # Logs from all pods with label

Execute commands in pod

kubectl exec -- ls /app kubectl exec -it -- /bin/bash kubectl exec -it -c -- /bin/sh

Port forwarding

kubectl port-forward 8080:80 kubectl port-forward service/ 8080:80

Copy files to/from pod

kubectl cp :/path/to/file ./local-file kubectl cp ./local-file :/path/to/file kubectl cp :/path/to/file ./local-file -c ```_

Pod Debugging

```bash

Get pod events

kubectl get events --field-selector involvedObject.name=

Debug pod startup issues

kubectl describe pod kubectl logs --previous

Check resource usage

kubectl top pod kubectl top pod --containers

Create debug pod

kubectl run debug --image=busybox --rm -it -- /bin/sh kubectl run debug --image=nicolaka/netshoot --rm -it -- /bin/bash ```_

Arbeitsverwaltung

Einsatzbereiche

```bash

Create deployment

kubectl create deployment nginx --image=nginx:1.21

Scale deployment

kubectl scale deployment nginx --replicas=3 kubectl scale deployment nginx --replicas=0 # Scale down to zero

Update deployment image

kubectl set image deployment/nginx nginx=nginx:1.22 kubectl set image deployment/nginx nginx=nginx:1.22 --record

Set environment variables

kubectl set env deployment/nginx ENV_VAR=production

Edit deployment

kubectl edit deployment nginx

Patch deployment

kubectl patch deployment nginx -p '\\{"spec":\\{"replicas":5\\}\\}' ```_

Rollout Management

```bash

Check rollout status

kubectl rollout status deployment/nginx

View rollout history

kubectl rollout history deployment/nginx kubectl rollout history deployment/nginx --revision=2

Rollback deployment

kubectl rollout undo deployment/nginx kubectl rollout undo deployment/nginx --to-revision=2

Restart deployment (rolling restart)

kubectl rollout restart deployment/nginx

Pause/resume rollout

kubectl rollout pause deployment/nginx kubectl rollout resume deployment/nginx ```_

Service Management

Dienstleistungen

```bash

Expose deployment as service

kubectl expose deployment nginx --port=80 --type=ClusterIP kubectl expose deployment nginx --port=80 --type=NodePort kubectl expose deployment nginx --port=80 --type=LoadBalancer

Create service with specific target port

kubectl expose deployment nginx --port=80 --target-port=8080

List services

kubectl get services kubectl get svc

Describe service

kubectl describe service nginx

Get service endpoints

kubectl get endpoints nginx

Test service connectivity

kubectl run test --image=busybox --rm -it -- wget -qO- http://nginx ```_

ConfigMap und Secret Management

ConfigMaßnahmen

```bash

Create ConfigMap from literal values

kubectl create configmap app-config --from-literal=database_url=mysql://localhost:3306 kubectl create configmap app-config --from-literal=key1=value1 --from-literal=key2=value2

Create ConfigMap from file

kubectl create configmap app-config --from-file=config.properties kubectl create configmap app-config --from-file=key=config.properties

Create ConfigMap from directory

kubectl create configmap app-config --from-file=config/

View ConfigMap

kubectl get configmap app-config -o yaml kubectl describe configmap app-config

Edit ConfigMap

kubectl edit configmap app-config ```_

Geheime Operationen

```bash

Create secret from literal values

kubectl create secret generic app-secret --from-literal=username=admin --from-literal=password=secret

Create secret from file

kubectl create secret generic app-secret --from-file=username.txt --from-file=password.txt

Create TLS secret

kubectl create secret tls tls-secret --cert=tls.crt --key=tls.key

Create Docker registry secret

kubectl create secret docker-registry regcred --docker-server=registry.example.com --docker-username=user --docker-password=pass

View secret (base64 encoded)

kubectl get secret app-secret -o yaml

Decode secret value

kubectl get secret app-secret -o jsonpath='\\{.data.password\\}'|base64 --decode

Edit secret

kubectl edit secret app-secret ```_

Name und Name

```bash

List namespaces

kubectl get namespaces kubectl get ns

Create namespace

kubectl create namespace my-namespace

Delete namespace (deletes all resources in it)

kubectl delete namespace my-namespace

Set default namespace for current context

kubectl config set-context --current --namespace=my-namespace

Get resources in specific namespace

kubectl get pods -n my-namespace

Get resources in all namespaces

kubectl get pods --all-namespaces kubectl get pods -A # Short form ```_

Ressourcenüberwachung und Debugging

Ressourcennutzung

```bash

Node resource usage

kubectl top nodes kubectl top nodes --sort-by=cpu kubectl top nodes --sort-by=memory

Pod resource usage

kubectl top pods kubectl top pods --sort-by=cpu kubectl top pods --sort-by=memory kubectl top pods --containers # Show container-level metrics kubectl top pods -n kube-system

Specific pod resource usage

kubectl top pod kubectl top pod --containers ```_

Veranstaltungen und Protokolle

```bash

Get cluster events

kubectl get events kubectl get events --sort-by=.metadata.creationTimestamp kubectl get events --field-selector type=Warning

Get events for specific resource

kubectl get events --field-selector involvedObject.name=

Watch events in real-time

kubectl get events --watch

Cluster information

kubectl cluster-info kubectl cluster-info dump ```_

Fehlerbehebung

```bash

Check node status

kubectl get nodes kubectl describe node

Check system pods

kubectl get pods -n kube-system

Check API server health

kubectl get --raw='/healthz'

Check component status (deprecated in newer versions)

kubectl get componentstatuses kubectl get cs

Network debugging

kubectl run netshoot --image=nicolaka/netshoot --rm -it -- /bin/bash kubectl run busybox --image=busybox --rm -it -- /bin/sh

DNS debugging

kubectl run debug --image=busybox --rm -it -- nslookup kubernetes.default kubectl run debug --image=busybox --rm -it -- nslookup ..svc.cluster.local ```_

Erweiterte Operationen

Label und Annotation Management

```bash

Add labels

kubectl label pods environment=production kubectl label nodes disktype=ssd

Remove labels

kubectl label pods environment-

Update labels

kubectl label pods environment=staging --overwrite

Add annotations

kubectl annotate pods description="Web server pod"

Remove annotations

kubectl annotate pods description-

Select resources by labels

kubectl get pods -l environment=production kubectl get pods -l environment!=production kubectl get pods -l 'environment in (production,staging)' kubectl get pods -l 'environment notin (development)' ```_

Feldauswähler

```bash

Select by field values

kubectl get pods --field-selector status.phase=Running kubectl get pods --field-selector spec.nodeName=node1 kubectl get events --field-selector type=Warning kubectl get events --field-selector involvedObject.kind=Pod

Combine multiple field selectors

kubectl get pods --field-selector status.phase=Running,spec.nodeName=node1 ```_

Ausgabeformatierung

```bash

JSON output

kubectl get pods -o json kubectl get pod -o json

YAML output

kubectl get pods -o yaml kubectl get pod -o yaml

Custom columns

kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName

JSONPath output

kubectl get pods -o jsonpath='\\{.items[].metadata.name\\}' kubectl get pods -o jsonpath='\\{range .items[]\\}\\{.metadata.name\\}\\{"\t"\\}\\{.status.phase\\}\\{"\n"\\}\\{end\\}'

Go template output

kubectl get pods -o go-template='\\{\\{range .items\\}\\}\\{\\{.metadata.name\\}\\}\\{\\{"\n"\\}\\}\\{\\{end\\}\\}'

Wide output (more columns)

kubectl get pods -o wide ```_

Patch Operationen

```bash

Strategic merge patch

kubectl patch deployment nginx -p '\\{"spec":\\{"replicas":3\\}\\}'

JSON merge patch

kubectl patch deployment nginx --type='merge' -p='\\{"spec":\\{"replicas":3\\}\\}'

JSON patch

kubectl patch deployment nginx --type='json' -p='[\\{"op": "replace", "path": "/spec/replicas", "value": 3\\}]'

Patch from file

kubectl patch deployment nginx --patch-file=patch.yaml ```_

Ressourcenquoten und Grenzwerte

```bash

Get resource quotas

kubectl get resourcequota kubectl describe resourcequota

Get limit ranges

kubectl get limitrange kubectl describe limitrange

Check resource usage against quotas

kubectl describe namespace ```_

Batch Operationen

Jobs und CronJobs

```bash

Create job

kubectl create job pi --image=perl -- perl -Mbignum=bpi -wle 'print bpi(2000)'

Create job from cronjob

kubectl create job --from=cronjob/backup-job backup-manual

List jobs

kubectl get jobs

Describe job

kubectl describe job pi

Delete job

kubectl delete job pi

List cronjobs

kubectl get cronjobs kubectl get cj # Short form

Suspend/resume cronjob

kubectl patch cronjob backup-job -p '\\{"spec":\\{"suspend":true\\}\\}' kubectl patch cronjob backup-job -p '\\{"spec":\\{"suspend":false\\}\\}' ```_

Großbetrieb

```bash

Delete all pods with label

kubectl delete pods -l app=nginx

Delete all resources in namespace

kubectl delete all --all -n my-namespace

Scale multiple deployments

kubectl scale deployment nginx web api --replicas=3

Apply multiple files

kubectl apply -f deployment.yaml -f service.yaml -f ingress.yaml

Apply all files in directory

kubectl apply -f ./manifests/

Apply with recursive directory search

kubectl apply -R -f ./manifests/ ```_

Sicherheit und RBAC

Service Accounts

```bash

Create service account

kubectl create serviceaccount my-service-account

List service accounts

kubectl get serviceaccounts kubectl get sa # Short form

Describe service account

kubectl describe serviceaccount my-service-account

Get service account token

kubectl get secret $(kubectl get serviceaccount my-service-account -o jsonpath='\\{.secrets[0].name\\}') -o jsonpath='\\{.data.token\\}'|base64 --decode ```_

RBAC-Betriebe

```bash

Check permissions

kubectl auth can-i create pods kubectl auth can-i create pods --as=system:serviceaccount:default:my-service-account kubectl auth can-i '' '' # Check if cluster admin

List roles and rolebindings

kubectl get roles kubectl get rolebindings kubectl get clusterroles kubectl get clusterrolebindings

Describe RBAC resources

kubectl describe role kubectl describe rolebinding

Create role

kubectl create role pod-reader --verb=get,list,watch --resource=pods

Create rolebinding

kubectl create rolebinding read-pods --role=pod-reader --user=jane

Create clusterrole

kubectl create clusterrole cluster-reader --verb=get,list,watch --resource=*

Create clusterrolebinding

kubectl create clusterrolebinding cluster-read --clusterrole=cluster-reader --user=jane ```_

Leistung und Optimierung

Ressourcenmanagement

```bash

Check resource requests and limits

kubectl describe nodes|grep -A 5 "Allocated resources"

Get resource usage

kubectl top nodes kubectl top pods --all-namespaces

Check pod resource specifications

kubectl get pods -o custom-columns=NAME:.metadata.name,CPU-REQUEST:.spec.containers[].resources.requests.cpu,MEMORY-REQUEST:.spec.containers[].resources.requests.memory

Identify pods without resource limits

| kubectl get pods -o json | jq '.items[] | select(.spec.containers[].resources.limits == null) | .metadata.name' | ```_

Clusteranalyse

```bash

Get cluster capacity

kubectl get nodes -o custom-columns=NAME:.metadata.name,CPU:.status.capacity.cpu,MEMORY:.status.capacity.memory

Check node conditions

kubectl get nodes -o custom-columns=NAME:.metadata.name,STATUS:.status.conditions[-1].type

Analyze pod distribution

| kubectl get pods -o wide --all-namespaces | awk '\\{print $8\\}' | sort | uniq -c |

Check for failed pods

kubectl get pods --all-namespaces --field-selector=status.phase=Failed ```_

Nützliche Alias und Funktionen

```bash

Add to ~/.bashrc or ~/.zshrc

Basic aliases

alias k='kubectl' alias kg='kubectl get' alias kd='kubectl describe' alias kdel='kubectl delete' alias kl='kubectl logs' alias kex='kubectl exec -it'

Advanced aliases

alias kgp='kubectl get pods' alias kgs='kubectl get services' alias kgd='kubectl get deployments' alias kgn='kubectl get nodes'

Functions

kns() \\{ kubectl config set-context --current --namespace=$1 \\}

kpf() \\{ kubectl port-forward $1 $2:$3 \\}

klf() \\{ kubectl logs -f $1 \\}

Enable kubectl autocompletion

source <(kubectl completion bash) # For bash source <(kubectl completion zsh) # For zsh ```_

Gemeinsame Muster und Beispiele

Rolling-Updates

```bash

Update deployment image

kubectl set image deployment/nginx nginx=nginx:1.22 --record

Monitor rollout

kubectl rollout status deployment/nginx

Rollback if needed

kubectl rollout undo deployment/nginx ```_

Blue-Green Bereitstellung

```bash

Create green deployment

kubectl create deployment nginx-green --image=nginx:1.22

Scale green deployment

kubectl scale deployment nginx-green --replicas=3

Update service selector to point to green

kubectl patch service nginx -p '\\{"spec":\\{"selector":\\{"app":"nginx-green"\\}\\}\\}'

Remove blue deployment

kubectl delete deployment nginx-blue ```_

Kanarische Bereitstellung

```bash

Scale down main deployment

kubectl scale deployment nginx --replicas=8

Create canary deployment

kubectl create deployment nginx-canary --image=nginx:1.22 kubectl scale deployment nginx-canary --replicas=2

Both deployments serve traffic through same service

Monitor metrics and gradually shift traffic

```_

Debugging Network Issues

```bash

Create debug pod

kubectl run debug --image=nicolaka/netshoot --rm -it -- /bin/bash

Inside debug pod:

nslookup kubernetes.default

nslookup ..svc.cluster.local

curl http://..svc.cluster.local

traceroute

```_

Best Practices

Ressourcenspezifikationen

```bash

Always specify resource requests and limits

kubectl run nginx --image=nginx --requests='cpu=100m,memory=128Mi' --limits='cpu=200m,memory=256Mi'

Use appropriate restart policies

kubectl run job-pod --image=busybox --restart=OnFailure -- /bin/sh -c "echo hello" kubectl run one-time-pod --image=busybox --restart=Never -- /bin/sh -c "echo hello" ```_

Gesundheitschecks

```bash

Add health checks to deployments

kubectl patch deployment nginx -p '\\{"spec":\\{"template":\\{"spec":\\{"containers":[\\{"name":"nginx","livenessProbe":\\{"httpGet":\\{"path":"/","port":80\\},"initialDelaySeconds":30,"periodSeconds":10\\}\\}]\\}\\}\\}\\}' ```_

Sicherheit

```bash

Run containers as non-root

kubectl run secure-pod --image=nginx --dry-run=client -o yaml|kubectl patch -f - -p '\\{"spec":\\{"securityContext":\\{"runAsNonRoot":true,"runAsUser":1000\\}\\}\\}'

Use read-only root filesystem

kubectl run secure-pod --image=nginx --dry-run=client -o yaml|kubectl patch -f - -p '\\{"spec":\\{"containers":[\\{"name":"secure-pod","securityContext":\\{"readOnlyRootFilesystem":true\\}\\}]\\}\\}' ```_

Ressourcen