Kubernetes Basics

Difficulty: Advanced

Question

What is Kubernetes? Explain pods, deployments, services, and when you would use Kubernetes over Docker Compose.

Answer

Kubernetes (K8s) is a container orchestration platform that automates deployment, scaling, and management of containerized applications. While Docker Compose manages containers on a single host, Kubernetes manages them across a cluster of machines.

Core concepts: - Pod: The smallest deployable unit. Contains one or more containers that share networking and storage. Usually one container per pod. - Deployment: Declares the desired state (which image, how many replicas). Kubernetes ensures reality matches the desired state. Handles rolling updates and rollbacks. - Service: Provides a stable network endpoint for a set of pods. Pods are ephemeral (they come and go), but services provide a consistent way to reach them. - Ingress: Routes external HTTP/HTTPS traffic to services. Acts like a reverse proxy with routing rules.

When to use Kubernetes over Docker Compose: - Multiple machines (scaling beyond one server) - Auto-scaling based on CPU/memory/custom metrics - Self-healing (automatic restart/replacement of failed containers) - Rolling updates with zero downtime - Service discovery across many microservices

Kubernetes is overkill for small projects. Docker Compose is simpler for local development and single-server deployments.

Code examples

Kubernetes Deployment and Service

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp
  labels:
    app: myapp
spec:
  replicas: 3
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
        - name: myapp
          image: myapp:1.0.0
          ports:
            - containerPort: 3000
          env:
            - name: NODE_ENV
              value: production
            - name: DATABASE_URL
              valueFrom:
                secretKeyRef:
                  name: app-secrets
                  key: database-url
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: 500m
              memory: 512Mi
          readinessProbe:
            httpGet:
              path: /health
              port: 3000
            initialDelaySeconds: 5
            periodSeconds: 10
          livenessProbe:
            httpGet:
              path: /health
              port: 3000
            initialDelaySeconds: 15
            periodSeconds: 20

---
# service.yaml
apiVersion: v1
kind: Service
metadata:
  name: myapp-service
spec:
  selector:
    app: myapp
  ports:
    - port: 80
      targetPort: 3000
  type: ClusterIP

The Deployment maintains 3 replicas with health checks. The Service provides a stable endpoint that load-balances across all healthy pods. Secrets come from Kubernetes Secrets, not env files.

Essential kubectl Commands

# Apply configuration
kubectl apply -f deployment.yaml
kubectl apply -f service.yaml

# View resources
kubectl get pods
# NAME                     READY   STATUS    RESTARTS   AGE
# myapp-7d4b8c6f5-abc12   1/1     Running   0          5m
# myapp-7d4b8c6f5-def34   1/1     Running   0          5m
# myapp-7d4b8c6f5-ghi56   1/1     Running   0          5m

kubectl get deployments
kubectl get services
kubectl get pods -o wide        # with IP and node info

# Describe (detailed info + events)
kubectl describe pod myapp-7d4b8c6f5-abc12

# View logs
kubectl logs myapp-7d4b8c6f5-abc12
kubectl logs -f myapp-7d4b8c6f5-abc12    # follow
kubectl logs --previous myapp-7d4b8c6f5-abc12  # crashed container

# Shell into a pod
kubectl exec -it myapp-7d4b8c6f5-abc12 -- sh

# Scale
kubectl scale deployment myapp --replicas=5

# Rolling update
kubectl set image deployment/myapp myapp=myapp:2.0.0
kubectl rollout status deployment/myapp

# Rollback
kubectl rollout undo deployment/myapp
kubectl rollout history deployment/myapp

kubectl is the primary K8s CLI. apply creates/updates resources. describe shows events for debugging. Rolling updates and rollbacks are built-in.

Ingress and Auto-Scaling

# ingress.yaml - Route external traffic
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: myapp-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
    - host: api.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: myapp-service
                port:
                  number: 80
  tls:
    - hosts:
        - api.example.com
      secretName: tls-secret

---
# Horizontal Pod Autoscaler
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: myapp-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: myapp
  minReplicas: 2
  maxReplicas: 10
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70

# Check autoscaler status
# kubectl get hpa
# NAME       REFERENCE          TARGETS   MINPODS  MAXPODS  REPLICAS
# myapp-hpa  Deployment/myapp   45%/70%   2        10       3

Ingress routes external traffic by hostname and path. HPA automatically scales pods based on CPU utilization. When CPU exceeds 70%, new pods are created up to maxReplicas.

Key points

Concepts covered

Kubernetes, Pods, Deployments, Services, Ingress, kubectl, Scaling