โ๏ธ ConfigMaps = Configuration Hardcoding config is bad. ConfigMaps externalize configuration. Change settings without rebuilding. ๐ Creating ConfigMaps # From literal values kubectl create configmap app-config \ –from-literal=env=production \ –from-literal=log-level=debug \ –from-literal=api-url=https://api.example.com # From file kubectl create configmap app-config \ –from-file=./configs/app.properties \ –from-file=./configs/log4j.properties # From YAML apiVersion: v1 kind: ConfigMap metadata: name: app-config data: env: […]
Category: Kubernetes
Kubernetes: Use Ingress Controllers for HTTP Routing
๐ช Ingress = HTTP Routing NodePort and LoadBalancer are basic. Ingress provides advanced HTTP routing. Single entry point, multiple services. ๐ Ingress Basics # Install NGINX Ingress Controller kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.8.1/deploy/static/provider/cloud/deploy.yaml # Ingress Resource apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: my-ingress spec: rules: – host: app.example.com http: paths: – path: / pathType: Prefix backend: […]
Kubernetes: Manage Storage with Persistent Volumes
๐พ Persistent Volumes = Storage Management Data outlives pods. Persistent Volumes store data. PV, PVC, StorageClass โ storage done right. ๐ PV and PVC # PersistentVolume (PV) apiVersion: v1 kind: PersistentVolume metadata: name: postgres-pv spec: capacity: storage: 10Gi volumeMode: Filesystem accessModes: – ReadWriteOnce persistentVolumeReclaimPolicy: Retain hostPath: path: /data/postgres # PersistentVolumeClaim (PVC) apiVersion: v1 kind: PersistentVolumeClaim […]
Kubernetes: Understand Service Discovery (DNS)
๐ Service Discovery = DNS Services need to find each other. Service Discovery uses DNS. Automatic, built-in, easy. ๐ DNS Basics # Service DNS format service-name.namespace.svc.cluster.local # Example my-service.default.svc.cluster.local # Short form (same namespace) my-service # With port my-service.default.svc.cluster.local:8080 # Headless Service (No cluster IP) apiVersion: v1 kind: Service metadata: name: headless-service spec: clusterIP: None […]
Kubernetes: Use Pod Lifecycle Hooks
๐ Pod Lifecycle Hooks Pods have lifecycle events. Lifecycle hooks run at specific times. Init, pre-stop, post-start. ๐ Hook Types apiVersion: v1 kind: Pod metadata: name: app spec: containers: – name: app image: myapp:latest lifecycle: postStart: exec: command: [“/bin/sh”, “-c”, “echo ‘Container started'”] preStop: exec: command: [“/bin/sh”, “-c”, “echo ‘Container stopping’ && sleep 5”] # […]
Kubernetes: Use Init Containers for Setup Tasks
โ๏ธ Init Containers = Setup Tasks Apps need setup before start. Init containers run before main containers. Database migrations, permissions, downloads. ๐ Init Container Basics apiVersion: v1 kind: Pod metadata: name: app-with-init spec: initContainers: – name: init-db image: busybox command: [‘sh’, ‘-c’, ‘echo “Initializing database…” && sleep 5’] – name: init-permissions image: busybox command: [‘sh’, […]
Kubernetes: Use CronJobs for Scheduled Tasks
โฐ CronJobs = Scheduled Tasks Regular tasks need automation. CronJobs schedule tasks in Kubernetes. Backups, cleanup, reports โ automatic. ๐ CronJob Setup apiVersion: batch/v1 kind: CronJob metadata: name: daily-backup spec: schedule: “0 2 * * *” # Daily at 2 AM jobTemplate: spec: template: spec: containers: – name: backup image: alpine:latest command: – /bin/sh – […]
Kubernetes: Choose the Right Service Type
๐ Service Types = How to Expose Apps Pods need access. Service types control exposure. ClusterIP, NodePort, LoadBalancer โ choose right one. ๐ Service Types # ClusterIP (Default) apiVersion: v1 kind: Service metadata: name: internal-app spec: type: ClusterIP selector: app: myapp ports: – port: 80 targetPort: 8080 # NodePort apiVersion: v1 kind: Service metadata: name: […]
Kubernetes: Use HPA for Automatic Scaling
๐ HPA = Automatic Scaling Traffic changes constantly. Horizontal Pod Autoscaler scales automatically. More pods when needed, less when not. ๐ HPA Setup # Install metrics-server kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml # Verify metrics-server kubectl top pods kubectl top nodes # Create HPA apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: name: web-hpa spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment […]
Kubernetes: Set Resource Limits for Stability
โ๏ธ Resource Limits = Stability Pods can consume all resources. Resource limits ensure stability. CPU, memory โ protect your cluster. ๐ Setting Limits apiVersion: v1 kind: Pod metadata: name: myapp spec: containers: – name: app image: myapp:latest resources: requests: memory: “64Mi” cpu: “250m” limits: memory: “128Mi” cpu: “500m” # Requests: Minimum guaranteed # Limits: Maximum […]
Kubernetes: Secure Your Cluster with Network Policies
๐ก๏ธ Network Policies = Cluster Security Default is allow all. Network Policies control traffic. Zero trust, micro-segmentation, security. ๐ Network Policy Basics # Deny all (Default deny) apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: deny-all spec: podSelector: {} policyTypes: – Ingress – Egress # Allow specific ingress apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: allow-nginx spec: podSelector: […]
Kubernetes: Use PodDisruptionBudget for High Availability
๐ก๏ธ PodDisruptionBudget = High Availability Pods fail, nodes upgrade. PodDisruptionBudget ensures availability. Minimum pods running, safe operations. ๐ PDB Basics apiVersion: policy/v1 kind: PodDisruptionBudget metadata: name: app-pdb spec: minAvailable: 2 # Minimum 2 pods running selector: matchLabels: app: myapp — # Or use maxUnavailable apiVersion: policy/v1 kind: PodDisruptionBudget metadata: name: app-pdb spec: maxUnavailable: 1 # […]
Kubernetes: Use Operators for Automated Management
๐ค Operators = Automated Management Manual operations are error-prone. Operators automate complex applications. Database, monitoring, custom apps โ self-healing. ๐ Popular Operators # Databases – Postgres Operator (Crunchy Data) – MySQL Operator (Oracle) – MongoDB Operator – Elasticsearch Operator – Redis Operator # Monitoring – Prometheus Operator – Grafana Operator – Datadog Operator # Infrastructure […]
Kubernetes: Use Ingress Controllers for HTTP Routing
๐ช Ingress = HTTP Routing NodePort and LoadBalancer are basic. Ingress provides advanced HTTP routing. Single entry point, multiple services, SSL. ๐ Ingress Basics # Install NGINX Ingress Controller kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.8.1/deploy/static/provider/cloud/deploy.yaml # Ingress Resource apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: my-ingress spec: rules: – host: app.example.com http: paths: – path: / pathType: Prefix […]
Kubernetes: Use Helm Charts for Package Management
๐ฆ Helm = Kubernetes Package Manager Kubernetes YAML is repetitive. Helm packages Kubernetes apps. Templates, versioning, sharing โ like apt/yum for K8s. ๐ Helm Commands # Install Helm curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash # Add repositories helm repo add bitnami https://charts.bitnami.com/bitnami helm repo add stable https://charts.helm.sh/stable helm repo update # Search charts helm search repo nginx […]
Kubernetes: Use Persistent Volumes for Data Persistence
๐พ Persistent Data in Kubernetes Pods are ephemeral. Data disappears. Persistent Volumes store data beyond pod life. Essential for databases, files, state. ๐ PV and PVC # PersistentVolume (PV) apiVersion: v1 kind: PersistentVolume metadata: name: postgres-pv spec: capacity: storage: 10Gi volumeMode: Filesystem accessModes: – ReadWriteOnce persistentVolumeReclaimPolicy: Retain hostPath: path: /data/postgres # PersistentVolumeClaim (PVC) apiVersion: v1 […]
Kubernetes: Use ConfigMaps for Configuration Management
โ๏ธ Centralized Configuration Hardcoding config is bad. ConfigMaps externalize configuration. Change settings without rebuilding. ๐ Creating ConfigMaps # From literal values kubectl create configmap app-config \ –from-literal=env=production \ –from-literal=log-level=debug \ –from-literal=api-url=https://api.example.com # From file kubectl create configmap app-config \ –from-file=./configs/app.properties \ –from-file=./configs/log4j.properties # From directory kubectl create configmap app-config \ –from-file=./configs/ # From YAML apiVersion: […]
Kubernetes: Use Secrets to Store Sensitive Data Securely
๐ Secure Secrets Management Passwords, tokens, keys โ never hardcode. Kubernetes Secrets store sensitive data securely. Use in pods via environment variables or volumes. ๐ Creating Secrets # Create from literal values kubectl create secret generic app-secret \ –from-literal=db-password=SecurePass123 \ –from-literal=api-key=abc-123-xyz # Create from file kubectl create secret generic app-secret \ –from-file=./secrets/db-password.txt \ –from-file=./secrets/api-key.txt # […]
Kubernetes: Use Service Mesh (Istio) for Advanced Traffic Management
๐ฆ Advanced Traffic Management for Microservices Service Mesh adds features to Kubernetes. Istio provides traffic routing, load balancing, security, observability. ๐ Install Istio # Download Istio curl -L https://istio.io/downloadIstio | sh – cd istio-1.20.0 export PATH=$PWD/bin:$PATH # Install Istio istioctl install –set profile=demo -y # Enable sidecar injection kubectl label namespace default istio-injection=enabled # Deploy […]
Kubernetes: Use PodDisruptionBudget for Zero Downtime
๐ก๏ธ Prevent Simultaneous Pod Evictions Node draining can evict all pods at once. PodDisruptionBudget ensures minimum availability during disruptions. ๐ PDB Example apiVersion: policy/v1 kind: PodDisruptionBudget metadata: name: app-pdb spec: minAvailable: 2 selector: matchLabels: app: myapp — apiVersion: policy/v1 kind: PodDisruptionBudget metadata: name: app-pdb spec: maxUnavailable: 1 selector: matchLabels: app: myapp ๐ฏ PDB Status # […]
Kubernetes: Use StatefulSets for Stateful Applications
Kubernetes: Use HPA to Auto-Scale Pods Based on Load
๐ Scale Pods Automatically Fixed replicas waste resources. HorizontalPodAutoscaler scales pods based on CPU/memory. Scale up during load, down during low traffic. ๐ HPA Configuration 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: […]
Kubernetes: Use DaemonSets to Run Pods on Every Node
๐ก One Pod Per Node โ Automatically Need monitoring agent on every node? Log collector? DaemonSet runs one pod per node. New nodes get pod automatically. ๐ DaemonSet Example apiVersion: apps/v1 kind: DaemonSet metadata: name: node-monitor namespace: kube-system spec: selector: matchLabels: name: node-monitor template: metadata: labels: name: node-monitor spec: containers: – name: monitor image: prom/node-exporter […]
Kubernetes: Use StorageClasses for Dynamic Volume Provisioning
๐พ StorageClasses Create Volumes Automatically Manual volume creation is tedious. StorageClasses provision volumes dynamically. Specify storage type, size, performance. ๐ StorageClass Examples apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: fast-ssd provisioner: kubernetes.io/aws-ebs parameters: type: gp3 encrypted: “true” iopsPerGB: “50” allowVolumeExpansion: true — apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: standard provisioner: kubernetes.io/aws-ebs parameters: type: gp2 encrypted: “true” […]
Kubernetes: Use Node Affinity to Control Pod Placement
๐ฏ Put Pods Where They Belong Some nodes have GPUs. Some are in different zones. Node affinity schedules pods on specific nodes. Control placement precisely. ๐ Node Affinity apiVersion: v1 kind: Pod metadata: name: gpu-pod spec: affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: – matchExpressions: – key: gpu operator: In values: – “nvidia” – “amd” containers: – name: […]
Kubernetes: Extend Kubernetes with Custom Resource Definitions
๐ Define Your Own Kubernetes Objects Kubernetes has Pods, Services, Deployments. Custom Resource Definitions (CRD) create your own objects. Extend Kubernetes for your needs. ๐ Create a CRD apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: name: databases.myapp.com spec: group: myapp.com versions: – name: v1 served: true storage: true schema: openAPIV3Schema: type: object properties: spec: type: object properties: […]
Kubernetes: Use Service Accounts for Pod Authentication
Kubernetes: Use Security Context to Control Pod Permissions
๐ Run Containers as Non-Root User Containers run as root by default. Security context runs as non-root. Less privilege, better security. ๐ Security Context apiVersion: v1 kind: Pod metadata: name: secure-pod spec: securityContext: runAsUser: 1000 runAsGroup: 3000 fsGroup: 2000 containers: – name: myapp image: myapp:latest securityContext: allowPrivilegeEscalation: false readOnlyRootFilesystem: true capabilities: drop: [“ALL”] add: [“NET_ADMIN”] […]
Kubernetes: Use Persistent Volumes for Data Storage
๐พ Pods Are Ephemeral. Data Shouldn’t Be. Pod restarts lose data. Persistent Volumes (PV) store data outside pods. Databases, uploads, logs survive restarts. ๐ Persistent Volume Claim apiVersion: v1 kind: PersistentVolumeClaim metadata: name: postgres-pvc spec: accessModes: – ReadWriteOnce resources: requests: storage: 10Gi storageClassName: standard — apiVersion: v1 kind: Pod metadata: name: postgres spec: containers: – […]
Kubernetes: Understand Service Types โ ClusterIP, NodePort, LoadBalancer
๐ Internal vs External Access Pods have IPs, but they change. Services provide stable access. Choose the right type: ClusterIP (internal), NodePort (external on node IP), LoadBalancer (cloud load balancer). ๐ Service Types ClusterIP (default): – Internal cluster access only – Virtual IP accessible inside cluster – Use for microservices communicating internally apiVersion: v1 kind: […]
