Kubernetes Basics
Kubernetes orchestrates containerized applications at scale. Learn fundamental Kubernetes concepts for production deployments.
Challenge
Section titled “Challenge”Deploy Node.js applications to Kubernetes with proper configuration, resource management, and high availability.
Explanation
Section titled “Explanation”Kubernetes Concepts
Section titled “Kubernetes Concepts”- Pod: Smallest deployable unit
- Service: Network exposure
- Deployment: Replica management
- ConfigMap: Configuration data
- Secret: Sensitive data
- Ingress: HTTP/HTTPS routing
Key Features
Section titled “Key Features”- Orchestration: Automate container management
- Scaling: Horizontal pod autoscaling
- Self-healing: Restart failed pods
- Load Balancing: Distribute traffic
- Updates: Rolling deployments
Code Examples
Section titled “Code Examples”1. Basic Kubernetes Deployment
Section titled “1. Basic Kubernetes Deployment”apiVersion: apps/v1kind: Deploymentmetadata: name: nodejs-app labels: app: nodejs-appspec: replicas: 3 strategy: type: RollingUpdate rollingUpdate: maxSurge: 1 maxUnavailable: 0 selector: matchLabels: app: nodejs-app template: metadata: labels: app: nodejs-app spec: containers: - name: app image: myapp:latest imagePullPolicy: Always ports: - containerPort: 3000 name: http env: - name: NODE_ENV value: production - name: DATABASE_URL valueFrom: secretKeyRef: name: app-secrets key: database-url - name: REDIS_URL valueFrom: configMapKeyRef: name: app-config key: redis-url
# Resource limits resources: requests: memory: "256Mi" cpu: "250m" limits: memory: "512Mi" cpu: "500m"
# Health checks livenessProbe: httpGet: path: /health port: 3000 initialDelaySeconds: 30 periodSeconds: 10 timeoutSeconds: 5 failureThreshold: 3
readinessProbe: httpGet: path: /ready port: 3000 initialDelaySeconds: 10 periodSeconds: 5 timeoutSeconds: 3 failureThreshold: 2
# Graceful shutdown lifecycle: preStop: exec: command: ["/bin/sh", "-c", "sleep 15"]
# Volumes volumeMounts: - name: logs mountPath: /app/logs
# Volume configuration volumes: - name: logs emptyDir: {}
# Node affinity affinity: nodeAffinity: preferredDuringSchedulingIgnoredDuringExecution: - weight: 100 nodeAffinityTerm: matchExpressions: - key: node-type operator: In values: [app-node]2. Service Configuration
Section titled “2. Service Configuration”apiVersion: v1kind: Servicemetadata: name: nodejs-app-service labels: app: nodejs-appspec: type: ClusterIP selector: app: nodejs-app ports: - port: 80 targetPort: 3000 protocol: TCP name: http
# Session affinity sessionAffinity: ClientIP sessionAffinityConfig: clientIP: timeoutSeconds: 10800
---
# Load balancer for external accessapiVersion: v1kind: Servicemetadata: name: nodejs-app-lb labels: app: nodejs-appspec: type: LoadBalancer selector: app: nodejs-app ports: - port: 80 targetPort: 3000 protocol: TCP3. Ingress Configuration
Section titled “3. Ingress Configuration”apiVersion: networking.k8s.io/v1kind: Ingressmetadata: name: nodejs-app-ingress annotations: cert-manager.io/cluster-issuer: "letsencrypt-prod" nginx.ingress.kubernetes.io/rate-limit: "100"spec: ingressClassName: nginx tls: - hosts: - api.example.com secretName: tls-secret rules: - host: api.example.com http: paths: - path: / pathType: Prefix backend: service: name: nodejs-app-service port: number: 80 - path: /api/v2 pathType: Prefix backend: service: name: nodejs-app-v2-service port: number: 804. ConfigMap and Secrets
Section titled “4. ConfigMap and Secrets”apiVersion: v1kind: ConfigMapmetadata: name: app-configdata: LOG_LEVEL: "info" REDIS_URL: "redis://redis-service:6379" API_TIMEOUT: "30000" MAX_CONNECTIONS: "100"
---
apiVersion: v1kind: Secretmetadata: name: app-secretstype: OpaquestringData: database-url: postgresql://user:password@postgres:5432/appdb jwt-secret: your-secret-key-here api-key: your-api-key
---
# Docker registry secret for private imagesapiVersion: v1kind: Secretmetadata: name: regcredtype: kubernetes.io/dockercfgdata: .dockercfg: eyJhdXRocyI6IHt...5. Horizontal Pod Autoscaling
Section titled “5. Horizontal Pod Autoscaling”apiVersion: autoscaling/v2kind: HorizontalPodAutoscalermetadata: name: nodejs-app-hpaspec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: nodejs-app minReplicas: 2 maxReplicas: 10 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 70 - type: Resource resource: name: memory target: type: Utilization averageUtilization: 80 behavior: scaleDown: stabilizationWindowSeconds: 300 policies: - type: Percent value: 10 periodSeconds: 60 scaleUp: stabilizationWindowSeconds: 0 policies: - type: Percent value: 100 periodSeconds: 306. Deployment Script
Section titled “6. Deployment Script”#!/bin/bashset -e
NAMESPACE=${NAMESPACE:-default}IMAGE=${IMAGE:-myapp:latest}ENV=${ENV:-staging}
echo "Deploying to Kubernetes ($ENV)..."
# Update imagekubectl set image deployment/nodejs-app \ app=$IMAGE \ -n $NAMESPACE
# Wait for rolloutkubectl rollout status deployment/nodejs-app \ -n $NAMESPACE \ --timeout=5m
# Verify healthecho "Verifying deployment health..."kubectl get pods -n $NAMESPACE -l app=nodejs-app
echo "✓ Deployment successful"Best Practices
Section titled “Best Practices”-
Resource Management
- Set resource requests and limits
- Monitor usage
- Use namespaces
- Define quotas
-
Health Checks
- Liveness probes
- Readiness probes
- Startup probes
- Graceful shutdown
-
Security
- Use Secrets for sensitive data
- RBAC policies
- Network policies
- Container security
-
High Availability
- Multiple replicas
- Pod disruption budgets
- Anti-affinity rules
- Rolling updates
-
Monitoring
- Prometheus metrics
- Pod monitoring
- Node monitoring
- Alerting
Real-World Applications
Section titled “Real-World Applications”- Production Deployments: Scale applications globally
- Multi-Environment: Dev, staging, production
- Auto-Scaling: Handle variable load
- Disaster Recovery: High availability setup
- Service Mesh: Advanced networking