Stage 1, Part 6 of 9 · p. 6, Kubernetes Fundamentals (Day 0/1)

PART 6: HANDS-ON LABS

Lab 1: Deploy Your First Pod

Goal: Understand Pod basics.

bash
# Create a Pod
kubectl run nginx --image=nginx:1.25-alpine --port=80

# Check it
kubectl get pods
kubectl describe pod nginx

# Test with port-forward
kubectl port-forward pod/nginx 8080:80

# In another terminal:
curl http://localhost:8080

# Logs
kubectl logs nginx

# Exec
kubectl exec -it nginx -- sh
# Inside: cat /etc/nginx/nginx.conf
exit

# Cleanup
kubectl delete pod nginx

Lab 2: Deployment with Rolling Updates

Goal: Deploy, update, rollback.

bash
# Create a Deployment
kubectl create deployment web --image=nginx:1.24-alpine --replicas=3

# Watch rollout
kubectl get pods -l app=web -w

# Update the image (rolling update)
kubectl set image deployment/web nginx=nginx:1.25-alpine

# Watch rollout
kubectl rollout status deployment/web

# View history
kubectl rollout history deployment/web

# Rollback
kubectl rollout undo deployment/web

# Verify
kubectl get pods -l app=web

# Cleanup
kubectl delete deployment web

Lab 3: Expose with Services

Goal: Create ClusterIP, NodePort, and LoadBalancer Services.

bash
# Create a Deployment
kubectl create deployment nginx --image=nginx:1.25-alpine --replicas=3

# ClusterIP Service
kubectl expose deployment nginx --port=80 --target-port=80 --name=nginx-clusterip

# Test internal access
kubectl run test --image=busybox --rm -it --restart=Never -- wget -qO- nginx-clusterip

# NodePort Service
kubectl expose deployment nginx --port=80 --target-port=80 --type=NodePort --name=nginx-nodeport

# Get node port
kubectl get svc nginx-nodeport
# Access via <NodeIP>:<NodePort>

# View endpoints
kubectl get endpoints

# Cleanup
kubectl delete svc nginx-clusterip nginx-nodeport
kubectl delete deployment nginx

Lab 4: Configuration with ConfigMaps and Secrets

Goal: Inject config and secrets.

bash
# Create ConfigMap
kubectl create configmap app-config \
  --from-literal=APP_MODE=production \
  --from-literal=LOG_LEVEL=info

# Create Secret
kubectl create secret generic db-secret \
  --from-literal=DB_USER=admin \
  --from-literal=DB_PASS=secret123

# Create Pod using both
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: config-demo
spec:
  containers:
  - name: app
    image: busybox
    command: ['sh', '-c', 'sleep 3600']
    envFrom:
    - configMapRef:
        name: app-config
    env:
    - name: DB_PASSWORD
      valueFrom:
        secretKeyRef:
          name: db-secret
          key: DB_PASS
    volumeMounts:
    - name: config-vol
      mountPath: /etc/config
      readOnly: true
  volumes:
  - name: config-vol
    configMap:
      name: app-config
EOF

# Verify
kubectl exec config-demo -- env | grep -E "APP_MODE|LOG_LEVEL|DB_PASSWORD"
kubectl exec config-demo -- ls /etc/config/
kubectl exec config-demo -- cat /etc/config/APP_MODE

# Cleanup
kubectl delete pod config-demo
kubectl delete configmap app-config
kubectl delete secret db-secret

Lab 5: Ingress with TLS

Goal: Expose with Ingress and TLS.

Prerequisites: Ingress controller installed.

bash
# Create a Deployment and Service
kubectl create deployment web --image=nginx:1.25-alpine
kubectl expose deployment web --port=80

# Create TLS cert (self-signed for testing)
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
  -keyout tls.key -out tls.crt \
  -subj "/CN=app.example.com"

# Create TLS Secret
kubectl create secret tls web-tls --cert=tls.crt --key=tls.key

# Create Ingress
cat <<'EOF' | kubectl apply -f -
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: web-ingress
spec:
  ingressClassName: nginx
  tls:
  - hosts:
    - app.example.com
    secretName: web-tls
  rules:
  - host: app.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: web
            port:
              number: 80
EOF

# Test
kubectl get ingress
curl -k -H "Host: app.example.com" https://<ingress-ip>/

# Cleanup
kubectl delete ingress web-ingress
kubectl delete secret web-tls
kubectl delete svc web
kubectl delete deployment web

Lab 6: Namespaces and Resource Quotas

Goal: Isolate with Namespaces and enforce quotas.

bash
# Create Namespace
kubectl create namespace dev

# Apply ResourceQuota
kubectl apply -n dev -f - <<'EOF'
apiVersion: v1
kind: ResourceQuota
metadata:
  name: dev-quota
spec:
  hard:
    requests.cpu: "4"
    requests.memory: 8Gi
    limits.cpu: "8"
    limits.memory: 16Gi
    pods: "10"
EOF

# Apply LimitRange
kubectl apply -n dev -f - <<'EOF'
apiVersion: v1
kind: LimitRange
metadata:
  name: dev-limits
