CS

Kubernetes (K8S)

Kubernetes Guide

This comprehensive guide covers Kubernetes (K8s) operations, from basic pod management to advanced deployment strategies and cluster administration.

Core Concepts

Kubernetes Architecture

  • Control Plane: API Server, etcd, Controller Manager, Scheduler
  • Worker Nodes: Kubelet, Kube Proxy, Container Runtime
  • Pods: Smallest deployable unit, containing one or more containers
  • Services: Network abstraction for pods
  • Deployments: Declarative way to manage pod replicas
  • ConfigMaps/Secrets: Configuration and sensitive data management

Pod Management

Basic Pod Commands

# Get pods
kubectl get pods
kubectl get pods -o wide          # Detailed view
kubectl get pods -w               # Watch mode
kubectl get pods -o yaml          # YAML output

# Pod operations
kubectl describe pod <pod-name>   # Detailed information
kubectl logs <pod-name>           # View logs
kubectl logs -f <pod-name>        # Follow logs
kubectl exec -it <pod-name> -- /bin/bash  # Execute into pod

# Pod lifecycle
kubectl delete pod <pod-name>     # Delete pod
kubectl edit pod <pod-name>       # Edit pod

Pod Creation

# Create pod from image
kubectl run <pod-name> --image=<image-name>

# Create pod with port and expose as service
kubectl run <pod-name> --image=<image-name> --port=<port> --expose

# Generate pod YAML
kubectl run <pod-name> --image=<image-name> --dry-run=client -o yaml > pod.yaml

Node Management

Node Operations

# Get nodes
kubectl get nodes
kubectl get nodes -o wide
kubectl describe node <node-name>

# Node maintenance
kubectl drain <node-name>         # Safely evict pods
kubectl cordon <node-name>        # Mark as unschedulable
kubectl uncordon <node-name>      # Allow scheduling

Resource Creation

Applying Manifests

# Apply single file
kubectl apply -f <file>.yaml

# Apply multiple files
kubectl apply -f <file1>.yaml -f <file2>.yaml

# Apply directory
kubectl apply -f ./<directory>/

# Apply from URL
kubectl apply -f https://<url>

Creating Resources Imperatively

# Create deployment
kubectl create deployment <name> --image=<image>
kubectl create deployment <name> --image=<image> --dry-run=client -o yaml > deployment.yaml

# Create service
kubectl create service <type> <name> --tcp=<port>:<target-port>
kubectl create service <type> <name> --tcp=<port>:<target-port> --dry-run=client -o yaml > service.yaml

# Expose existing deployment
kubectl expose deployment <name> --type=<type> --port=<port> --target-port=<target-port>

Configuration Management

# Create ConfigMap
kubectl create configmap <name> --from-literal=<key>=<value>
kubectl create configmap <name> --from-file=<file>
kubectl create configmap <name> --from-env-file=<file>

# Create Secret
kubectl create secret generic <name> --from-literal=<key>=<value>
kubectl create secret generic <name> --from-file=<file>

Monitoring and Troubleshooting

Resource Monitoring

# Node utilization
kubectl top nodes
kubectl top node <node-name>

# Pod utilization
kubectl top pods
kubectl top pods <pod-name>

Debugging Commands

# Check pod status
kubectl get pods
kubectl describe pod <pod-name>

# Check logs
kubectl logs <pod-name>
kubectl logs <pod-name> -c <container-name>  # Multi-container pods

# Check events
kubectl get events
kubectl get events --sort-by=.metadata.creationTimestamp

# Port forwarding for debugging
kubectl port-forward pod/<pod-name> <local-port>:<pod-port>

Deployment Management

Deployment Operations

# Get deployments
kubectl get deployments
kubectl get deployment <deployment-name>
kubectl describe deployment <deployment-name>

# Scale deployment
kubectl scale deployment <name> --replicas=<count>

# Update deployment
kubectl set image deployment/<name> <container>=<new-image>
kubectl rollout status deployment/<name>

# Rollback deployment
kubectl rollout undo deployment/<name>
kubectl rollout undo deployment/<name> --to-revision=<number>

Rolling Updates

# Check rollout status
kubectl rollout status deployment/<name>

# Pause/resume rollout
kubectl rollout pause deployment/<name>
kubectl rollout resume deployment/<name>

# View rollout history
kubectl rollout history deployment/<name>

Service Management

Service Types

# ClusterIP (default)
kubectl create service clusterip <name> --tcp=<port>:<target-port>

# NodePort
kubectl create service nodeport <name> --tcp=<port>:<target-port> --node-port=<node-port>

# LoadBalancer
kubectl create service loadbalancer <name> --tcp=<port>:<target-port>

# ExternalName
kubectl create service externalname <name> --external-name=<external-name>

Service Discovery

# Get services
kubectl get services
kubectl get svc
kubectl describe service <name>

