Kubernetes Cheatsheet

Алиасы (сэкономят часы)

alias k=kubectl
alias kgp='kubectl get pods'
alias kgs='kubectl get svc'
alias kgd='kubectl get deploy'
alias kctx='kubectl config use-context'
alias kns='kubectl config set-context --current --namespace'
alias kdesc='kubectl describe'
alias klogs='kubectl logs -f'

# Auto-completion
source <(kubectl completion bash)
complete -o default -F __start_kubectl k

Контекст и namespace

kubectl config get-contexts
kubectl config current-context
kubectl config use-context prod
kubectl config set-context --current --namespace=app-prod

# kubens / kubectx — must-have инструменты
kubens app-prod
kubectx prod

Получение объектов

kubectl get pods
kubectl get pods -A                     # все namespaces
kubectl get pods -o wide                # доп. инфо (Node, IP)
kubectl get pods -o yaml                # YAML
kubectl get pods -o json | jq
kubectl get pods --show-labels
kubectl get pods -l app=api,env=prod    # по labels
kubectl get pods --field-selector=status.phase=Running
kubectl get pods --watch                # live updates

kubectl get all                         # pods, deployments, services, ...
kubectl get all -A
kubectl get pods,svc,deploy -l app=api

Описание / дебаг

kubectl describe pod <name>             # ★ Events в конце
kubectl logs <pod>
kubectl logs <pod> -c <container>       # multi-container
kubectl logs <pod> --previous           # лог упавшего
kubectl logs -f <pod>                   # follow
kubectl logs -l app=api --tail=100      # по label

kubectl exec -it <pod> -- sh
kubectl exec -it <pod> -- env

kubectl get events --sort-by='.lastTimestamp'
kubectl get events --field-selector type!=Normal

# Debug pod
kubectl debug <pod> -it --image=nicolaka/netshoot
kubectl debug node/<node> -it --image=ubuntu

Создание / обновление

kubectl apply -f manifest.yaml
kubectl apply -f ./manifests/           # вся директория
kubectl apply -k ./overlay/             # Kustomize
kubectl delete -f manifest.yaml

kubectl create deploy nginx --image=nginx
kubectl run debug --rm -it --image=busybox -- sh
kubectl scale deploy/api --replicas=5
kubectl rollout restart deploy/api
kubectl rollout status deploy/api
kubectl rollout undo deploy/api         # откат
kubectl rollout history deploy/api

# Editing in place
kubectl edit deploy/api
kubectl set image deploy/api api=myimg:2.0

Сеть

kubectl get svc
kubectl port-forward svc/api 8000:80    # ★ доступ локально
kubectl port-forward pod/api 8000:8000
kubectl expose deploy/api --port=80 --target-port=8000

# Тест сервиса из кластера
kubectl run -it --rm test --image=nicolaka/netshoot --restart=Never -- /bin/bash
curl api.default.svc.cluster.local
nslookup api

ConfigMap / Secret

kubectl create cm app-config --from-file=app.yaml
kubectl create cm app-config --from-literal=KEY=value
kubectl create secret generic db --from-literal=password=secret

# decode secret
kubectl get secret db -o jsonpath='{.data.password}' | base64 -d

Ресурсы и узлы

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

kubectl get nodes
kubectl describe node <name>
kubectl cordon <node>                   # не давать новых pod
kubectl uncordon <node>
kubectl drain <node> --ignore-daemonsets --delete-emptydir-data

Эталонные манифесты

Deployment

apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
  labels: {app: api}
spec:
  replicas: 3
  selector: {matchLabels: {app: api}}
  template:
    metadata:
      labels: {app: api}
    spec:
      securityContext:
        runAsNonRoot: true
        runAsUser: 10000
        fsGroup: 10000
      containers:
        - name: api
          image: ghcr.io/me/api:1.0
          ports: [{containerPort: 8000}]
          resources:
            requests: {cpu: 100m, memory: 128Mi}
            limits:   {memory: 256Mi}
          livenessProbe:
            httpGet: {path: /healthz, port: 8000}
            periodSeconds: 10
          readinessProbe:
            httpGet: {path: /ready, port: 8000}
            periodSeconds: 5
          securityContext:
            readOnlyRootFilesystem: true
            allowPrivilegeEscalation: false
            capabilities: {drop: [ALL]}

Service + Ingress

apiVersion: v1
kind: Service
metadata: {name: api}
spec:
  selector: {app: api}
  ports: [{port: 80, targetPort: 8000}]
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: api
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
  ingressClassName: nginx
  tls:
    - hosts: [api.example.com]
      secretName: api-tls
  rules:
    - host: api.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend: {service: {name: api, port: {number: 80}}}

HPA

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: {name: api}
spec:
  scaleTargetRef: {apiVersion: apps/v1, kind: Deployment, name: api}
  minReplicas: 3
  maxReplicas: 20
  metrics:
    - type: Resource
      resource:
        name: cpu
        target: {type: Utilization, averageUtilization: 70}

NetworkPolicy default deny

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: default-deny}
spec:
  podSelector: {}
  policyTypes: [Ingress, Egress]
  egress:
    # разрешить только DNS
    - to: []
      ports:
        - protocol: UDP
          port: 53

Helm

helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo update
helm search repo nginx
helm install my-nginx bitnami/nginx -n web --create-namespace
helm upgrade my-nginx bitnami/nginx --set replicaCount=3
helm list
helm history my-nginx
helm rollback my-nginx 1
helm uninstall my-nginx

# Свой chart
helm create mychart
helm template mychart                   # рендер без install
helm install --dry-run --debug mychart

Common статусы и что делать

STATUSЧто делать
CrashLoopBackOffkubectl logs <pod> --previous
ImagePullBackOffПроверь тег, imagePullSecrets, права
Pendingkubectl describe → Events: нет ресурсов? taint?
OOMKilledУвеличь memory limit
EvictedНода под давлением. describe node
Init:0/1InitContainer падает. logs <pod> -c init-name

Полезные tools