spec:
  limits:
  - default:
      cpu: 500m
      memory: 512Mi
    defaultRequest:
      cpu: 100m
      memory: 128Mi
    type: Container
EOF

# Create a Pod without resources (gets defaults)
kubectl run test -n dev --image=nginx:1.25-alpine

# Check resources
kubectl get pod test -n dev -o jsonpath='{.spec.containers[0].resources}'

# Try to exceed quota
kubectl run big -n dev --image=nginx --overrides='{"spec":{"containers":[{"name":"big","image":"nginx","resources":{"requests":{"memory":"20Gi"}}}]}}'
# Expected: Error

# Cleanup
kubectl delete namespace dev

Lab 7: Package with Helm

Goal: Create, install, and upgrade a Helm chart.

bash
# Create chart
helm create mychart
cd mychart

# View the structure
ls -la

# Render locally
helm template my-release .

# Install
helm install my-release . --namespace default

# Check
kubectl get all -l app.kubernetes.io/instance=my-release

# Upgrade with different values
helm upgrade my-release . --set replicaCount=5

# Check history
helm history my-release

# Rollback
helm rollback my-release 1

# Uninstall
helm uninstall my-release

# Cleanup
cd ..
rm -rf mychart

Lab 8: StatefulSet with Persistent Storage

Goal: Deploy a stateful application.

Prerequisites: StorageClass available.

bash
# Create a StatefulSet
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Service
metadata:
  name: nginx-headless
spec:
  clusterIP: None
  selector:
    app: nginx-stateful
  ports:
  - port: 80
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: nginx
spec:
  serviceName: nginx-headless
  replicas: 3
  selector:
    matchLabels:
      app: nginx-stateful
  template:
    metadata:
      labels:
        app: nginx-stateful
    spec:
      containers:
      - name: nginx
        image: nginx:1.25-alpine
        ports:
        - containerPort: 80
        volumeMounts:
        - name: data
          mountPath: /usr/share/nginx/html
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: ["ReadWriteOnce"]
      resources:
        requests:
          storage: 1Gi
EOF

# Check Pods (created in order)
kubectl get pods -l app=nginx-stateful -w

# Check PVCs
kubectl get pvc

# Test DNS
kubectl run test --image=busybox --rm -it --restart=Never -- nslookup nginx-0.nginx-headless

# Write to each Pod's storage
kubectl exec nginx-0 -- sh -c "echo 'Pod 0 data' > /usr/share/nginx/html/index.html"
kubectl exec nginx-1 -- sh -c "echo 'Pod 1 data' > /usr/share/nginx/html/index.html"

# Cleanup
kubectl delete statefulset nginx
kubectl delete svc nginx-headless
kubectl delete pvc -l app=nginx-stateful

Lab 9: Complete 3-Tier Application

Goal: Deploy a full stack.

bash
# Create the namespace
kubectl create namespace app

# Database (StatefulSet)
kubectl apply -n app -f - <<'EOF'
apiVersion: v1
kind: Secret
metadata:
  name: db-secret
type: Opaque
stringData:
  POSTGRES_PASSWORD: secret123
---
apiVersion: v1
kind: Service
metadata:
  name: db
spec:
  clusterIP: None
  selector:
    app: db
  ports:
  - port: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: db
spec:
  serviceName: db
  replicas: 1
  selector:
    matchLabels:
      app: db
  template:
    metadata:
      labels:
        app: db
    spec:
      containers:
      - name: postgres
        image: postgres:16-alpine
        env:
        - name: POSTGRES_PASSWORD
          valueFrom:
            secretKeyRef:
              name: db-secret
              key: POSTGRES_PASSWORD
        ports:
        - containerPort: 5432
        volumeMounts:
        - name: data
          mountPath: /var/lib/postgresql/data
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: ["ReadWriteOnce"]
      resources:
        requests:
          storage: 1Gi
EOF

# Backend (Deployment)
kubectl apply -n app -f - <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
spec:
  replicas: 2
  selector:
    matchLabels:
      app: api
  template:
    metadata:
      labels:
        app: api
    spec:
      containers:
      - name: api
        image: kennethreitz/httpbin
        ports:
        - containerPort: 80
        env:
        - name: DB_HOST
          value: db-0.db.app.svc.cluster.local
---
apiVersion: v1
kind: Service
metadata:
  name: api
spec:
  selector:
    app: api
  ports:
  - port: 80
    targetPort: 80
EOF

# Frontend (Deployment + Ingress)
kubectl apply -n app -f - <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 2
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
      - name: nginx
        image: nginx:1.25-alpine
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: web
spec:
  selector:
    app: web
  ports:
  - port: 80
    targetPort: 80
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: web
spec:
  ingressClassName: nginx
  rules:
  - host: app.local
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: web
            port:
              number: 80
EOF

# Verify
kubectl get all -n app

# Test
kubectl port-forward -n app svc/web 8080:80
curl http://localhost:8080

# Cleanup
kubectl delete namespace app

1:1 copy of the class Google Doc, code in code blocks.