# Test service connectivity
kubectl run test-pod --image=busybox --rm -it -- wget <service-name>:<port>

Configuration and Storage

Persistent Volumes

# Get PV/PVC
kubectl get pv
kubectl get pvc

# Create PVC
kubectl apply -f pvc.yaml

# Check storage classes
kubectl get storageclass

Ingress Management

# Get ingresses
kubectl get ingress
kubectl describe ingress <name>

# Create ingress
kubectl create ingress <name> --rule="<host>/<path>=<service>:<port>"

Advanced Operations

Namespaces

# Get namespaces
kubectl get namespaces
kubectl get ns

# Create namespace
kubectl create namespace <name>

# Switch context to namespace
kubectl config set-context --current --namespace=<name>

# Get resources in all namespaces
kubectl get pods --all-namespaces

Labels and Selectors

# Label resources
kubectl label pods <pod-name> app=web
kubectl label nodes <node-name> disktype=ssd

# Select with labels
kubectl get pods -l app=web
kubectl get pods -l 'app in (web,api)'

# Remove labels
kubectl label pods <pod-name> app-

Resource Quotas

# Get resource quotas
kubectl get resourcequotas
kubectl describe resourcequota <name>

# Create resource quota
kubectl create quota <name> --hard=cpu=2,memory=4Gi,pods=10

Networking

Network Policies

# Get network policies
kubectl get networkpolicies
kubectl describe networkpolicy <name>

# Apply network policy
kubectl apply -f network-policy.yaml

DNS and Services

# Service DNS format
<service-name>.<namespace>.svc.cluster.local

# Test DNS resolution
kubectl run test-pod --image=busybox --rm -it -- nslookup <service-name>

Security

RBAC (Role-Based Access Control)

# Get roles/rolebindings
kubectl get roles
kubectl get rolebindings
kubectl get clusterroles
kubectl get clusterrolebindings

# Create service account
kubectl create serviceaccount <name>

# Bind role to user/serviceaccount
kubectl create rolebinding <name> --role=<role> --user=<user>

Secrets Management

# Get secrets
kubectl get secrets
kubectl describe secret <name>

# Create TLS secret
kubectl create secret tls <name> --cert=<cert-file> --key=<key-file>

# Create docker registry secret
kubectl create secret docker-registry <name> --docker-server=<server> --docker-username=<user> --docker-password=<pass>

Helm (Package Manager)

Helm Operations

# Install chart
helm install <release-name> <chart-name>

# Upgrade release
helm upgrade <release-name> <chart-name>

# List releases
helm list

# Uninstall release
helm uninstall <release-name>

# Add repository
helm repo add <name> <url>
helm repo update

Troubleshooting Common Issues

Pod Issues

# Pod stuck in Pending
kubectl describe pod <pod-name>  # Check events
kubectl get nodes               # Check node capacity

# Pod CrashLoopBackOff
kubectl logs <pod-name>         # Check application logs
kubectl describe pod <pod-name> # Check exit codes

# Pod in ImagePullBackOff
kubectl describe pod <pod-name> # Check image pull errors
kubectl get secrets             # Check registry credentials

Service Issues

# Service not accessible
kubectl get endpoints <service-name>  # Check if pods are selected
kubectl get pods -l <selector>        # Check pod labels

# DNS resolution issues
kubectl run test-pod --image=busybox --rm -it -- nslookup <service-name>

Node Issues

# Node NotReady
kubectl describe node <node-name>     # Check conditions
kubectl logs <kubelet-pod> -n kube-system  # Check kubelet logs

# Resource pressure
kubectl top nodes                     # Check resource usage
kubectl get pods -o wide              # Check pod distribution

Best Practices

  1. Resource Limits: Always set CPU/memory limits
  2. Health Checks: Implement readiness and liveness probes
  3. Rolling Updates: Use rolling update strategy for zero-downtime deployments
  4. Secrets Management: Never store secrets in code or configmaps
  5. Network Policies: Implement network segmentation
  6. Monitoring: Set up comprehensive monitoring and alerting
  7. Backup: Regular backup of etcd and persistent data
  8. Updates: Keep cluster and applications updated
  9. Security: Implement RBAC, scan images, use security contexts
  10. Documentation: Document your cluster configuration and processes

YAML Manifest Examples

Pod Manifest

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
  labels:
    app: my-app
spec:
  containers:
  - name: my-container
    image: nginx:latest
    ports:
    - containerPort: 80
    resources:
      limits:
        cpu: 100m
        memory: 128Mi
      requests:
        cpu: 50m
        memory: 64Mi

Deployment Manifest

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: my-container
        image: nginx:latest
        ports:
        - containerPort: 80

Service Manifest

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: my-app
  ports:
  - port: 80
    targetPort: 80
  type: ClusterIP

This guide provides comprehensive coverage of Kubernetes operations, from basic pod management to advanced cluster administration and troubleshooting.