kubectl Essentials
Apply & Inspect
kubectl apply -f file.yaml # create/update
kubectl get pods -o wide # list with node/IP
kubectl get all # everything in namespace
kubectl describe pod web # events + spec
kubectl delete -f file.yaml
kubectl explain deployment.spec # schema docs
Debug
kubectl logs -f web # follow logs
kubectl logs web --previous # crashed container
kubectl exec -it web -- sh # shell in
kubectl port-forward svc/web 8080:80
kubectl get events --sort-by=.lastTimestamp
kubectl top pods # live CPU/mem
Namespaces & Context
kubectl create namespace staging
kubectl get pods -n staging
kubectl config set-context --current --namespace=staging
kubectl config get-contexts
kubectl config use-context prod
Deployment
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: ghcr.io/acme/web:1.4.0
ports:
- containerPort: 8080
Service Types
| Type | Scope |
|---|---|
| ClusterIP | internal only (default) |
| NodePort | node IP : 30000-32767 |
| LoadBalancer | external via cloud LB |
apiVersion: v1
kind: Service
metadata:
name: web
spec:
type: ClusterIP
selector: { app: web }
ports:
- port: 80
targetPort: 8080
kubectl expose deployment web --port=80 --target-port=8080
Config & Secrets
kubectl create configmap app-config \
--from-literal=LOG_LEVEL=info
kubectl create secret generic app-secret \
--from-literal=DB_PASSWORD=s3cr3t
# inject into container spec
envFrom:
- configMapRef: { name: app-config }
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: app-secret
key: DB_PASSWORD
Rollouts
kubectl set image deployment/web web=repo/web:1.5.0
kubectl rollout status deployment/web
kubectl rollout history deployment/web
kubectl rollout undo deployment/web
kubectl scale deployment/web --replicas=5
Probes & Resources
livenessProbe:
httpGet: { path: /healthz, port: 8080 }
initialDelaySeconds: 10
periodSeconds: 10
readinessProbe:
httpGet: { path: /ready, port: 8080 }
periodSeconds: 5
resources:
requests: { cpu: "250m", memory: "256Mi" }
limits: { cpu: "500m", memory: "512Mi" }
Readiness gates traffic; liveness restarts the container. Don't point liveness at external dependencies.
Autoscaling & Ingress
kubectl autoscale deployment web \
--cpu-percent=70 --min=3 --max=20
kubectl get hpa
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web
spec:
ingressClassName: nginx
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web
port: { number: 80 }