kubectl Basics
Cluster Info
kubectl cluster-info kubectl get nodes kubectl config current-context kubectl config use-context my-cluster
Essential Commands
kubectl get <resource>List resources
kubectl describe <resource> <name>Detailed resource info
kubectl create -f file.yamlCreate resource from file
kubectl apply -f file.yamlCreate or update resource
kubectl delete -f file.yamlDelete resource from file
kubectl edit <resource> <name>Edit resource in-place
kubectl api-resourcesList all resource types
Output Formats
-o wideExtra columns (IP, node)
-o yamlFull YAML output
-o jsonFull JSON output
-o jsonpath='{.spec}'Extract specific fields
--sort-by=.metadata.nameSort output by field
Pods
Pod Operations
kubectl get pods kubectl get pods -A # all namespaces kubectl run nginx --image=nginx # quick pod kubectl delete pod nginx
Pod YAML
apiVersion: v1 kind: Pod metadata: name: myapp labels: { app: myapp } spec: containers: - name: app image: nginx:1.27 ports: - containerPort: 80
Pod Status Values
RunningAll containers started
PendingWaiting for scheduling or image pull
CrashLoopBackOffContainer keeps crashing and restarting
ImagePullBackOffCannot pull container image
CompletedRan to completion (Jobs)
Deployments
Deployment YAML
apiVersion: apps/v1 kind: Deployment metadata: name: web spec: replicas: 3 selector: matchLabels: { app: web } template: metadata: labels: { app: web } spec: containers: - name: web image: nginx:1.27 ports: - containerPort: 80
Deployment Commands
kubectl get deployList deployments
kubectl scale deploy web --replicas=5Scale replicas
kubectl set image deploy/web web=nginx:1.28Update image (rolling)
kubectl rollout status deploy/webWatch rollout progress
kubectl rollout undo deploy/webRollback to previous revision
kubectl rollout history deploy/webView revision history
Services
Service Types
ClusterIPInternal only (default)
NodePortExpose on each node's IP at a static port
LoadBalancerExternal load balancer (cloud)
ExternalNameDNS alias to external service
Service YAML
apiVersion: v1 kind: Service metadata: name: web-svc spec: type: ClusterIP selector: { app: web } ports: - port: 80 targetPort: 80
Quick Expose
kubectl expose deploy web --port=80 --type=ClusterIP kubectl expose deploy web --port=80 --type=NodePort kubectl get svc
ConfigMaps & Secrets
ConfigMap
kubectl create configmap app-cfg \ --from-literal=DB_HOST=db.example.com \ --from-file=config.ini
Secret
kubectl create secret generic db-creds \ --from-literal=username=admin \ --from-literal=password=s3cret
Using in Pods
# As environment variables envFrom: - configMapRef: { name: app-cfg } - secretRef: { name: db-creds } # As volume mount volumes: - name: cfg configMap: { name: app-cfg }
Commands
kubectl get cmList ConfigMaps
kubectl get secretList Secrets
kubectl describe cm app-cfgShow ConfigMap data
kubectl get secret db-creds -o yamlShow Secret (base64-encoded)
Namespaces
Namespace Commands
kubectl get nsList namespaces
kubectl create ns stagingCreate namespace
kubectl delete ns stagingDelete namespace and all resources
kubectl get pods -n stagingList pods in namespace
kubectl get pods -AList pods across all namespaces
Set Default Namespace
kubectl config set-context --current \ --namespace=staging
Volumes
PersistentVolumeClaim
apiVersion: v1 kind: PersistentVolumeClaim metadata: name: data-pvc spec: accessModes: [ReadWriteOnce] resources: requests: { storage: 10Gi }
Mount in Pod
volumes: - name: data persistentVolumeClaim: claimName: data-pvc containers: - volumeMounts: - name: data mountPath: /app/data
Volume Types
emptyDirTemp dir, deleted with pod
hostPathMount host filesystem path
persistentVolumeClaimPersistent storage (PVC)
configMapMount ConfigMap as files
secretMount Secret as files
Ingress
Ingress YAML
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: web-ingress spec: rules: - host: app.example.com http: paths: - path: / pathType: Prefix backend: service: name: web-svc port: { number: 80 }
Ingress Notes
Ingress ControllerRequired (nginx-ingress, traefik, etc.)
pathType: PrefixMatch URL prefix
pathType: ExactMatch exact URL path
TLSAdd tls: section with secret name
Debugging
Diagnostic Commands
kubectl logs <pod>Container stdout/stderr
kubectl logs <pod> -c <ctr>Specific container logs
kubectl logs <pod> --previousLogs from crashed container
kubectl describe pod <pod>Events, conditions, status
kubectl exec -it <pod> -- shShell into container
kubectl port-forward <pod> 8080:80Forward local port to pod
kubectl top podsCPU/memory usage (metrics-server)
kubectl get events --sort-by=.lastTimestampCluster events timeline
Debug Pod
kubectl run debug --rm -it --image=busybox -- sh # or attach ephemeral container kubectl debug -it --image=busybox
Common Patterns
Labels & Selectors
kubectl get pods -l app=web kubectl get pods -l 'env in (prod,staging)' kubectl label pod myapp env=prod
Resource Limits
resources: requests: { cpu: 100m, memory: 128Mi } limits: { cpu: 500m, memory: 256Mi }
Liveness & Readiness
livenessProbe: httpGet: { path: /healthz, port: 8080 } initialDelaySeconds: 5 periodSeconds: 10 readinessProbe: httpGet: { path: /ready, port: 8080 }
Quick Recipes
Dry runkubectl apply -f file.yaml --dry-run=client
Generate YAMLkubectl create deploy web --image=nginx --dry-run=client -o yaml
Watchkubectl get pods -w
Copy fileskubectl cp file.txt pod:/tmp/
Restart deploykubectl rollout restart deploy/web