Skip to content

📚 Table of Contents

  • Chapter 1: Kubernetes Kya Hai, Really? (What is Kubernetes, Really?)
    • 1.1 Tumhare Digital Toys: Containers aur Apps 📦
    • 1.2 K8s: Tumhara Super-Smart Toy Organizer 🧠
    • 1.3 K8s Itna Important Kyun Hai? (Aur Practical Benefits) 🤔
  • Chapter 2: Chalo K8s ke Saath Khelte Hain! (Let's Play with K8s!)
    • 2.1 Tumhara Chhota Playground: Minikube (Setup Assumption) 🏞️
    • 2.2 Pehla Kadam: Kubectl - Tumhari Magic Wand ✨
  • Chapter 3: Tumhare Apps ke Chhote Ghar: Pods 🏡
    • 3.1 Pods Kya Hote Hain? (Like a Small House for your App) 🏠
    • 3.2 Apps ko Chalana: Seedhe Bolo Ya Plan Banao? (Imperative vs. Declarative) 🗣️📝
      • 3.2.1 Seedhe Bolna: Imperative Commands (Quick and Direct) 💬
      • 3.2.2 Plan Banana: Declarative YAML Files (Organized and Repeatable) 📜
  • Chapter 4: Ek Ghar Mein Ek Se Zyaada Dost: Multi-Container Pods 👯
    • 4.1 Sidecar Pattern: Tumhara Helpful Chhota Bhai (Background Helper) 🤖
    • 4.2 Shared Khazana: EmptyDir Volume (Temporary Shared Storage) 🧺
    • 4.3 Port Forwarding: App ko Apne Computer pe Kaise Dekhein? (Making a Tunnel) 🌉
  • Chapter 5: Apps ki Factory: Deployments 🏭
    • 5.1 Deployments Kya Hote Hain? (Like a Toy Factory for your Apps) 🧸
    • 5.2 Apps ki Copies ko Kam Ya Zyaada Karna: Scale Up/Down (Adjusting Production) 📈📉
  • Chapter 6: Naye Version Lana aur Wapas Jaana: Rollout aur Rollback 🔄
    • 6.1 Apps ko Update Karna: Recreate ya RollingUpdate? (Different Ways to Change Clothes) 👗
    • 6.2 Galti Sudharna: Rollback Feature (Going Back in Time) ⏪
  • Chapter 7: Apps ki Apni Communication System: Services 📞
    • 7.1 Services Kya Hote Hain? (Like a Post Office for your Apps) 📬
    • 7.2 Alag-alag Tarah ki Services: ClusterIP, NodePort, LoadBalancer (Different Ways to Connect) 🌐
  • Chapter 8: Apps ki Sehat ka Khayal: Liveness aur Readiness Probes ❤️‍🩹
    • 8.1 Liveness Probe: "Kya App Zinda Hai?" (Is it Breathing?) 🤔
    • 8.2 Readiness Probe: "Kya App Ready Hai Kaam Karne Ke Liye?" (Is it Ready for Customers?) 💡
  • Chapter 9: Apps ke Secret aur Settings: Secrets aur ConfigMaps 🤫📝
    • 9.1 Secrets: Tumhara Secret Locker (Sensitive Data) 🔒
    • 9.2 ConfigMaps: Tumhari Important Notepad (Non-Sensitive Settings) 🗒️
  • Chapter 10: Ek Baar Wale aur Schedule Wale Kaam: Jobs aur CronJobs ⏰
    • 10.1 Jobs: One-Time Homework (Tasks that Run Once) 📚
    • 10.2 CronJobs: Tumhara Daily Alarm (Tasks that Run on Schedule) 🔔
  • Chapter 11: Har Computer Pe Ek App: DaemonSets 🌐
    • 11.1 DaemonSets Kya Hote Hain? (Like Antivirus on Every PC) 🛡️
  • Chapter 12: Data ko Mehfooz Rakhna: Persistent Volumes (PV) aur Persistent Volume Claims (PVC) 💾
    • 12.1 Data ka Magic Hard Drive (Permanent Storage) 🪄
    • 12.2 Simulating an NFS Server for Minikube (Our Fake Storage) 🧪
    • 12.3 PV: Tumhara Storage Room (The Actual Storage Unit) 📦
    • 12.4 PVC: Tumhara Request Form (Asking for Storage) 📝
    • 12.5 Using PVC in Your App (Connecting Storage to Your App) 🔗
  • Chapter 13: Naam Wale Apps aur Unka Khaas Data: StatefulSets 🐾
    • 13.1 StatefulSets Kya Hote Hain? (Like Named Pets with their Own Beds) 🐕
    • 13.2 Headless Service: StatefulSet ka Dost (For Direct Pod Access) 🤝
    • 13.3 Volume Claim Templates: Har Pet ka Apna Bed (Unique Persistent Storage) 🛏️
  • Chapter 14: Apps ko Kahan Rakhna Hai: Node Affinity aur Taint/Toleration 🛋️
    • 14.1 Node Affinity: "Sirf Yahan Baitho!" (Preferring Specific Computers) 🪑
    • 14.2 Taint aur Toleration: "Yahan Mat Aana!" (Keeping Apps Away from Computers) 🚫
  • Chapter 15: Bahar Ki Duniya Se Apps ko Milana: Ingress 🚦
    • 15.1 Ingress Kya Hai? (Like a Theme Park Entrance for your Website) 🎪
    • 15.2 Ingress Controller: The Smart Gatekeeper 👮
    • 15.3 Host File Editing: Your Computer's Phonebook ☎️
  • Chapter 16: K8s ki Control Panel: Dashboard 📊
    • 16.1 Dashboard Kya Hai? (Like a Video Game Scoreboard for your Cluster) 🎮
    • 16.2 Dashboard Login: Getting the Secret Key 🔑
  • Chapter 17: Apps ka App Store: Helm 🛍️
    • 17.1 Helm Kya Hai? (Like Google Play Store for Kubernetes Apps) 📱
    • 17.2 Helm Installation (On Your Computer) 💻
    • 17.3 Important Helm Terms: Charts, Repositories, Releases 🗺️
    • 17.4 Installing a Real App with Helm (Jenkins Example) 🚀
  • Chapter 18: Apna K8s Playground Banana: Kubeadm (Real Cluster Setup - Advanced Overview) 🏗️
    • 18.1 Kubeadm Kya Hai? (Your Cluster Builder Tool) 🛠️
    • 18.2 Simple Steps to Build a Real Cluster (Conceptual) 🧩
  • Chapter 19: Kya Ho Raha Hai Dekhna: Monitoring 👁️
    • 19.1 Prometheus: Tumhara Data Collector (Gathering Information) 📈
    • 19.2 Grafana: Tumhara Smart Screen (Showing Information Visually) 📊
    • 19.3 Installing Prometheus and Grafana with Helm 📦
  • Glossary: Kubernetes Words jo Seekhe! 📖
  • Summary: Kya Seekha aur Aage Kya Karein? 🚀

Chapter 1: Kubernetes Kya Hai, Really? (What is Kubernetes, Really?)

Hello, mere chote scientists! 👋 Humare digital world mein, har din lakho-karodo apps chalte hain. Jab tum YouTube pe videos dekhte ho, ya koi online game khelte ho, ya Google pe kuch search karte ho – in sab ke peeche apps hi chalte hain.

1.1 Tumhare Digital Toys: Containers aur Apps 📦

Imagine karo, tumhare paas bahut saare favourite digital toys hain.

  • Apps: Yeh woh games ya software hain jo tum chalate ho. Jaise: YouTube, Minecraft, tumhara drawing app.

  • Containers: Ab socho, tumhare in digital toys ko chalane ke liye unko sab kuch chahiye hota hai: unke instructions, unke chote-chote parts, unko chalane ke liye power, sab kuch. Agar tum in sab cheezon ko ek chote, air-tight, strong box mein pack kar do, toh woh box "container" ban jayega. 📦

    Real-life analogy: Socho, tumhara favorite video game. Agar woh game sirf ek خاص computer pe chalta hai, toh kya hoga agar woh computer kharab ho jaye? 😥 Game band! Lekin agar tum us game ko ek container mein pack kar do, toh woh container box ab kisi bhi computer pe chal sakta hai, chahe woh tumhare ghar ka computer ho ya internet pe koi bada server. Kyunki us box mein woh saari cheezein hain jo game ko chalane ke liye chahiye. Docker ek bahut popular company hai jo aise containers banane mein help karti hai.

1.2 K8s: Tumhara Super-Smart Toy Organizer 🧠

Jab tumhare paas sirf ek ya do containers hote hain, toh unko manage karna easy hai. Lekin agar tumhare paas 100 containers hain? Ya 1000 containers? Un sab ka khayal kaun rakhega?

  • Kaun dekhega ki saare container boxes theek hain, yaani apps chal rahe hain?
  • Agar koi box toot gaya ya koi app crash ho gaya, toh uski jagah naya box ya app kaun chalayega?
  • Agar suddenly bahut saare log tumhare game ko use karna chahte hain, toh uski aur copies kaun banayega?
  • Aur saare boxes ko kahan rakhna hai, kis computer (server) pe, kaun decide karega?

Yahin pe hamara hero Kubernetes (K8s) aata hai! K8s ek super-smart, jaadui organizer hai.

  • Super-Manager: K8s ek bahut bada manager hai jo tumhare saare container apps ka khayal rakhta hai. Yeh ensure karta hai ki tumhare apps hamesha chalte rahein aur available hon.
  • Smart Worker: Yeh apps ko automatic tareeke se chalata hai, agar koi app kharab ho jaati hai toh use khud theek kar deta hai (jise Self-healing kehte hain), aur agar zyada log app use karein toh uski aur copies bana deta hai (jise Scaling kehte hain).
  • Cloud Computing Analogy: Kya tumne Google Drive ya Dropbox use kiya hai? Jahan tum apni files online save karte ho aur phir unhein kisi bhi computer se (phone, tablet, laptop) access kar sakte ho? K8s bhi kuch aisa hi hai. Tum apne apps ko K8s mein daal dete ho, aur woh phir internet pe chal rahe kisi bhi bade "cloud" computer (jise hum server ya Node kahenge) pe chal sakte hain. Tumhe pata bhi nahi chalta ki kaunse physical computer pe tumhara app chal raha hai, bas woh chalna chahiye! 🌐

1.3 K8s Itna Important Kyun Hai? (Aur Practical Benefits) 🤔

Socho, agar tumhara favourite online game sirf ek hi computer par chal raha hai aur woh computer kharab ho gaya? Game band! 😭 Players gussa ho jayenge! Lekin agar woh game K8s pe chal raha hai, toh K8s use automatically kisi doosre computer pe chalu kar dega. Tumhe pata bhi nahi chalega aur game chalta rahega!

Iske kuch bahut cool aur practical fayde hain:

  • Apps Kabhi Band Nahi Hote (High Availability): Agar cluster mein ek computer (Node) kharab ho gaya ya usmein koi problem aa gayi, toh K8s us computer pe chal rahe apps ko automatically doosre working computer pe shift kar dega ya unki nayi copies chalu kar dega. Tumhara app kabhi band nahi hoga! 🎉 Companies ke liye yeh bahut important hai taaki unke customers hamesha unki services use kar sakein.
  • Zyada Log = Zyada Apps (Automatic Scaling): Tumhara game ya website suddenly bahut popular ho gayi, aur bahut saare log ek saath use karne lag gaye. Agar sirf ek copy hai, toh woh slow ho jayegi ya crash ho jayegi. K8s khud-ba-khud game ki aur copies bana dega taaki sab smoothly khel sakein ya website load ho sake. Aur jab log kam ho jayein, toh K8s extra copies ko band bhi kar sakta hai taaki resources waste na hon. 📈📉
  • Smartly Manage Karta Hai (Efficient Resource Management): K8s dekhta hai ki kis computer pe kitni jagah aur power (CPU, Memory) khali hai, aur phir apps ko wisely unhi computers par rakhta hai jahan woh sabse achha perform kar sakein. Isse companies apne computers ka best use kar paati hain.
  • Naye Updates Aasani Se (Seamless Updates/Rollouts): Tum apne apps mein naye features add kar sakte ho, ya purane bugs fix kar sakte ho. K8s unhein bina kisi rukawat ke update kar dega, ek baar mein saari copies ko band kiye bina. Jaise phone apps update hote hain, lekin tum update ke dauran bhi phone use kar paate ho. 🔄
  • Self-Healing Power: Agar koi app (container) crash ho gaya ya theek se kaam nahi kar raha, toh K8s use automatically restart kar dega. Tumhe jaakar manually theek karne ki zarurat nahi. ❤️‍🩹

Toh, Kubernetes ek bahut powerful aur smart system hai jo digital world ko smoothly chalaane mein aur companies ko apne apps ko manage karne mein help karta hai. Ab hum dekhenge ki hum K8s ke saath khud kaise khel sakte hain! Chalo, next chapter mein! 🤩


Chapter 2: Chalo K8s ke Saath Khelte Hain! (Let's Play with K8s!)

Ab jab tum Kubernetes ke baare mein thoda bahut jaan gaye ho aur uske fayde bhi samajh gaye ho, toh chalo iske saath khelna shuru karte hain! Lekin, itne bade Kubernetes ke playground pe seedhe kaise jayenge? Humein pehle apna chhota sa playground set up karna padega.

2.1 Tumhara Chhota Playground: Minikube (Setup Assumption) 🏞️

Kubernetes ek bahut bada system hai jo bade-bade servers (computers) par chalta hai, jinhein "Nodes" kehte hain. Lekin, usko seekhne ke liye, humein itne bade aur expensive servers ki zarurat nahi hai. Hum apna ek chhota sa playground bana sakte hain apne hi computer par! Is chhote playground ka naam hai Minikube.

Minikube kya hai? Minikube ek special tool hai jo tumhare computer ke andar hi ek chhota sa Kubernetes cluster (yaani ek chhota K8s playground) bana deta hai. Socho jaise tumhare computer mein ek video game console hai, aur uske andar tum games khel rahe ho. Minikube bhi waisa hi hai, yeh tumhare computer ke andar ek virtual computer (virtual machine) banata hai aur usmein Kubernetes ko install kar deta hai. Isse tum K8s ke saath practice kar sakte ho, bina kisi bade server ki zarurat ke.

Important Note: Is ebook mein, hum assume kar rahe hain ki tumhare computer par Minikube aur Kubectl (jo hum next section mein discuss karenge) pehle se installed hain. Agar nahi hain, toh tumhe pehle unhein install karna hoga. Tum apne parents ya teacher ki help le sakte ho, ya Minikube ki official website (https://minikube.sigs.k8s.io/docs/start/) pe jaakar instructions follow kar sakte ho.

Step 1: Minikube Start Karo Pehle apna Minikube playground chalu kar lo, agar woh band hai toh. Yeh tumhare terminal (command prompt ya PowerShell ya Git Bash) mein type karna hoga:

bash
minikube start

Explanation:

  • minikube start: Yeh command Minikube ko chalu karta hai.
  • What happens: Jab tum yeh command dete ho, Minikube tumhare computer pe ek chhota sa virtual computer banata hai (agar pehle se nahi bana ho) aur usmein Kubernetes ke saare zaruri components ko chalu karta hai.
  • Time taken: Ismein thoda time lag sakta hai, jaise koi bada game load hone mein time lagta hai. Tumhein Starting minikube..., Creating Kubernetes ..., Done! kubectl is now configured to use "minikube" jaise messages dikhenge.
  • Result: Jab yeh successfully start ho jayega, toh tumhara chhota Kubernetes playground ready hoga! Tumhein kubectl is now configured to use "minikube" message dikhega, jo matlab hai ki ab tum kubectl command se apne Minikube cluster se baat kar sakte ho. 😊

Step 2: Minikube Band Karo (Optional, for later use) Jab tumhara khel khatam ho jaye, toh tum Minikube ko band bhi kar sakte ho. Isse tumhare computer ke resources (memory, CPU) free ho jayenge.

bash
minikube stop

Explanation:

  • minikube stop: Yeh command Minikube ko temporarily band kar deta hai.
  • What happens: Jab tum Minikube ko stop karte ho, toh woh "so" jaata hai, aur tumhara computer uski memory aur CPU ka use nahi karta.
  • Result: Jab tum use minikube start se phir chalu karoge, toh woh wahi se shuru hoga jahan se chhoda tha, bina saare components ko naye sire se install kiye.

Step 3: Minikube Ko Hamesha Ke Liye Delete Karo (Optional, for complete cleanup) Agar tum Minikube ko completely apne computer se hatana chahte ho (jaise kisi game ko uninstall karte ho), toh yeh command use karte hain:

bash
minikube delete

Explanation:

  • minikube delete: Yeh command Minikube ko tumhare computer se puri tarah se mita deta hai.
  • What happens: Isse Minikube ka banaaya hua virtual computer aur uske saare files delete ho jaate hain. Yeh tabhi use karo jab tum Minikube ko phir se naye sire se install karna chahte ho ya uski zarurat nahi hai.
  • Result: Agli baar minikube start karne par, woh naya virtual computer banayega.

2.2 Pehla Kadam: Kubectl - Tumhari Magic Wand ✨

Ab jab tumhara playground (Minikube) ready hai, toh usmein commands kaise doge? Tumhe chahiye ek special magic wand! Is magic wand ka naam hai Kubectl.

Kubectl kya hai?Kubectl (pronounced: koob-sek-tel) ek command-line tool hai. Yeh tumhare commands ko Kubernetes cluster tak pahunchata hai. Socho, jaise tumhare paas ek remote control hai aur usse tum TV ko control karte ho. Kubectl bhi waisa hi hai, yeh tumhara remote control hai Kubernetes cluster ke liye.

  • Tum Kubectl se kehte ho "Ek app chalao!"
  • Ya "Yeh app kitni copies chal rahi hain?"
  • Ya "Iss app mein kya error hai?"
  • Aur Kubectl woh baat Kubernetes ko samjha deta hai aur tumhe uska answer deta hai.

Step 1: Apne Cluster ke Nodes Dekho Jab Minikube chal raha ho (check kar lo minikube status se), toh tum Kubectl se apne playground ke baare mein pooch sakte ho. Chalo dekhte hain ki tumhare playground mein kitne bade computers (Nodes) hain:

bash
kubectl get nodes

Explanation:

  • kubectl: Yeh hamari magic wand (command-line tool) hai.
  • get: Iska matlab hai "mujhe jankari do" ya "list karo".
  • nodes: Kis cheez ki jankari chahiye? Nodes ki. Nodes woh bade computers hote hain jahan tumhare apps (containers) chalte hain.
  • What happens: Yeh command tumhare Kubernetes playground mein kitne Nodes hain, unki list dikhayega.
  • Result: Minikube mein usually ek hi node hota hai, jiska naam aksar 'minikube' hi hota hai. Tumhein uska status Ready dikhna chahiye, matlab woh kaam karne ke liye bilkul taiyar hai! 👍
    NAME       STATUS   ROLES           AGE     VERSION
    minikube   Ready    control-plane   5m2s    v1.26.3
    Yeh dikhata hai ki tumhara K8s playground properly chal raha hai aur minikube naam ka Node ready hai.

Toh, ab tum apne Kubernetes playground ko chalu karna aur usse baat karna seekh gaye ho. Next chapter mein hum apne apps ko in "Nodes" par chalana seekhenge, Kubectl ki madad se! Ready ho? 🚀


Chapter 3: Tumhare Apps ke Chhote Ghar: Pods 🏡

Chalo, ab hum apne apps ko Kubernetes ke playground mein chalane ki taiyari karte hain. Har app ko chalane ke liye ek chhota sa ghar chahiye hota hai. Kubernetes mein, is chhote ghar ko Pod kehte hain.

3.1 Pods Kya Hote Hain? (Like a Small House for your App) 🏠

Socho, tumne ek chhota sa game banaya, ya ek website banayi. Is game ya website (jo ki ab ek container mein packed hai) ko chalane ke liye tumhe ek jagah chahiye Kubernetes mein. Woh jagah ek Pod hoti hai.

  • Pod: Pod ek sabse chhota building block hai Kubernetes mein. Yeh ek ya ek se zyada containers ko apne andar rakhta hai. Generally, ek Pod mein sirf ek hi main app container hota hai.
  • House Analogy: Pod ek chhota sa ghar hai. Is ghar mein tumhara app (container) rehta hai. Yeh ghar app ko chalane ke liye zaruri saari cheezein provide karta hai, jaise network, storage.
  • Unique IP Address: Har Pod ka apna ek unique phone number (IP address) hota hai, jisse doosre apps (doosre Pods) usse baat kar sakte hain.
  • One Node, One Pod (at a time): Ek Pod hamesha ek hi bade computer (Node) par chalta hai. Woh ek Node se doosre Node pe khud-ba-khud switch nahi karta jab tak woh delete na ho aur naya Pod kisi doosre Node pe na bane.

3.2 Apps ko Chalana: Seedhe Bolo Ya Plan Banao? (Imperative vs. Declarative) 🗣️📝

Apps ko Pods mein chalane ke do main tareeke hain, jaise koi kaam karne ke do tareeke hote hain:

  1. Seedhe Bolo (Imperative Way): Tum Kubectl (magic wand) se seedha bolte ho "Yeh app chala do!" Jaise tum seedha apne dost ko bolte ho "Ball feko!"
    • Best for: Quick tests, one-time tasks, ya jab tumhe kisi existing app mein chhota sa change karna ho.
  2. Plan Banao (Declarative Way): Tum ek detailed plan banate ho (ek file mein likhte ho) ki "Yeh app aise chalna chahiye, iska yeh naam hona chahiye, isko yeh-yeh settings chahiye." Phir tum Kubectl se kehte ho "Yeh plan execute kar do." Jaise tum apne dost ko ek list dete ho "Yeh saare kaam karne hain."
    • Best for: Big projects, complex setups, jab tumhe changes ko track karna ho, ya configuration ko baar-baar use karna ho.

Dono tareeke achhe hain, lekin alag-alag situations ke liye. Hum dono tareeke seekhenge!

3.2.1 Seedhe Bolna: Imperative Commands (Quick and Direct) 💬

Yeh tareeka tab achha hai jab tumhe jaldi se kuch test karna ho ya ek hi baar koi chhota sa app chalana ho.

Step 1: Minikube Start Karo (Agar Band Hai Toh) Pehle apna Minikube playground chalu kar lo, agar woh band hai toh. Agar Minikube already running hai, toh yeh step skip kar sakte ho.

bash
minikube start

Explanation:

  • This command starts your Minikube local Kubernetes cluster. Make sure it shows kubectl is now configured to use "minikube" once finished.

Step 2: Hamara Pehla Pod Chalao Ab, hum Kubectl se seedha bolenge ki ek Pod chalao. Hum 'nginx' naam ka ek popular web server app chalayenge. Nginx ek light-weight (chhota) web server hai, jo internet pages dikhane ke kaam aata hai.

bash
kubectl run mera-pehla-pod --image=nginx:latest --restart=Never

Explanation:

  • kubectl run: Yeh Kubectl ko batata hai ki ek naya application (Pod) chalao.
  • mera-pehla-pod: Yeh hamare Pod ka naam hai. Tum koi bhi naam de sakte ho jo tumhe pasand ho, jaise my-first-game.
  • --image=nginx:latest: Yeh batata hai ki kaunsa app (container image) chalana hai.
    • nginx: Yeh app ka naam hai, jo ek web server hai.
    • :latest: Yeh nginx app ka version hai. latest matlab uska sabse naya version.
    • Analogy: Socho, jaise tum App Store se Minecraft game download karte ho, nginx game ka naam hai aur latest uska version hai. Yeh app DockerHub se download hoga, jo apps ka ek online store hai.
  • --restart=Never: Yeh batata hai ki agar yeh app ek baar chal ke successfully band ho jaye ya koi galti (crash) ho jaye, toh Kubernetes usko phir se automatically chalu mat karna. Yeh setting Jobs ke liye useful hoti hai (jo hum aage seekhenge). Deployments (aage seekhenge) usually Always restart policy use karte hain.
  • What happens: Kubernetes ko yeh command milega, woh nginx:latest image ko download karega (agar pehle se nahi hai), aur us image se mera-pehla-pod naam ka ek Pod bana kar chalayega.
  • Result: pod/mera-pehla-pod created jaisa message dikhega.

Step 3: Dekho Pod Chal Raha Hai Ya Nahi Pod chalu hua ya nahi, aur uski current status kya hai, yeh dekhne ke liye:

bash
kubectl get pods

Explanation:

  • kubectl get pods: Yeh command tumhare Kubernetes cluster mein chal rahe saare Pods ki list dikhayega.
  • What happens: Kubectl cluster se saare Pods ki current status poochhega.
  • Result: Tumhara mera-pehla-pod yahan dikhna chahiye, aur uski STATUS Running honi chahiye (jab tak woh puri tarah se start ho jaye).
    NAME              READY   STATUS    RESTARTS   AGE
    mera-pehla-pod    1/1     Running   0          20s
    • NAME: Pod ka naam.
    • READY: 1/1 matlab 1 container chal raha hai Pod ke andar (aur ready hai), out of 1 container.
    • STATUS: Pod ki current halat. Running matlab sab theek hai. Dusre status bhi ho sakte hain jaise ContainerCreating (abhi ban raha hai), Pending (wait kar raha hai), Error (kuch problem hai).
    • RESTARTS: Kitni baar Pod restart hua hai (agar crash hua ho).
    • AGE: Kitni der se Pod chal raha hai.

Step 4: Pod Ki Zyaada Jankari Dekho (Troubleshooting ke liye) Agar Pod mein koi problem hai ya tumhe uske baare mein aur detailed information jaan na hai (jaise woh kis computer pe chal raha hai, kaunsa image use kar raha hai, koi errors ya warnings hain kya), toh describe command use karte hain:

bash
kubectl describe pod mera-pehla-pod

Explanation:

  • kubectl describe pod mera-pehla-pod: Yeh command mera-pehla-pod ke baare mein saari detailed information dikhayega.
  • What happens: Kubectl cluster se Pod ke saare configuration details aur uske latest events (kya-kya hua hai us Pod ke saath, jaise image pull kiya, container started) fetch karega.
  • Result: Tumhein ek lambi output dikhegi jismein IP Address, Node (jis computer pe chal raha hai), Events (jaise Pulled image, Created container, Started container), aur bahut saari technical details hongi. Events section bahut useful hota hai jab koi problem hoti hai Pod mein.
    Name:             mera-pehla-pod
    Namespace:        default
    ...
    IP:               172.17.0.3
    Node:             minikube/192.168.49.2
    ...
    Events:
      Type    Reason     Age   From               Message
      ----    ------     ----  ----               -------
      Normal  Pulled     2m    kubelet, minikube  Container image "nginx:latest" already present on machine
      Normal  Created    2m    kubelet, minikube  Created container mera-pehla-container
      Normal  Started    2m    kubelet, minikube  Started container mera-pehla-container

Step 5: Pod Ke Logs Dekho (Debugging ke liye) Apps (containers) apne logs generate karte hain, jaise tumhare computer mein programs ki activities record hoti hain. Agar koi app theek se kaam nahi kar raha, toh uske logs dekhna bahut useful hota hai.

bash
kubectl logs mera-pehla-pod

Explanation:

  • kubectl logs mera-pehla-pod: Yeh command mera-pehla-pod ke andar chal rahe container ke logs dikhayega.
  • What happens: Kubectl Pod ke logs ko fetch karega.
  • Result: Nginx web server ke liye, tumhe uski startup messages aur access logs dikhenge (agar koi usko access kare).
    /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to execute files in order:
    /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
    /docker-entrypoint.d/20-envsubst-on-templates.sh
    /docker-entrypoint.d/30-tune-worker-processes.sh
    ... (Nginx server started messages) ...

Step 6: Pod Ke Live Logs Dekho (-f flag) Agar tumhe logs real-time mein dekhne hain, jaise koi live show dekhte ho, toh -f (follow) flag use karte hain:

bash
kubectl logs -f mera-pehla-pod

Explanation:

  • kubectl logs -f mera-pehla-pod: Yeh command mera-pehla-pod ke logs ko live stream karega.
  • What happens: Naye log messages aate hi tumhare terminal pe dikhte rahenge.
  • To Stop: Live logs dekhna band karne ke liye, Ctrl+C (Control + C) press karo.

Step 7: Pod Ke Andar Command Chalao Tum Pod ke andar jaakar commands bhi chala sakte ho, jaise ls (files dekhne ke liye) ya hostname. Yeh tab useful hota hai jab tumhe Pod ke andar kuch check karna ho ya debug karna ho.

bash
kubectl exec mera-pehla-pod -- hostname

Explanation:

  • kubectl exec: Yeh Pod ke andar ek command chalata hai.
  • mera-pehla-pod: Us Pod ka naam jiske andar command chalani hai.
  • --: Iske baad jo bhi likhoge, woh Pod ke andar ek command ban jayega. Yeh --Kubectl ko batata hai ki iske baad ke arguments command ke liye hain, na ki kubectl exec ke liye.
  • hostname: Yeh command Pod ka hostname (computer ka naam) batayega (jo ki aksar Pod ka apna ID hota hai).
  • Result: Tumhein Pod ka hostname dikhega, jaise mera-pehla-pod.

Step 8: Pod Ke Andar Enter Karo (Interactive Terminal Access) Agar tumhe Pod ke andar puri tarah se ghusna hai, jaise tum apne computer ka terminal use karte ho, toh -it flags use karte hain:

bash
kubectl exec -it mera-pehla-pod -- bash

Explanation:

  • -i: Iska matlab hai "interactive", yani tum Pod ke andar commands type kar paoge aur woh Pod un commands ko run karega.
  • -t: Iska matlab hai "tty" (terminal), jo ek proper terminal experience deta hai, jaise colors aur backspace support.
  • -- bash: Iska matlab hai Pod ke andar bash shell (ek type ka command interpreter) chalu karo. Agar bash nahi mile, toh sh (shell) use kar sakte ho: kubectl exec -it mera-pehla-pod -- sh.
  • What happens: Tum Pod ke andar login ho jaoge aur uska command prompt dikhega. Ab tum Pod ke andar ki files explore kar sakte ho, programs chala sakte ho, jaise ls / (root directory mein files dekhne ke liye).
  • To Exit: Pod se bahar aane ke liye, exit type karke Enter press karo, ya Ctrl+P then Ctrl+Q press karo (yeh Pod ko chalte rehne dega background mein, sirf terminal disconnect karega).

Step 9: Pod Ko Delete Karo Jab tumhara kaam khatam ho jaye, toh Pod ko delete kar do. Yaad rakhna, kubectl run se banaya gaya Pod Deployment se managed nahi hota (hum Deployments chapter 5 mein seekhenge).

bash
kubectl delete pod mera-pehla-pod

Explanation:

  • kubectl delete pod mera-pehla-pod: Yeh command mera-pehla-pod ko Kubernetes playground se delete kar dega.
  • What happens: Kubernetes mera-pehla-pod ko stop karega aur usko cluster se hata dega.
  • Result: pod "mera-pehla-pod" deleted jaisa message dikhega. Tum kubectl get pods chala ke confirm kar sakte ho.

Imperative tareeka achha hai jab tumhe jaldi se kuch test karna ho. Lekin agar tumhe bahut saare Pods banani hain, ya unke detailed settings karne hain, ya unko automatically manage karna hai, toh yeh mushkil ho jayega. Isliye, hum Declarative tareeka dekhenge next section mein! Yeh zyada professional aur organized hai.

3.2.2 Plan Banana: Declarative YAML Files (Organized and Repeatable) 📜

Declarative tareeke mein, hum apne Pods (aur dusre Kubernetes objects) ki puri details ek file mein likhte hain. Is file ko YAML file (pronounced: yah-muhl) kehte hain. YAML files bahut easy hoti hain padhne aur likhne mein. Isse tumhare configurations ko manage karna aur version control (changes ko track karna) easy ho jaata hai.

Step 1: Pod Ki YAML File Banao Apne computer pe ek new file banao, uska naam do first-app-pod.yaml (ya koi bhi naam jo tumhe pasand ho, jaise my-game-config.yaml). Is file ko kisi simple text editor (jaise Notepad, VS Code, Sublime Text) mein open karo aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct, YAML is very sensitive to spaces!

yaml
# File: first-app-pod.yaml

# Yeh batata hai ki hum Kubernetes ka kaunsa API version use kar rahe hain.
# 'v1' Pods, Services, aur Secrets jaise basic objects ke liye hota hai.
apiVersion: v1

# Yeh batata hai ki hum kya bana rahe hain. Yahan hum ek 'Pod' bana rahe hain.
kind: Pod

# 'metadata' section mein object ke baare mein jankari hoti hai, jaise uska naam aur labels.
metadata:
  # Hamare Pod ka naam. Yeh naam unique hona chahiye ek namespace ke andar.
  name: my-first-declarative-pod
  # 'labels' Pod ko categorize karne ke liye tags hote hain.
  # Socho, jaise tum apne khilone pe sticker lagaate ho 'car' ya 'truck' ya 'red'.
  # In labels se hum Pods ko baad mein aasani se dhundh sakte hain ya group kar sakte hain.
  labels:
    app: frontend-web
    environment: development

# 'spec' (specification) section mein Pod ke andar kya-kya hoga, uski detailed settings hoti hain.
# Yahan hum define karte hain ki Pod mein kaun-kaun se containers chalenge.
spec:
  # 'containers' ek list hoti hai Pod ke andar chalne wale containers ki.
  # Har container ki apni settings hoti hain.
  containers:
  # Ek single dash '-' matlab yeh ek naya item hai list mein.
  - # Pehle container ka naam. Yeh naam Pod ke andar unique hona chahiye.
    name: nginx-web-server
    # Kaunsa Docker image use karna hai. 'nginx:latest' matlab 'nginx' web server ka sabse naya version.
    # Kubernetes yeh image DockerHub (ek online image store) se download karega.
    image: nginx:latest
    # 'ports' batate hain ki container ke andar kaunse network ports open honge.
    # Jaise ghar ka door number jahan se log andar aa sakte hain.
    ports:
    - # 'containerPort' woh port hai jo container ke andar app use kar raha hai.
      # Nginx web server default roop se port 80 pe chalta hai.
      containerPort: 80
    # 'env' (environment variables) app ke andar settings ko pass karne ke liye use hote hain.
    # Jaise tumhare computer mein SYSTEM_PATH ya HOME directory settings hoti hain.
    env:
      # 'name' environment variable ka naam hai.
      - name: APP_ENVIRONMENT
        # 'value' us environment variable ki value hai.
        value: "Dev"
      - name: APP_VERSION
        value: "1.0"

Explanation (YAML file ke har section ki simplified jankari):

  • apiVersion: v1: Yeh batata hai ki yeh file Kubernetes ke kis "version" ya "bhasha" mein likhi hai. v1 Pods aur Services jaise basic cheezon ke liye standard hai.
  • kind: Pod: Yeh batata hai ki is file se hum kya banana chahte hain. Yahan hum ek Pod bana rahe hain, jo app ke chhote ghar jaisa hai.
  • metadata:: Is section mein us cheez ke baare mein jankari hoti hai jo hum bana rahe hain.
    • name: my-first-declarative-pod: Yeh hamare Pod ka naam hai. Yeh naam cluster mein unique hona chahiye.
    • labels:: Yeh Pod ko diye gaye "tags" hain. Jaise tum apne toys pe stickers lagaate ho car ya doll ya red color. app: frontend-web aur environment: development do labels hain. In labels se hum Pods ko baad mein aasani se dhundh sakte hain ya group kar sakte hain.
  • spec: (specification): Is section mein detail mein bataya jaata hai ki Pod ko kya karna hai, uske andar kya-kya hoga.
    • containers:: Ek Pod ke andar ek ya zyada containers ho sakte hain. Yahan hum bata rahe hain ki kaunse containers chalenge.
    • - name: nginx-web-server: Yeh pehle container ka naam hai, jo humne nginx-web-server rakha hai.
    • image: nginx:latest: Yeh batata hai ki is container mein kaunsa app chalega. nginx ek popular web server software hai, aur :latest matlab uska sabse naya version. Kubernetes is app ki image ko DockerHub (jahan bahut saare apps store hote hain) se download karega.
    • ports:: Yeh batata hai ki container ke andar kaunse network ports (communication channels) open honge, jaise ghar ka door number.
      • - containerPort: 80: nginx web server default roop se port 80 pe listen karta hai (yani requests sunta hai).
    • env:: Ismein hum environment variables (choti-choti settings) define karte hain jo app ke andar available hongi.
      • - name: APP_ENVIRONMENT: Yeh ek environment variable ka naam hai.
      • value: "Dev": Yeh us APP_ENVIRONMENT variable ki value hai.
      • Dusra variable APP_VERSION bhi define kiya hai.

Step 2: YAML File Ko Apply Karo Ab Kubectl ko bolo ki is first-app-pod.yaml file mein likhe hue plan ko execute karo aur Pod banao:

bash
kubectl apply -f first-app-pod.yaml

Explanation:

  • kubectl apply: Yeh command YAML file mein likhe hue plan ko Kubernetes cluster mein apply karta hai (yani bana deta hai ya update karta hai).
  • -f: Iska matlab hai "file", yani iske baad jo naam hai (yahan first-app-pod.yaml) woh ek file hai jiske andar plan likha hai.
  • What happens: Kubectl first-app-pod.yaml file ko padhega, usmein likhe Pod ki details ko Kubernetes API server ko bhejega. API server woh details save karega, aur phir Kubernetes scheduler aur kubelet Pod ko banane aur chalane ka kaam shuru kar denge.
  • Result: pod/my-first-declarative-pod created jaisa message dikhega.

Step 3: Pod Ki Status Dekho Pod chalu hua ya nahi, aur uski status kya hai, yeh dekhne ke liye:

bash
kubectl get pods

Explanation:

  • kubectl get pods: Yeh command saare Pods ki list dikhayega.
  • Result: Tumhara my-first-declarative-pod yahan Running status mein dikhna chahiye (jab tak woh puri tarah se start ho jaye). READY column 1/1 hona chahiye.

Step 4: Pod Ke Environment Variables Verify Karo Humne Pod ki YAML file mein APP_ENVIRONMENT aur APP_VERSION environment variables define kiye the. Chalo, check karte hain ki woh Pod ke andar available hain ya nahi.

Pehle, Pod ke andar ek interactive terminal session open karo:

bash
kubectl exec -it my-first-declarative-pod -- bash

Explanation:

  • kubectl exec -it my-first-declarative-pod -- bash: This command opens a shell (terminal) inside our Pod. my-first-declarative-pod is our Pod's name.

Ab jab tum Pod ke andar ho, printenv command chalao aur usmein se hamare variables ko filter karo:

bash
# Jab Pod ke andar ho, yeh command type karo:
printenv | grep APP_

Explanation:

  • printenv: Yeh command Pod ke andar saare environment variables ko print karta hai.
  • | grep APP_: | (pipe) ka matlab hai, printenv ke output ko grep command ko do. grep APP_ un lines ko dhundhega jinmein APP_ likha ho.
  • Result: Tumhein APP_ENVIRONMENT=Dev aur APP_VERSION=1.0 dikhne chahiye, matlab environment variables successfully Pod mein pass ho gaye hain! 🎉
    APP_ENVIRONMENT=Dev
    APP_VERSION=1.0

Step 5: Pod Ko Delete Karo Jab kaam khatam ho jaye, toh Pod ko delete kar do. Declarative tareeke mein delete karna bhi usi YAML file se hota hai:

bash
kubectl delete -f first-app-pod.yaml

Explanation:

  • kubectl delete -f first-app-pod.yaml: Yeh command first-app-pod.yaml file mein define kiye gaye saare Kubernetes objects (yahan sirf Pod) ko delete kar dega.
  • What happens: Kubernetes my-first-declarative-pod ko stop karega aur cluster se hata dega.
  • Result: pod "my-first-declarative-pod" deleted jaisa message dikhega. Tum kubectl get pods chala ke confirm kar sakte ho.

Toh, Imperative (seedhe bolna) aur Declarative (plan banana) dono tareeke important hain. Bade projects mein Declarative tareeka zyaada use hota hai kyunki ismein saara plan ek file mein likha hota hai, jise manage karna, track karna aur doosron ke saath share karna easy hota hai.

Ab chalte hain next chapter pe jahan hum seekhenge ki ek hi Pod mein ek se zyada apps (containers) kaise chalaate hain! 👬


Chapter 4: Ek Ghar Mein Ek Se Zyaada Dost: Multi-Container Pods 👯

Pichhle chapter mein humne dekha ki ek Pod mein ek app (container) kaise chalate hain. Lekin kabhi-kabhi, tumhare ek main app ko help karne ke liye ek chhota sa helper app bhi chahiye hota hai. Socho, jaise tumhara game chal raha hai (main app), aur background mein ek chhota robot (helper app) hai jo game ke scores ko save kar raha hai ya naye levels download kar raha hai.

Kubernetes mein, hum ek ji Pod ke andar ek se zyada containers chala sakte hain. Isko Multi-Container Pod kehte hain. Iska ek popular example hai Sidecar Pattern.

4.1 Sidecar Pattern: Tumhara Helpful Chhota Bhai (Background Helper) 🤖

Sidecar kya hai? Ek Sidecar container ek main application container ke saath uski help ke liye chalta hai. Yeh dono containers ek hi Pod ke andar hote hain. Iska matlab hai:

  • Ek Hi Ghar Mein: Dono containers ek hi Pod mein rehte hain. Jaise tum aur tumhara chhota bhai ek hi room mein rehte ho.
  • Same IP Address: Dono containers ka phone number (IP address) same hota hai, toh woh ek doosre se easily baat kar sakte hain. Jaise tum aur tumhara bhai ek hi phone number share karte ho.
  • Shared Khazana (Shared Volume): Dono containers ek ji common storage area (jise Volume kehte hain) ko use kar sakte hain, jahan woh files share kar sakte hain. Socho, jaise tum aur tumhara chhota bhai ek hi almari share karte ho, jahan tum apni-apni cheezein rakhte ho.

Real-Life Example: Ek website ka example lete hain. Tumhari website ka content (HTML files, images) ek web server (jaise Nginx) dikhata hai. Ab socho, agar tumhari website pe naya content internet se download karna ho, toh woh kaun karega? Hum ek Sidecar container bana sakte hain jo internet se naya content download karega, aur usko us shared jagah pe rakhega jahan Nginx server usko utha kar users ko dikha sake.

Step 1: Multi-Container Pod Ki YAML File Banao Apne computer pe ek new file banao, uska naam do multicontainer-app.yaml. Is file ko text editor mein open karo aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct!

yaml
# File: multicontainer-app.yaml

# API version for Pods
apiVersion: v1
# Type of Kubernetes object: Pod
kind: Pod
# Metadata for the Pod
metadata:
  # Name of our multi-container Pod
  name: website-updater-pod
# Specification for the Pod
spec:
  # List of containers that will run inside this Pod
  containers:
  # First container: our main web server (Nginx)
  - name: web-server-nginx
    # Image for the web server
    image: nginx
    # Ports that this container exposes
    ports:
      - containerPort: 80 # Nginx runs on port 80 inside the container
    # Volumes that this container will mount (connect)
    volumeMounts:
    - name: shared-html-volume # Name of the volume to mount (defined below)
      # Path inside the container where Nginx serves web pages from
      mountPath: /usr/share/nginx/html
  
  # Second container: our helper sidecar (Busybox)
  # This sidecar will download website content
  - name: content-downloader-sidecar
    # Image for the sidecar, Busybox is a small toolkit with basic commands
    image: busybox
    # Command to run inside the Busybox container
    command: ["/bin/sh"] # Start a shell interpreter
    # Arguments for the command. This will run a loop.
    args:
    - "-c" # Execute the following string as a command
    - "while true; do wget -O /var/log/index.html https://raw.githubusercontent.com/omerbsezer/Fast-Kubernetes/main/index.html; sleep 15; done"
    # Explanation of args:
    # `while true; do ... ; done`: This creates an infinite loop.
    # `wget -O /var/log/index.html ...`: Downloads the `index.html` file from the given URL.
    # `-O /var/log/index.html`: Saves the downloaded content to `/var/log/index.html`.
    # `https://raw.githubusercontent.com/omerbsezer/Fast-Kubernetes/main/index.html`: The URL from where to download the content.
    # `sleep 15`: Waits for 15 seconds before running the loop again.
    
    # Volumes that this container will mount (connect)
    volumeMounts:
    - name: shared-html-volume # Same volume as the Nginx container
      # Path inside the sidecar container where it will save the downloaded file
      mountPath: /var/log
  
  # Definition of the volumes used by the Pod
  volumes:
  # This is an "emptyDir" type volume.
  # It creates an empty directory when the Pod starts, and deletes it when the Pod is removed.
  # It's great for sharing data temporarily between containers in the same Pod.
  - name: shared-html-volume # Name of our shared volume
    emptyDir: {} # This defines an empty directory, a temporary shared storage

Explanation (YAML file ke har section ki simplified jankari):

  • kind: Pod: Hum ek Pod bana rahe hain.
  • metadata: name: website-updater-pod: Hamare Pod ka naam website-updater-pod hai.
  • spec: containers:: Is Pod mein do containers hain:
    • - name: web-server-nginx: Yeh hamara main container hai.
      • image: nginx: Yeh Nginx web server ka image use karta hai.
      • ports: - containerPort: 80: Nginx app Pod ke andar port 80 pe chalega.
      • volumeMounts: - name: shared-html-volume: Yeh container shared-html-volume naam ke volume ko mount karega.
      • mountPath: /usr/share/nginx/html: Nginx server is path se web pages dikhata hai, toh humne volume ko yahin mount kiya hai.
    • - name: content-downloader-sidecar: Yeh hamara helper container hai, jise Sidecar kehte hain.
      • image: busybox: Yeh busybox image use karta hai, jo ek chhota sa toolkit hai jismein bahut saare basic commands hote hain.
      • command: ["/bin/sh"] aur args: ["-c", "while true; do wget -O ... ; sleep 15; done"]: Yeh commands batate hain ki sidecar har 15 seconds mein wget command se internet se index.html file download karega.
      • volumeMounts: - name: shared-html-volume: Yeh sidecar bhi shared-html-volume ko mount karega.
      • mountPath: /var/log: Sidecar downloaded index.html file ko /var/log path pe save karega (jo ki shared volume mein hai).
  • volumes: - name: shared-html-volume: Yahan hum shared-html-volume ko define kar rahe hain.
    • emptyDir: {}: Iska type emptyDir hai. Yeh ek temporary shared folder hai. Jab website-updater-pod banega, tab yeh folder bhi banega. Jab website-updater-pod delete hoga, tab yeh folder aur uske andar ka saara data bhi delete ho jayega.

4.2 Shared Khazana: EmptyDir Volume (Temporary Shared Storage) 🧺

EmptyDir Volume kya hai?emptyDir (yani "khali directory") ek temporary storage area hai. Socho, jaise tumne drawing karne ke liye ek khali paper liya. Jab drawing khatam ho gayi aur paper throw kar diya, toh uski memory bhi chali gayi. emptyDir volume Pod ke create hote hi ban jaata hai aur Pod ke delete hote hi gayab ho jaata hai. Yeh Pod ke andar chal rahe containers ke beech data share karne ke liye best hai.

Hamare example mein:

  • content-downloader-sidecar container index.html file internet se download karega aur use shared-html-volume ke /var/log path pe save karega.
  • Kyunki shared-html-volume web-server-nginx container ke /usr/share/nginx/html path pe bhi mount hai, web-server-nginx us index.html file ko utha kar logon ko dikha payega. Iska matlab hai ki Sidecar ne content download kiya aur Nginx ne us content ko display kar diya, dono ne emptyDir volume ke through data share kiya.

Step 2: Multi-Container Pod Ko Apply Karo Ab Kubectl ko bolo ki is multicontainer-app.yaml file mein likhe hue plan ko execute karo:

bash
kubectl apply -f multicontainer-app.yaml

Explanation:

  • kubectl apply -f multicontainer-app.yaml: This command creates the website-updater-pod as defined in the YAML file.
  • Result: pod/website-updater-pod created message dikhega.

Step 3: Pod Ki Status Dekho Pod chalu hua ya nahi, yeh dekhne ke liye:

bash
kubectl get pods

Explanation:

  • kubectl get pods: This command lists all running pods.
  • Result: Tumhara website-updater-pod ko Running status mein dekhoge. READY column 2/2 dikhna chahiye, matlab dono containers (Nginx aur Busybox Sidecar) chal rahe hain aur ready hain.

Step 4: Sidecar Container Ke Logs Dekho (Content Download ho raha hai kya?) Chalo dekhte hain ki hamara content-downloader-sidecar actually content download kar raha hai ya nahi. Hum uske logs dekhenge.

bash
kubectl logs -f website-updater-pod -c content-downloader-sidecar

Explanation:

  • kubectl logs: Logs dekhne ka command.
  • -f: follow flag, matlab live logs dekho.
  • website-updater-pod: Hamare Pod ka naam.
  • -c content-downloader-sidecar: Yeh bahut important hai! Kyunki hamare Pod mein do containers hain, hamein specify karna padta hai ki kis container ke logs dekhne hain. -c flag container ka naam batata hai.
  • What happens: Tumhe wget commands ke output dikhenge, jismein index.html file download hone ke messages honge. Har 15 seconds mein yeh process repeat hota dikhega.
    --2023-10-27 10:30:00--  https://raw.githubusercontent.com/omerbsezer/Fast-Kubernetes/main/index.html
    Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ...
    Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.
    HTTP request sent, awaiting response... 200 OK
    Length: 461 [text/html]
    Saving to: '/var/log/index.html'
    
    /var/log/index.html 100% |*******************************|   461  --.-KB/s    eta 0s
    
    2023-10-27 10:30:00 (6.13 MB/s) - '/var/log/index.html' saved [461/461]
  • To Stop: Ctrl+C press karke logs dekhna band kar do.

Step 5: Nginx Container Ke Andar Jao aur Shared Content Dekho Ab, hum web-server-nginx container ke andar jaakar check karenge ki kya usko index.html file mili hai jo sidecar ne download ki thi.

bash
kubectl exec -it website-updater-pod -c web-server-nginx -- ls /usr/share/nginx/html

Explanation:

  • kubectl exec -it website-updater-pod -c web-server-nginx -- ls /usr/share/nginx/html: This command opens a shell inside the web-server-nginx container and runs ls /usr/share/nginx/html.
  • Result: Tumhe index.html file dikhegi! 🎉 Iska matlab hai ki emptyDir volume successfully data share kar raha hai Nginx aur Sidecar ke beech.
    index.html

4.3 Port Forwarding: App ko Apne Computer pe Kaise Dekhein? (Making a Tunnel) 🌉

Ab, hum is website ko apne computer ke browser mein dekhna chahte hain. Website web-server-nginx container mein chal rahi hai, jo ki Pod ke andar hai. Hum apne computer se seedha Pod tak nahi pahunch sakte. Iske liye hum Port Forwarding use karenge.

Port Forwarding kya hai? Port Forwarding ek temporary "tunnel" banata hai. Yeh tumhare computer ke ek port (jaise 8080) ko Pod ke andar chal rahe app ke ek port (jaise 80) se jod deta hai. Socho, jaise tumhare paas ek walkie-talkie hai. Tum ek walkie-talkie apne computer pe rakhte ho aur doosra walkie-talkie Pod ke andar rakh dete ho, dono ko ek hi channel (port) pe set kar dete ho. Ab tumhare computer pe jo bhi signals aayenge, woh Pod tak pahunch jayenge.

Step 6: Port Forwarding Shuru Karo Ek naya terminal window open karo (tumhara purana terminal jahan tum commands de rahe the, use chalta rehne do). Is naye terminal mein yeh command type karo:

bash
kubectl port-forward pod/website-updater-pod 8080:80

Explanation:

  • kubectl port-forward: Yeh port forwarding command hai.
  • pod/website-updater-pod: Target Pod. pod/ prefix batata hai ki hum Pod ka naam de rahe hain.
  • 8080:80: Iska matlab hai, apne computer ke port 8080 ko website-updater-pod ke andar ke port 80 se connect karo. Matlab, jo bhi request tumhare computer ke 8080 port pe aayegi, woh website-updater-pod ke andar 80 port pe chali jayegi.
  • What happens: Yeh command chalte hi tumhare terminal pe Forwarding from 127.0.0.1:8080 -> 80 jaisa message aayega. Yeh terminal tab tak chalta rahega jab tak tum port forwarding kar rahe ho.
  • Result: Ab tumhare computer ka port 8080 website-updater-pod ke port 80 se connected hai.

Step 7: Browser Mein Website Access Karo Ab, apne computer ke web browser (jaise Chrome, Firefox) ko open karo aur address bar mein type karo:

http://localhost:8080/

Explanation:

  • http://localhost:8080/: localhost matlab tumhara apna computer. 8080 woh port hai jisko tumne forward kiya hai.
  • Result: Tumhe woh index.html page dikhega jo content-downloader-sidecar ne download kiya tha aur web-server-nginx dikha raha hai! 🤩

Step 8: Updated Content Dekho (Magic!) Sidecar container har 15 seconds mein index.html file ko internet se download karta hai. Tum https://raw.githubusercontent.com/omerbsezer/Fast-Kubernetes/main/index.html URL pe jaakar us index.html file ka content change kar sakte ho (agar tumhe permission hai ya tumne khud ki file upload ki hai). Jab content change hoga, toh sidecar naya content download kar lega.

Ab, apne browser mein http://localhost:8080/ page ko refresh karo. Tumhe naya content dikhna chahiye! 🪄 Iska matlab hai ki tumhara Multi-Container Pod aur emptyDir volume perfectly kaam kar rahe hain.

Step 9: Cleanup - Port Forwarding Stop Karo Naye terminal window pe jahan kubectl port-forward chal raha hai, wahan Ctrl+C press karo. Isse port forwarding band ho jayega.

Step 10: Pod Ko Delete Karo Jab kaam khatam ho jaye, toh Pod ko delete kar do. Yaad rakhna, emptyDir volume ka data bhi Pod ke delete hote hi gayab ho jayega.

bash
kubectl delete -f multicontainer-app.yaml

Explanation:

  • kubectl delete -f multicontainer-app.yaml: This command deletes the website-updater-pod.
  • Result: pod "website-updater-pod" deleted message dikhega.

Multi-container Pods bahut useful hote hain jab tumhe ek main app ke saath chote helper apps chalane ho jo same resources share karte hain aur tightly coupled hote hain. Bahut maza aaya na? Ab chalte hain next chapter pe jahan hum seekhenge ki apps ki bahut saari copies ko automatically kaise manage karte hain! 🎉


Chapter 5: Apps ki Factory: Deployments 🏭

Pichhle chapters mein humne Pods (apps ke chhote ghar) ke baare mein seekha. Agar tumhara game ya website bahut popular ho gaya hai, toh tum sirf ek Pod pe usko nahi chala sakte. Kyun?

  • Traffic Load: Agar bahut saare log ek saath game khel rahe hain, toh ek Pod ka server itna traffic handle nahi kar paayega aur slow ho jayega.
  • Availability: Agar woh ek Pod crash ho gaya ya jis computer pe woh chal raha hai, woh kharab ho gaya, toh tumhara game puri tarah se band ho jayega. 😱

Yahan pe kaam aata hai Deployment. Deployment ek smart factory ki tarah hai jo yeh ensure karti hai ki tumhare game ki hamesha zaroorat ke hisaab se copies (Pods) ready hon aur chal rahi hon.

5.1 Deployments Kya Hote Hain? (Like a Toy Factory for your Apps) 🧸

  • Deployment: Deployment ek Kubernetes object hai. Yeh Pods ki multiple copies ko banane, unko manage karne, aur unhein update karne ke liye use hota hai. Deployment ensure karta hai ki tumhare app ki desired number of copies hamesha chal rahi hon.
  • Toy Factory Analogy: Imagine karo tumhari ek toy factory hai jo cars banati hai.
    • Tum factory ke manager (Deployment) ko bolte ho, "Mujhe hamesha 5 cars chahiye ready!" (Desired state: 5 replicas).
    • Factory automatically 5 cars (Pods) banana shuru kar degi.
    • Agar koi car toot gayi (Pod crash ho gaya), factory khud-ba-khud nayi car bana degi taaki hamesha 5 cars ready hon.
    • Agar tumhari cars ki demand badh gayi, toh tum factory ko bol sakte ho, "Ab mujhe 10 cars chahiye!" Factory automatically 5 aur cars bana degi (Scaling up).
  • Key Idea: Desired State: Deployment ka main idea "Desired State" hai. Tum Kubernetes ko batate ho ki "Mujhe is app ki itni copies chahiye chalte hue." Phir Kubernetes ka Deployment Controller us state ko achieve karne ki koshish karta hai, chahe koi Pod crash ho ya Node down ho.

Real-Life Example: Ek popular e-commerce website ka example lete hain. Us website ka frontend (jo users ko dikhta hai) bahut traffic handle karta hai. Hum uski multiple copies (Pods) chalayenge Deployment ki madad se.

Step 1: Deployment Ki YAML File Banao Apne computer pe ek new file banao, uska naam do my-web-app-deployment.yaml. Is file ko text editor mein open karo aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct!

yaml
# File: my-web-app-deployment.yaml

# API version for Deployment objects (usually 'apps/v1' for Deployments)
apiVersion: apps/v1
# Type of Kubernetes object: Deployment
kind: Deployment
# Metadata for our Deployment
metadata:
  # Name of our Deployment
  name: my-first-web-deployment
  # Labels for the Deployment itself (not for the Pods it creates)
  labels:
    project: website-frontend
# Specification for the Deployment
spec:
  # 'replicas' tells Kubernetes how many copies (Pods) of our application we want to run.
  # Here, we want 3 copies of our Nginx web server.
  replicas: 3
  # 'selector' tells the Deployment which Pods it should manage.
  # It identifies Pods based on their labels.
  selector:
    # 'matchLabels' ensures that only Pods with this specific label are managed by this Deployment.
    matchLabels:
      app: web-frontend # This Deployment will manage Pods that have the label 'app: web-frontend'
  # 'template' is the blueprint for the Pods that this Deployment will create.
  # Every time the Deployment creates a new Pod, it will use this template.
  template:
    # Metadata for the Pods created by this template
    metadata:
      # Labels for the Pods themselves. These labels must match the 'selector' above.
      # If they don't match, the Deployment won't know which Pods to manage!
      labels:
        app: web-frontend # This label ensures the Pods are selected by our Deployment
    # Specification for the Pods created by this template
    spec:
      # List of containers inside each Pod
      containers:
      - # Name of the container inside the Pod
        name: nginx-web-server-container
        # Image for the container (Nginx web server)
        image: nginx:latest
        # Ports exposed by the container
        ports:
        - containerPort: 80 # Nginx serves content on port 80

Explanation (YAML file ke har section ki simplified jankari):

  • apiVersion: apps/v1: Deployments ke liye apps/v1 API version use hota hai.
  • kind: Deployment: Hum ek Deployment bana rahe hain.
  • metadata: name: my-first-web-deployment: Deployment ka naam my-first-web-deployment hai.
  • spec:: Deployment ki settings.
    • replicas: 3: Yeh sabse important setting hai! Iska matlab hai ki hum apne nginx app ki 3 copies (Pods) chalana chahte hain. Deployment hamesha ensure karega ki 3 Pods chal rahi hon.
    • selector: matchLabels: app: web-frontend: Yeh Deployment ko batata hai ki usko kin Pods ko monitor karna hai aur manage karna hai. Yahan app: web-frontend label wale Pods ko yeh Deployment dekhega.
    • template:: Ismein Pod ki definition hoti hai. Jab Deployment naya Pod banata hai, toh woh is template ko use karta hai.
      • template -> metadata -> labels: app: web-frontend: Yeh labels bahut zaruri hain! Inhein selector se match karna chahiye. Agar yeh match nahi karenge, toh Deployment ko pata hi nahi chalega ki woh kis Pod ko manage kare.
      • template -> spec -> containers: - name: nginx-web-server-container, image: nginx:latest, ports: - containerPort: 80: Yeh normal Pod definition hai, jaisi humne Chapter 3 mein dekhi thi. Nginx web server chalega.

Step 2: Deployment Ko Apply Karo Ab Kubectl ko bolo ki is my-web-app-deployment.yaml file mein likhe hue plan ko execute karo:

bash
kubectl apply -f my-web-app-deployment.yaml

Explanation:

  • kubectl apply -f my-web-app-deployment.yaml: This command creates the my-first-web-deployment in your Kubernetes cluster.
  • Result: deployment.apps/my-first-web-deployment created jaisa message dikhega.

Step 3: Deployments aur Pods Ki Status Dekho Chalo, dekhte hain ki hamara Deployment successfully bana aur usne Pods banaye ya nahi:

bash
kubectl get deployments

Explanation:

  • kubectl get deployments: This command lists all Deployments in your current namespace.
  • Result: Tumhe my-first-web-deployment dikhega. READY column mein 3/3 hona chahiye, matlab 3 Pods running hain, out of 3 desired.
    NAME                  READY   UP-TO-DATE   AVAILABLE   AGE
    my-first-web-deployment   3/3     3            3           20s
    • READY: 3/3 matlab 3 Pods ready hain (chal rahe hain) out of the 3 jo humne maange the.
    • UP-TO-DATE: Kitne Pods latest configuration pe hain.
    • AVAILABLE: Kitne Pods users ke liye available hain.

Ab, Pods ki list dekho, jinko Deployment ne banaya hai:

bash
kubectl get pods -o wide

Explanation:

  • kubectl get pods -o wide: This command lists all Pods with more detailed information (-o wide).
  • Result: Tumhe 3 Pods dikhenge, jinke naam my-first-web-deployment- se shuru honge aur uske baad kuch random letters aur numbers honge (jaise my-first-web-deployment-85c8f8d9c6-abcde). Sabki STATUS Running honi chahiye.
    NAME                                   READY   STATUS    RESTARTS   AGE   IP           NODE       NOMINATED NODE   READINESS GATES
    my-first-web-deployment-85c8f8d9c6-abcde   1/1     Running   0          30s   172.17.0.4   minikube   <none>           <none>
    my-first-web-deployment-85c8f8d9c6-fghij   1/1     Running   0          30s   172.17.0.5   minikube   <none>           <none>
    my-first-web-deployment-85c8f8d9c6-klmno   1/1     Running   0          30s   172.17.0.6   minikube   <none>           <none>
    • Notice karo ki Pods ke naam ke beech mein 85c8f8d9c6 jaisa kuch hai. Yeh ReplicaSet ka hash hai (ReplicaSet Deployment ka helper hai jo Pods ki count maintain karta hai).

Step 4: Deployment Ki Self-Healing Power Dekho Chalo, dekhte hain ki agar koi Pod crash ho gaya, toh Deployment use automatically theek karta hai ya nahi. Hum forcefully ek Pod ko delete kar denge.

Pehle, ek Pod ka poora naam copy karo (jaise my-first-web-deployment-85c8f8d9c6-abcde). Ab, ek alag terminal window open karo aur usmein live Pod status dekho:

bash
kubectl get pods -w

Explanation:

  • kubectl get pods -w: w flag (watch) ka matlab hai ki yeh command Pods ki list ko real-time mein update karta rahega, jaise hi koi change hoga. Isko chalta rehne do.

Ab, original terminal mein wapas jao aur ek Pod ko delete karo (us Pod ka naam paste karo jo tumne copy kiya tha):

bash
kubectl delete pod <paste_your_pod_name_here>

Example:kubectl delete pod my-first-web-deployment-85c8f8d9c6-abcde

Explanation:

  • kubectl delete pod <pod_name>: This command deletes the specified Pod.
  • What happens: Tumne ek Pod ko delete kar diya. Ab my-first-web-deployment (jo 3 copies chahta hai) dekhega ki ab sirf 2 Pods chal rahe hain. Uska Desired State (3 Pods) Current State (2 Pods) se match nahi kar raha. Toh, Deployment Controller automatically ek naya Pod bana dega.
  • Result: kubectl get pods -w wale terminal mein tumhe dikhega ki jo Pod tumne delete kiya tha, woh Terminating ho jayega. Kuch hi seconds mein, ek naya Pod ContainerCreating se Running state mein aayega, jiska naam bilkul naya hoga. Total Pods phir se 3 ho jayenge! 🎉
    NAME                                   READY   STATUS        RESTARTS   AGE
    my-first-web-deployment-85c8f8d9c6-abcde   1/1     Terminating   0          2m (Pod gets deleted)
    my-first-web-deployment-85c8f8d9c6-fghij   1/1     Running       0          2m
    my-first-web-deployment-85c8f8d9c6-klmno   1/1     Running       0          2m
    my-first-web-deployment-85c8f8d9c6-xyz01   0/1     ContainerCreating 0          2s (A new Pod appears!)
    my-first-web-deployment-85c8f8d9c6-xyz01   1/1     Running       0          10s
    kubectl get pods -w wale terminal ko Ctrl+C press karke band kar do.

5.2 Apps ki Copies ko Kam Ya Zyaada Karna: Scale Up/Down (Adjusting Production) 📈📉

Tumhara game aur bhi popular ho gaya, toh tumhe aur copies chahiye! Ya phir, raat ho gayi, aur players kam ho gaye, toh copies kam karni hain. Is process ko Scaling kehte hain.

Step 1: Deployment Ko Scale Up Karo (Zyada Copies Banao) Chalo, ab hum apne my-first-web-deployment ki copies 3 se 5 karte hain:

bash
kubectl scale deployment my-first-web-deployment --replicas=5

Explanation:

  • kubectl scale: Yeh command Deployment ki copies (replicas) ko change karta hai.
  • deployment my-first-web-deployment: Target Deployment.
  • --replicas=5: Ab hum chahte hain ki 5 copies chalengi.
  • What happens: Deployment Controller dekhega ki usko 5 Pods chahiye, lekin abhi sirf 3 chal rahe hain. Toh woh automatically 2 naye Pods bana dega.
  • Result: deployment.apps/my-first-web-deployment scaled message dikhega.

Pod status ko phir se watch karo, ek alag terminal mein:

bash
kubectl get pods -w

Explanation: Tumhe dikhega ki 2 naye Pods ContainerCreating se Running state mein aayenge. Ab total 5 Pods honi chahiye.

Step 2: Deployment Ko Scale Down Karo (Copies Kam Karo) Ab game ki popularity thodi kam ho gayi ya raat ho gayi, toh copies kam karte hain. Chalo, 5 se 2 copies karte hain:

bash
kubectl scale deployment my-first-web-deployment --replicas=2

Explanation:

  • --replicas=2: Ab hum chahte hain ki sirf 2 copies chalengi.
  • What happens: Deployment Controller dekhega ki usko 2 Pods chahiye, lekin abhi 5 chal rahe hain. Toh woh automatically 3 extra Pods ko gracefully delete kar dega.
  • Result: deployment.apps/my-first-web-deployment scaled message dikhega.

kubectl get pods -w wale terminal mein dekho. Tumhe dikhega ki 3 Pods Terminating ho jayenge. Ab total 2 Pods honi chahiye.

Step 3: Cleanup - Deployment Ko Delete Karo Jab kaam khatam ho jaye, toh Deployment ko delete kar do:

bash
kubectl delete -f my-web-app-deployment.yaml

Explanation:

  • kubectl delete -f my-web-app-deployment.yaml: This command deletes the my-first-web-deployment and all the Pods it created.
  • Result: deployment.apps "my-first-web-deployment" deleted jaisa message dikhega.

Deployments bahut powerful hote hain kyunki yeh tumhare apps ko hamesha chalate rehte hain aur unki copies ko automatically manage karte hain, chahe kuch bhi ho jaye. Next chapter mein hum dekhenge ki apps ko smoothly update kaise karte hain aur agar koi galti ho jaye toh wapas purane version pe kaise jaate hain! 🎉


Chapter 6: Naye Version Lana aur Wapas Jaana: Rollout aur Rollback 🔄

Socho, tumne apna game banaya hai (jo ab Deployment se manage ho raha hai aur uski bahut saari copies chal rahi hain). Ab tum game mein naye features add karte ho, ya usmein koi bug fix karte ho. Iska matlab hai ki tumhe game ka naya "version" chalana hai. Lekin tum yeh nahi chahte ki naya version aate hi purana version ekdum se band ho jaye aur players ko game band mile! Imagine, game ke beech mein hi disconnect ho jaye! 😨

Yahin pe kaam aate hain Rollout aur Rollback! Yeh features Deployment ko apne apps ko smoothly update karne aur agar koi problem ho toh turant purane version pe wapas jaane ki power dete hain.

6.1 Apps ko Update Karna: Recreate ya RollingUpdate? (Different Ways to Change Clothes) 👗

Jab hum apne app ka naya version Deployment mein daalte hain, toh is process ko Rollout kehte hain. Rollout ke do main tareeke hote hain, jaise naye kapde pehenne ke alag-alag tareeke:

  1. Recreate Strategy:
    • Kaise kaam karta hai: Ismein Deployment pehle saare purane Pods ko delete kar deta hai, phir naye Pods ko naye version ke saath banata hai. Socho, jaise tum saare purane kapde utar ke ekdum se naye kapde pehente ho.
    • Fayda: Simple. Agar naye aur purane version mein bahut bada badlav hai aur woh ek saath nahi chal sakte (jaise, ek app database version 1 se connect ho raha hai aur doosra app database version 2 se, aur dono ek saath connect nahi ho sakte), toh yeh theek hai.
    • Nuksan: Kuch der ke liye app unavailable ho sakta hai (downtime), kyunki purane Pods delete hote hain aur naye banne mein time lagta hai. Users ko Error dikh sakta hai.
    • YAML mein define karna: strategy: type: Recreate

Step 1: Recreate Deployment File Banao Apne computer pe ek new file banao, uska naam do recreate-deployment.yaml. Is file ko text editor mein open karo aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct!

yaml
# File: recreate-deployment.yaml

# API version for Deployment objects
apiVersion: apps/v1
# Type of Kubernetes object: Deployment
kind: Deployment
# Metadata for our Deployment
metadata:
  name: recreate-web-app
  labels:
    type: web-server
# Specification for the Deployment
spec:
  # We want 3 replicas (copies) of our web app
  replicas: 3
  # This Deployment will manage Pods with this label
  selector:
    matchLabels:
      app: recreate-app
  # This defines the rollout strategy.
  # 'Recreate' means: Delete all old Pods first, then create all new Pods.
  strategy:
    type: Recreate # This is the strategy for updating our application
  # Template for the Pods that this Deployment will create
  template:
    metadata:
      labels:
        app: recreate-app # Pods created by this Deployment will have this label
    spec:
      containers:
      - name: nginx-app-container # Name of the container
        image: nginx:1.14 # Initial version of Nginx (an older stable version)
        ports:
        - containerPort: 80

**Step 1: Frontend Ke Liye NodePort Service Banao**
Apne computer pe ek new file `frontend-nodeport-service.yaml` naam se banao aur usmein yeh code copy paste karo. **Make sure spacing (indentation) is correct!**

```yaml
# File: frontend-nodeport-service.yaml

# API version for Service objects
apiVersion: v1
# Type of Kubernetes object: Service
kind: Service
# Metadata for our Service
metadata:
  name: frontend-web-nodeport-service
# Specification for the Service
spec:
  # 'type: NodePort' means this Service will be accessible from outside the cluster
  # via any Node's IP address on a specific port (NodePort).
  type: NodePort
  # This Service will send traffic to Pods with 'app: web-frontend' label.
  selector:
    app: web-frontend
  # Ports definition for the Service
  ports:
    - protocol: TCP
      port: 80 # This is the Service's internal cluster port (like a ClusterIP port)
      targetPort: 80 # This is the port inside the Pod's container (Nginx is on 80)
      # Kubernetes will automatically assign a 'nodePort' between 30000-32767.
      # You can also manually specify it here, e.g., nodePort: 30080 (if available).

Explanation:

  • kind: Service: Hum ek Service bana rahe hain.
  • name: frontend-web-nodeport-service: Service ka naam frontend-web-nodeport-service hai.
  • type: NodePort: Is Service ki type NodePort hai. Kubernetes automatically 30000 se 32767 ke beech ek random port assign karega har Node pe. Yahi NodePort hai.

Step 2: Service Ko Apply Karo

bash
kubectl apply -f frontend-nodeport-service.yaml

Explanation:

  • kubectl apply -f frontend-nodeport-service.yaml: This command creates the frontend-web-nodeport-service.
  • Result: service/frontend-web-nodeport-service created message dikhega.

Step 3: Service Ki Status Dekho

bash
kubectl get svc

Explanation:

  • kubectl get svc: This command lists all Services.
  • Result: frontend-web-nodeport-service dikhegi. TYPE NodePort hoga, aur PORT(S) column mein 80:3XXXX/TCP jaisa kuch dikhega. 3XXXX woh random port hai jo Kubernetes ne assign kiya hai (tumhare case mein koi alag number hoga). Yahi hamara NodePort hai.
    NAME                            TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)          AGE
    frontend-web-nodeport-service   NodePort    10.100.Y.Y    <none>        80:30080/TCP     15s
    • 30080: This is the NodePort. It will be different for you.

Step 4: App Ko Bahar Se Access Karo (Using Minikube's Special Command) Agar tum Minikube use kar rahe ho, toh usmein NodePort Service ko access karne ke liye ek special command hoti hai. Yeh command automatically tumhare browser mein URL open kar dega ya URL dikhayega.

bash
minikube service frontend-web-nodeport-service --url

Explanation:

  • minikube service frontend-web-nodeport-service --url: This command gets the URL for the frontend-web-nodeport-service in Minikube.
  • What happens: Minikube ek temporary tunnel banayega ya seedha URL generate karega.
  • Result: Tumhein ek URL dikhega, jaise http://192.168.49.2:30080 (tumhare IP aur port alag ho sakte hain). Is URL ko copy karke apne computer ke browser mein paste karo. Tumhe Nginx ka default welcome page (jo "Welcome to nginx!" dikhata hai) dikhna chahiye! 🌐

Alternative access (For Real Clusters, Not Minikube): Agar tum Minikube use nahi kar rahe ho aur tumhare paas ek real Kubernetes cluster hai (jaise jo Chapter 18 mein bataya jayega), toh tum kisi bhi Node ka IP address (jo kubectl get nodes -o wide se milta hai) aur us NodePort (jo kubectl get svc se mila tha) use karke access kar sakte ho: http://<Node_IP_Address>:<NodePort> (e.g., http://192.168.1.100:30080).

  1. LoadBalancer Service (Cloud ka Smart Post Office):
    • Kaise kaam karta hai: Yeh Service NodePort aur ClusterIP Services ko automatically banati hai. Lekin iski sabse khaas baat yeh hai ki yeh ek Cloud Provider (jaise Google Cloud, AWS, Azure) ka Load Balancer use karti hai. Cloud Load Balancer tumhe ek external public IP address deta hai, jise tum seedha internet se access kar sakte ho.
    • Use: Jab tum kisi public website ya app ko internet pe directly expose karna chahte ho. Yeh sabse best aur professional tareeka public apps ke liye hai.
    • Analogy: Tumhari website ka apna ek unique public phone number (like a 1-800 number) hai jo poori duniya mein use ho sakta hai. Yeh number hamesha same rehta hai, aur iske peeche Load Balancer apne aap traffic ko tumhare app ki copies tak bhej deta hai.
    • Important Note: Yeh Service sirf tab kaam karti hai jab tumhara Kubernetes cluster kisi cloud provider par bana ho (e.g., Google Kubernetes Engine (GKE), Amazon EKS, ya Azure AKS). Minikube isko simulate kar sakta hai, lekin ek real external public IP address nahi deta, woh usually <pending> ya localhost dikhayega.

Step 1: Frontend Ke Liye LoadBalancer Service Banao Apne computer pe ek new file frontend-loadbalancer-service.yaml naam se banao aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct!

yaml
# File: frontend-loadbalancer-service.yaml

# API version for Service objects
apiVersion: v1
# Type of Kubernetes object: Service
kind: Service
# Metadata for our Service
metadata:
  name: frontend-web-loadbalancer-service
# Specification for the Service
spec:
  # 'type: LoadBalancer' will request a Load Balancer from your cloud provider.
  # This Load Balancer will get an external IP address, making the Service accessible from the internet.
  type: LoadBalancer
  # This Service will send traffic to Pods with 'app: web-frontend' label.
  selector:
    app: web-frontend
  # Ports definition for the Service
  ports:
    - protocol: TCP
      port: 80 # This is the Service's external port
      targetPort: 80 # This is the port inside the Pod's container (Nginx is on 80)

Explanation:

  • kind: Service: Hum ek Service bana rahe hain.
  • name: frontend-web-loadbalancer-service: Service ka naam frontend-web-loadbalancer-service hai.
  • type: LoadBalancer: Is Service ki type LoadBalancer hai. Yeh Cloud Provider se Load Balancer request karegi.

Step 2: Service Ko Apply Karo

bash
kubectl apply -f frontend-loadbalancer-service.yaml

Explanation:

  • kubectl apply -f frontend-loadbalancer-service.yaml: This command creates the frontend-web-loadbalancer-service.
  • Result: service/frontend-web-loadbalancer-service created message dikhega.

Step 3: Service Ki Status Dekho (External IP check karo)

bash
kubectl get svc

Explanation:

  • kubectl get svc: This command lists all Services.
  • Result: frontend-web-loadbalancer-service dikhegi. Uski TYPE LoadBalancer hogi.
    • On a Cloud Cluster: EXTERNAL-IP column mein tumhe ek public IP address dikhega (e.g., 34.123.45.67). Is IP ko copy karke apne browser mein paste karo, aur tumhe Nginx page dikhega.
    • On Minikube: EXTERNAL-IP usually <pending> ya localhost dikhega, kyunki Minikube real public Load Balancer provide nahi kar sakta. Lekin tum minikube service frontend-web-loadbalancer-service --url chala ke use access kar sakte ho.
    NAME                                TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)          AGE
    frontend-web-loadbalancer-service   LoadBalancer  10.97.Z.Z     <pending>     80:30080/TCP     5s

Step 4: Cleanup - Saare Services aur Deployments Ko Delete Karo Jab kaam khatam ho jaye, toh saare Services aur Deployments ko delete kar do. Yaad rakhna, pehle Services delete karna achha practice hai, phir Deployments.

bash
kubectl delete -f backend-clusterip-service.yaml
kubectl delete -f frontend-nodeport-service.yaml
kubectl delete -f frontend-loadbalancer-service.yaml
kubectl delete -f web-apps-deployments.yaml

Explanation:

  • kubectl delete -f <file_name>: This command deletes the specified Kubernetes objects.

Services Kubernetes mein apps ko aapas mein baat karne aur bahar ki duniya se connect hone mein help karti hain. Bahut hi useful hain, hai na? Ab tum apps ki communication system bhi samajh gaye ho. Agle chapter mein hum apps ki sehat ka khayal rakhna seekhenge! ❤️‍🩹


Chapter 8: Apps ki Sehat ka Khayal: Liveness aur Readiness Probes ❤️‍🩹

Socho, tumhara game server Kubernetes mein chal raha hai. Sab kuch Running dikh raha hai. Lekin kabhi-kabhi apps ajeeb behave karte hain. Woh chalte toh hain (process running hai), lekin theek se kaam nahi karte. Jaise:

  • Liveness: Game ka server on hai, lekin woh hang ho gaya hai (jaise freeze ho gaya hai) aur koi player connect nahi ho pa raha.
  • Readiness: Game server abhi start ho raha hai (booting up), database se connect kar raha hai, ya bahut saari files load kar raha hai. Is time mein agar players connect karne ki koshish karein, toh unhein errors milenge kyunki server abhi puri tarah se ready nahi hai requests handle karne ke liye.

Kubernetes mein, hum apne apps ki "sehat" (health) check kar sakte hain, taaki woh hamesha theek se kaam karte rahein. Iske liye hum Liveness Probes aur Readiness Probes use karte hain. Socho, jaise tumhare mummy-papa tumhari health check karte hain, waise hi K8s apps ki health check karta hai.

8.1 Liveness Probe: "Kya App Zinda Hai?" (Is it Breathing?) 🤔

Liveness Probe kya hai?Liveness Probe (pronouned: lai-iv-ness prohb) yeh check karta hai ki tumhara app zinda hai aur chal raha hai ya nahi (matlab, woh hang toh nahi ho gaya, ya freeze toh nahi ho gaya).

  • Doctor's Checkup Analogy: Liveness Probe ek doctor ki tarah hai. Woh tumhara pulse check karta hai. Agar pulse nahi hai (app hang ho gaya hai), toh doctor tumhe "zinda" karne ki koshish karega (yani Kubernetes us Pod ko automatically restart kar dega).
  • Purpose: Liveness Probes apps ko CrashLoopBackOff status mein jaane se bachate hain aur ensure karte hain ki app hamesha responsive rahe.

Liveness Probe Kaise Kaam Karta Hai? Liveness Probes alag-alag tareeko se app ki health check kar sakte hain:

  1. HTTP Get Request (httpGet):
    • Kaise check karta hai: App ko ek web request bhejta hai (jaise tum koi website open karte ho, http://localhost:8080/health).
    • Result: Agar app theek HTTP response deta hai (jaise 200 OK ya 2xx series ka koi code), toh woh theek hai. Agar error code (jaise 500 Internal Server Error ya 4xx series ka koi code) aata hai, toh matlab app hang ho gaya hai aur probe fail ho jayega.
  2. Exec Command (exec):
    • Kaise check karta hai: App ke andar ek command chalaata hai (jaise cat /tmp/healthy).
    • Result: Agar command successfully chali aur uska exit code 0 aaya, toh app theek hai. Agar exit code 0 ke alawa kuch aur aaya (non-zero), toh matlab app mein problem hai aur probe fail ho jayega.
  3. TCP Socket (tcpSocket):
    • Kaise check karta hai: App ke kisi specific network port pe connect karne ki koshish karta hai (jaise port: 8080).
    • Result: Agar connection successfully establish ho gaya, toh theek hai. Agar connect nahi kar paaya (jaise port open hi nahi hai), toh problem hai aur probe fail ho jayega.

Important Settings for Probes:

  • initialDelaySeconds: Jab Pod chalu ho jaaye, uske kitni der baad Liveness Probe check karna shuru kare (jaise app start hone ke 5 second baad). Yeh useful hai kyunki app ko puri tarah se load hone mein thoda time lag sakta hai.
  • periodSeconds: Kitni der baad dobara check kare (jaise har 3 second baad).
  • timeoutSeconds: Kitni der tak response ka wait kare. Agar is time mein response nahi aaya, toh probe fail.
  • failureThreshold: Kitni baar probe fail ho, phir Pod ko restart kare.

Step 1: Liveness Probe Ke Saath Pod File Banao Apne computer pe ek new file liveness-probes.yaml naam se banao aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct!

yaml
# File: liveness-probes.yaml

# Pod demonstrating HTTP Get Liveness Probe
apiVersion: v1
kind: Pod
metadata:
  labels:
    test: liveness-http-probe
  name: liveness-http-test-pod # Name of the Pod
spec:
  containers:
  - name: liveness-http-container
    # This is a special image provided by Kubernetes examples that simulates health checks.
    # It has a web server that responds on /healthz.
    image: k8s.gcr.io/liveness
    args: ["/server"] # Run the server executable inside the container
    # Define the Liveness Probe
    livenessProbe:
      # Use HTTP Get method for the probe
      httpGet:
        path: /healthz # Path (URL) to check on the container's web server
        port: 8080 # Port where the web server is listening inside the container
        # Optional: Add custom HTTP headers if needed for the check
        httpHeaders:
        - name: Custom-Header
          value: Awesome
      initialDelaySeconds: 3 # Wait 3 seconds after container starts before starting the probe
      periodSeconds: 3 # Check every 3 seconds
---
# Pod demonstrating Exec Command Liveness Probe
apiVersion: v1
kind: Pod
metadata:
  labels:
    test: liveness-exec-probe
  name: liveness-exec-test-pod # Name of the Pod
spec:
  containers:
  - name: liveness-exec-container
    # Using busybox image for simple command execution
    image: busybox
    args:
    - /bin/sh # Start a shell
    - -c # Execute the following string as a command
    # This command creates a file /tmp/healthy, waits for 30 seconds, then deletes the file, and sleeps for 600 seconds.
    # So, the file will exist for 30 seconds, then it will be deleted.
    - "touch /tmp/healthy; sleep 30; rm -rf /tmp/healthy; sleep 600"
    # Define the Liveness Probe
    livenessProbe:
      # Use Exec command method for the probe
      exec:
        command:
        - cat # Command to execute inside the container
        - /tmp/healthy # This command will try to read the /tmp/healthy file
                       # If the file exists, 'cat' will succeed (exit code 0).
                       # If the file doesn't exist, 'cat' will fail (non-zero exit code).
      initialDelaySeconds: 5 # Wait 5 seconds after container starts before starting the probe
      periodSeconds: 5 # Check every 5 seconds
---
# Pod demonstrating TCP Socket Liveness Probe
apiVersion: v1
kind: Pod
metadata:
  name: liveness-tcp-test-pod # Name of the Pod
  labels:
    test: liveness-tcp-probe
spec:
  containers:
  - name: liveness-tcp-container
    # This image provides a simple TCP listener on port 8080
    image: k8s.gcr.io/goproxy:0.1
    ports:
    - containerPort: 8080 # App listens on port 8080 inside the container
    # Define the Liveness Probe
    livenessProbe:
      # Use TCP Socket method for the probe
      tcpSocket:
        port: 8080 # Try to establish a TCP connection to this port inside the container
      initialDelaySeconds: 15 # Wait 15 seconds before starting the probe
      periodSeconds: 20 # Check every 20 seconds

Explanation (YAML file ke har section ki simplified jankari):

  • liveness-http-test-pod (HTTP Get Probe):
    • image: k8s.gcr.io/liveness: Yeh Google Kubernetes ki taraf se ek special image hai jo health check ke liye theek response deta hai.
    • livenessProbe: httpGet:: Hum HTTP request bhejenge.
    • path: /healthz, port: 8080: Container ke andar http://localhost:8080/healthz pe request jayegi.
    • initialDelaySeconds: 3, periodSeconds: 3: Pod start hone ke 3 second baad check shuru hoga, aur phir har 3 second baad check hoga.
  • liveness-exec-test-pod (Exec Command Probe):
    • image: busybox: Hum busybox use kar rahe hain, jo simple commands chalane ke liye achha hai.
    • args: - "touch /tmp/healthy; sleep 30; rm -rf /tmp/healthy; sleep 600": Yeh command sequence hai.
      1. touch /tmp/healthy: Pod start hote hi /tmp/healthy naam ki file bana dega.
      2. sleep 30: 30 second tak wait karega.
      3. rm -rf /tmp/healthy: 30 second baad /tmp/healthy file ko delete kar dega.
      4. sleep 600: 10 minute tak kuch nahi karega.
    • livenessProbe: exec: command: - cat - /tmp/healthy: Liveness Probe har 5 second baad cat /tmp/healthy command chalayega.
      • First 30 seconds: /tmp/healthy file exist karegi, toh cat command succeed hoga (exit code 0), aur probe Pass hoga.
      • After 30 seconds: /tmp/healthy file delete ho jayegi, toh cat command Fail hoga (non-zero exit code), aur probe Fail hoga. Jab probe fail hoga, toh Kubernetes is Pod ko restart kar dega.
  • liveness-tcp-test-pod (TCP Socket Probe):
    • image: k8s.gcr.io/goproxy:0.1: Yeh image port 8080 pe listen karta hai.
    • livenessProbe: tcpSocket: port: 8080: Liveness Probe container ke port 8080 pe TCP connection banane ki koshish karega. Agar connection ban gaya, toh Pass, warna Fail.
    • initialDelaySeconds: 15, periodSeconds: 20: 15 second baad check shuru hoga, phir har 20 second baad check hoga.

Step 2: Pods Ko Apply Karo

bash
kubectl apply -f liveness-probes.yaml

Explanation:

  • kubectl apply -f liveness-probes.yaml: This command creates all three Pods.
  • Result: pod/liveness-http-test-pod created, pod/liveness-exec-test-pod created, pod/liveness-tcp-test-pod created messages dikhenge.

Step 3: Pod Status aur Restart Count Dekho (Live Observation) Ek alag terminal window open karo aur usmein Pods ko watch karo. Isko chalta rehne do.

bash
kubectl get pods -w

Explanation:

  • kubectl get pods -w: This command will show live updates of your Pods.
  • What to observe:
    • liveness-http-test-pod: Yeh Pod Running rahega aur RESTARTS count 0 hi rahega, kyunki iska health check hamesha pass hoga.
    • liveness-tcp-test-pod: Yeh Pod bhi Running rahega aur RESTARTS count 0 hi rahega, kyunki iska TCP connection hamesha banega.
    • liveness-exec-test-pod: Yeh Pod shuru mein Running hoga aur RESTARTS count 0 hoga. Lekin, roughly 35-40 seconds baad (5s initial delay + 30s sleep = 35s, then first probe check), tum dekhoge ki iska RESTARTS count 1, 2, 3... badhna shuru ho jayega! Aur STATUS CrashLoopBackOff bhi dikh sakta hai.
  • Why liveness-exec-test-pod restarts: Kyunki 30 seconds baad /tmp/healthy file delete ho jati hai, toh cat /tmp/healthy command fail hota hai. Liveness Probe fail hone par Kubernetes Pod ko restart kar deta hai.
    NAME                     READY   STATUS             RESTARTS   AGE
    liveness-http-test-pod   1/1     Running            0          1m
    liveness-exec-test-pod   1/1     Running            0          1m
    liveness-tcp-test-pod    1/1     Running            0          1m
    # ... after 35-40 seconds ...
    liveness-exec-test-pod   0/1     CrashLoopBackOff   1          1m
    liveness-exec-test-pod   0/1     CrashLoopBackOff   2          2m

kubectl get pods -w wale terminal ko Ctrl+C press karke band kar do.

Step 4: Restarted Pod Ke Events Dekholiveness-exec-test-pod ki detailed events dekhne ke liye, jahan tumhe restarts ka reason dikhega:

bash
kubectl describe pod liveness-exec-test-pod

Explanation:

  • kubectl describe pod liveness-exec-test-pod: This command shows detailed information about the specific Pod.
  • Result: Events section mein tumhe Liveness probe failed aur Container exited jaise messages dikhenge, jo batayenge ki Pod kyu restart ho raha hai.
    Events:
      Type     Reason     Age                  From               Message
      ----     ------     ----                 ----               -------
      Normal   Pulled     2m                   kubelet, minikube  Container image "busybox" already present on machine
      Normal   Created    2m                   kubelet, minikube  Created container liveness-exec-container
      Normal   Started    2m                   kubelet, minikube  Started container liveness-exec-container
      Warning  Unhealthy  15s (x3 over 1m)     kubelet, minikube  Liveness probe failed: cat: can't open '/tmp/healthy': No such file or directory
      Normal   Killing    15s (x3 over 1m)     kubelet, minikube  Container liveness-exec-container failed liveness probe, will be restarted
      Normal   Pulled     14s (x3 over 1m)     kubelet, minikube  Container image "busybox" already present on machine
      Normal   Created    14s (x3 over 1m)     kubelet, minikube  Created container liveness-exec-container
      Normal   Started    14s (x3 over 1m)     kubelet, minikube  Started container liveness-exec-container
    Yahan Unhealthy reason Liveness probe failed clear dikh raha hai.

8.2 Readiness Probe: "Kya App Ready Hai Kaam Karne Ke Liye?" (Is it Ready for Customers?) 💡

Readiness Probe kya hai?Readiness Probe (pronounced: reh-dee-ness prohb) yeh check karta hai ki tumhara app requests handle karne ke liye ready hai ya nahi.

  • Traffic Light Analogy: Readiness Probe ek traffic light ki tarah hai. Jab tum game server chalu karte ho, toh woh thoda time leta hai ready hone mein (jaise database connect karna, badi files load karna). Is time mein, traffic light Red hai (Pod is Not Ready). Jab app puri tarah se load ho gaya aur requests handle karne ke liye ready hai, tab light Green hoti hai (Pod is Ready), aur tabhi users ki requests us tak jaati hain.
  • Purpose: Readiness Probe yeh ensure karta hai ki traffic sirf un Pods tak jaye jo fully operational hain. Isse users ko errors nahi milte aur app ka experience smooth rehta hai.

Kaise Kaam Karta Hai? Readiness Probes bhi httpGet, exec, tcpSocket methods use karte hain, bilkul Liveness Probes ki tarah. Sirf livenessProbe ki jagah readinessProbe key use hoti hai YAML file mein.

Example Scenario for Readiness Probe: Tumne ek web app banaya hai jo database se data fetch karta hai. Jab app start hota hai, toh database se connect hone mein 10-15 seconds lagte hain. Is 10-15 seconds ke dauran, app chal toh raha hai, lekin woh requests handle nahi kar sakta kyunki database se connected nahi hai. Agar is dauran koi user request bhejega, toh usko error milega. Readiness Probe is situation ko avoid karta hai. Jab tak database connect nahi hota, Readiness Probe Fail hoga, aur Kubernetes is Pod ko Not Ready mark kar dega. Service is Not Ready Pod ko traffic nahi bhejegi. Jaise hi database connect hoga, Readiness Probe Pass hoga, aur Pod Ready ho jayega, aur phir traffic us tak aayega.

Step 5: Cleanup - Pods Ko Delete Karo Jab kaam khatam ho jaye, toh saare Pods ko delete kar do.

bash
kubectl delete -f liveness-probes.yaml

Explanation:

  • kubectl delete -f liveness-probes.yaml: This command deletes all the Pods defined in the YAML file.

Liveness aur Readiness Probes bahut important hain apps ko stable aur always-available rakhne ke liye. Yeh ensure karte hain ki users ko hamesha ek working aur responsive app mile. Agle chapter mein hum settings aur secrets ko manage karna seekhenge! 🤫📝


Chapter 9: Apps ke Secret aur Settings: Secrets aur ConfigMaps 🤫📝

Socho, tumhara game server Kubernetes mein chal raha hai. Is game server ko kuch khaas jankari chahiye hoti hai taaki woh theek se chal sake:

  • Secret Information: Jaise database ka password, game ka secret API key (jisse hackers game ko access na kar payein), ya SSL certificate (jisse website secure ho). Yeh information bahut sensitive hoti hai aur kisi ko dikhni nahi chahiye. Agar yeh information leaked ho gayi, toh bahut badi problem ho sakti hai!
  • Normal Settings: Jaise game ka default level, game ka default theme (dark ya light), ya koi feature toggle (jaise "new_leaderboard_feature: true/false"). Yeh information sensitive nahi hoti, lekin game ko chalane ke liye zaruri hoti hai aur aksar badalti rehti hai.

Kubernetes mein, hum in do tarah ki information ko alag-alag objects mein store karte hain:

  • Secrets: Sensitive (secret) information ke liye.
  • ConfigMaps: Non-sensitive (normal) settings ke liye.

Yeh dono objects apps (Pods) ko yeh information provide karte hain, lekin kabhi bhi file mein ya command history mein dikhte nahi hain. Socho, jaise tumhare ghar mein ek secret locker hai aur ek normal notepad.

9.1 Secrets: Tumhara Secret Locker (Sensitive Data) 🔒

Secrets kya hain?Secrets (pronounced: see-krets) Kubernetes objects hain jo sensitive data, jaise passwords, API keys, aur certificates, ko store karte hain. Kubernetes in data ko internally base64 encode kar deta hai taaki woh simple kubectl get command se seedha plain text mein na dikhe. Lekin, yaad rakhna, base64 encoding koi encryption nahi hai, bas hiding hai. Real security ke liye aur steps chahiye hote hain.

  • Secret Locker Analogy: Jaise tumhare ghar mein ek secret locker hai, jahan tum apni sabse important aur secret cheezein rakhte ho. Koi bhi usse nahi dekh sakta, bas jisko permission hai, wahi access kar sakta hai.

Secrets Ko Kaise Use Karein Pods mein? Pods Secrets ko do main tareeko se use kar sakte hain:

  1. Environment Variables ki Tarah: Secret values Pods ke andar environment variables ban jaate hain. App code unhein normal environment variables ki tarah read kar sakta hai. (Example: DB_PASSWORD="MySuperSecret123")
  2. Volume ki Tarah (Files ki Tarah): Secret data ko Pod ke andar ek virtual file system ke roop mein mount kiya jaata hai. Secret ke andar ki har key ek file ban jaati hai, aur value us file ka content. (Example: /etc/secrets/db_password file jismein password likha hai)

Step 1: Secret Object Banao (Declarative Way) Apne computer pe ek new file my-secret.yaml naam se banao aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct!

yaml
# File: my-secret.yaml

# API version for Secret objects
apiVersion: v1
# Type of Kubernetes object: Secret
kind: Secret
# Metadata for our Secret
metadata:
  # Name of our Secret
  name: my-database-secret # This name will be used by Pods to reference this secret
# Type of the Secret. 'Opaque' is the default and most common type for general-purpose secrets.
type: Opaque
# 'stringData' is used to define key-value pairs in plain text.
# Kubernetes will automatically base64-encode these values internally.
# This is safer than using 'data' field where you would have to base64-encode manually.
stringData:
  db_server: mydatabase.example.com # Database server address (non-sensitive, but often kept with sensitive ones)
  db_username: admin # Database username (sensitive)
  db_password: P@ssw0rd! # Database password (VERY sensitive!)

Explanation (YAML file ke har section ki simplified jankari):

  • kind: Secret: Hum ek Secret bana rahe hain.
  • name: my-database-secret: Secret ka naam my-database-secret hai. Pods isi naam se is secret ko access karenge.
  • type: Opaque: Yeh Secret ka type hai. Opaque general-purpose secrets ke liye common type hai, matlab yeh kisi specific format ka data nahi hai (jaise passwords, keys).
  • stringData:: Yahan tum plain text mein key-value pairs define karte ho. Kubernetes automatically in values ko base64 encode kar dega jab Secret ban jayega.

Step 2: Secret Ko Apply Karo

bash
kubectl apply -f my-secret.yaml

Explanation:

  • kubectl apply -f my-secret.yaml: This command creates the my-database-secret.
  • Result: secret/my-database-secret created message dikhega.

Step 3: Secret Ki Jankari Dekho (Values will be encoded!) Jab tum secret ko get karte ho (-o yaml flag se), toh uski values base64 encoded dikhti hain, plain text mein nahi.

bash
kubectl get secret my-database-secret -o yaml

Explanation:

  • kubectl get secret my-database-secret -o yaml: This command fetches the my-database-secret and displays its full YAML definition.
  • Result: data section mein tumhe db_server, db_username, db_password ki values base64 encoded strings ke roop mein dikhengi, jaise P@ssw0rd! ke liye UABzc3cwcmQh jaisa kuch.
    yaml
    apiVersion: v1
    data:
      db_password: UABzc3cwcmQh # This is base64 encoded "P@ssw0rd!"
      db_server: ZGIuZXhhbXBsZS5jb20=
      db_username: YWRtaW4=
    kind: Secret
    metadata:
      creationTimestamp: "2023-10-27T12:00:00Z"
      name: my-database-secret
      namespace: default
      resourceVersion: "12345"
      uid: abcdef12-3456-7890-abcd-ef1234567890
    type: Opaque
    Yeh isliye hai taaki koi bhi kubectl get command se seedha secrets ko plain text mein na dekh sake. Real security ke liye, is data ko aur bhi secure tareeko se handle karna padta hai.

Optional: Base64 Decode Kaise Karein? Agar tumhein encoded value ko decode karke dekhna hai (sirf learning purpose ke liye, production mein aisa nahi karna chahiye):

bash
echo "UABzc3cwcmQh" | base64 --decode

Explanation:

  • echo "UABzc3cwcmQh": Yeh base64 string ko print karega.
  • | base64 --decode: | (pipe) ka matlab hai, echo ke output ko base64 --decode command ko do, jo use decode kar dega.
  • Result: P@ssw0rd! dikhega.

Step 4: Pods Ko Secret Access Karne Ke Liye File Banao Apne computer pe ek new file secret-access-pods.yaml naam se banao aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct! Is file mein teen alag-alag Pods hain jo Secrets ko alag-alag tareeko se access karte hain: volume, individual environment variables, aur saare environment variables.

yaml
# File: secret-access-pods.yaml

# Pod 1: Accessing Secret as a Volume (files in a directory)
apiVersion: v1
kind: Pod
metadata:
  name: secret-volume-test-pod # Pod's name
spec:
  containers:
  - name: secret-volume-container
    image: nginx # Using Nginx for demonstration
    volumeMounts: # How to connect volumes to this container
    - name: secret-data-volume # Name of the volume to mount (defined below)
      mountPath: "/etc/my-app-secrets" # Path inside the container where secret files will appear
      readOnly: true # IMPORTANT: Set to true so the container cannot accidentally modify secret files
  volumes: # Definition of volumes for the Pod
  - name: secret-data-volume # Name of our volume
    secret: # This volume will use a Secret
      secretName: my-database-secret # The name of the Secret to use
---
# Pod 2: Accessing Secret as Individual Environment Variables
apiVersion: v1
kind: Pod
metadata:
  name: secret-env-test-pod # Pod's name
spec:
  containers:
  - name: secret-env-container
    image: nginx
    env: # Define environment variables for this container
      - name: DB_USERNAME # Name of the environment variable (can be different from secret key)
        valueFrom: # Get value from another source
          secretKeyRef: # Get value from a Secret key
            name: my-database-secret # The name of the Secret
            key: db_username # The specific key within the Secret whose value to use
      - name: DB_PASSWORD # Another environment variable
        valueFrom:
          secretKeyRef:
            name: my-database-secret
            key: db_password
      - name: DB_SERVER_ADDRESS # Another environment variable
        valueFrom:
          secretKeyRef:
            name: my-database-secret
            key: db_server
---
# Pod 3: Accessing ALL Secret keys as Environment Variables (using envFrom)
apiVersion: v1
kind: Pod
metadata:
  name: secret-env-all-test-pod # Pod's name
spec:
  containers:
  - name: secret-env-all-container
    image: nginx
    envFrom: # This field allows you to load all key-value pairs from a Secret or ConfigMap
    - secretRef: # Reference a Secret
        name: my-database-secret # The name of the Secret whose keys will become env vars

Explanation (YAML file ke har section ki simplified jankari):

  • Pod 1 (secret-volume-test-pod - Secret as Volume):
    • volumeMounts: - name: secret-data-volume, mountPath: "/etc/my-app-secrets": secret-data-volume ko container ke andar /etc/my-app-secrets path pe mount kiya gaya hai.
    • volumes: - name: secret-data-volume, secret: secretName: my-database-secret: secret-data-volume my-database-secret se data lega. Is mountPath pe db_server, db_username, db_password naam ki files ban jayengi, jinmein unki respective secret values hongi.
    • readOnly: true: Important! Isse Pod ke andar apps in secret files ko modify nahi kar sakte.
  • Pod 2 (secret-env-test-pod - Secret as Individual Environment Variables):
    • env: - name: DB_USERNAME, valueFrom: secretKeyRef: name: my-database-secret, key: db_username: Yahan hum my-database-secret se db_username key ki value nikal kar DB_USERNAME naam ke environment variable mein daal rahe hain. Har variable ko alag-alag define karna padta hai.
  • Pod 3 (secret-env-all-test-pod - Secret as All Environment Variables using envFrom):
    • envFrom: - secretRef: name: my-database-secret: Yeh easy tareeka hai! Isse my-database-secret ke andar ki saari key-value pairs automatically container ke liye environment variables ban jayengi. Yani db_server, db_username, db_password naam ke teen environment variables khud-ba-khud ban jayenge.

Step 5: Pods Ko Apply Karo

bash
kubectl apply -f secret-access-pods.yaml

Explanation:

  • kubectl apply -f secret-access-pods.yaml: This command creates all three Pods.
  • Result: pod/secret-volume-test-pod created, pod/secret-env-test-pod created, pod/secret-env-all-test-pod created messages dikhenge.

Step 6: Pods Ke Andar Secret Access Verify Karo Chalo, har Pod mein jaakar verify karte hain ki Secrets theek se expose hue hain ya nahi.

Verify Secret as Volume (Pod 1):secret-volume-test-pod mein jao:

bash
kubectl exec -it secret-volume-test-pod -- bash
# Ab Pod ke andar ho, yahan type karo:
ls /etc/my-app-secrets/
cat /etc/my-app-secrets/db_username
cat /etc/my-app-secrets/db_password
exit # Pod se bahar aa jao

Explanation:

  • ls /etc/my-app-secrets/: Tumhein db_server, db_username, db_password naam ki files dikhengi.
  • cat /etc/my-app-secrets/db_username: Tumhein admin dikhega.
  • cat /etc/my-app-secrets/db_password: Tumhein P@ssw0rd! dikhega.
  • Result: Secrets successfully files ki tarah mount ho gaye hain!

Verify Secret as Individual Environment Variables (Pod 2):secret-env-test-pod mein jao:

bash
kubectl exec -it secret-env-test-pod -- bash
# Ab Pod ke andar ho, yahan type karo:
printenv | grep DB_ # Sirf 'DB_' se shuru hone wale env vars print karo
exit # Pod se bahar aa jao

Explanation:

  • printenv | grep DB_: Tumhein DB_USERNAME=admin, DB_PASSWORD=P@ssw0rd!, aur DB_SERVER_ADDRESS=mydatabase.example.com dikhne chahiye.
  • Result: Secrets successfully individual environment variables ban gaye hain!

Verify Secret as All Environment Variables (Pod 3):secret-env-all-test-pod mein jao:

bash
kubectl exec -it secret-env-all-test-pod -- bash
# Ab Pod ke andar ho, yahan type karo:
printenv | grep db_ # 'db_' (lowercase) se shuru hone wale env vars print karo, because original key names are lowercase
exit # Pod se bahar aa jao

Explanation:

  • printenv | grep db_: Tumhein db_server=mydatabase.example.com, db_username=admin, aur db_password=P@ssw0rd! dikhne chahiye.
  • Result: envFrom ne saare secrets ko automatically environment variables mein load kar diya hai!

Step 7: Secret Ko Delete Karo Jab kaam khatam ho jaye, toh Secret aur uske Pods ko delete kar do. Pehle Pods delete karna achha hai, phir Secret.

bash
kubectl delete -f secret-access-pods.yaml
kubectl delete -f my-secret.yaml

Explanation:

  • kubectl delete -f <file_name>: This command deletes the specified Kubernetes objects.

9.2 ConfigMaps: Tumhari Important Notepad (Non-Sensitive Settings) 🗒️

ConfigMaps kya hain?ConfigMaps (pronounced: kon-fig-maps) Kubernetes objects hain jo non-sensitive configuration data (normal settings) ko store karte hain. Jaise app ka default theme, log level, ya koi feature flag. ConfigMaps ka data plain text mein store hota hai (unencrypted), kyunki woh sensitive nahi hota.

  • Important Notepad Analogy: Jaise tumhare ghar mein ek notepad hai jahan tum important, non-secret jankari likhte ho, jaise shopping list, homework assignments, ya TV channels ki list. Koi bhi usse dekh sakta hai, koi problem nahi.

ConfigMaps Ko Kaise Use Karein Pods mein? Secrets ki tarah, ConfigMaps ko bhi Pods do tareeko se use kar sakte hain:

  1. Environment Variables ki Tarah:
  2. Volume ki Tarah (Files ki Tarah):

Step 1: ConfigMap Object Banao (Declarative Way) Apne computer pe ek new file my-configmap.yaml naam se banao aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct!

yaml
# File: my-configmap.yaml

# API version for ConfigMap objects
apiVersion: v1
# Type of Kubernetes object: ConfigMap
kind: ConfigMap
# Metadata for our ConfigMap
metadata:
  # Name of our ConfigMap
  name: my-app-general-config # This name will be used by Pods
# 'data' field stores the actual configuration key-value pairs in plain text.
data:
  app_theme: dark # App's theme setting
  log_level: INFO # Logging level for the application
  api_base_url: http://api.mygame.com/ # Base URL for an external API
  # You can also add multi-line data using the '|' (pipe) operator
  welcome_message: |
    Hello Player!
    Welcome to my awesome game!
    Enjoy playing!

Explanation (YAML file ke har section ki simplified jankari):

  • kind: ConfigMap: Hum ek ConfigMap bana rahe hain.
  • name: my-app-general-config: ConfigMap ka naam my-app-general-config hai.
  • data:: Yahan tum plain text mein key-value pairs define karte ho. app_theme: dark, log_level: INFO, api_base_url are example settings. welcome_message ek multi-line string hai.

Step 2: ConfigMap Ko Apply Karo

bash
kubectl apply -f my-configmap.yaml

Explanation:

  • kubectl apply -f my-configmap.yaml: This command creates the my-app-general-config ConfigMap.
  • Result: configmap/my-app-general-config created message dikhega.

Step 3: ConfigMap Ki Jankari Dekho (Values will be plain text)

bash
kubectl get configmap my-app-general-config -o yaml

Explanation:

  • kubectl get configmap my-app-general-config -o yaml: This command fetches the my-app-general-config and displays its full YAML definition.
  • Result: data section mein tumhe app_theme, log_level, api_base_url, welcome_message ki values plain text mein dikhengi, encoded nahi.
    yaml
    apiVersion: v1
    data:
      api_base_url: http://api.mygame.com/
      app_theme: dark
      log_level: INFO
      welcome_message: |-
        Hello Player!
        Welcome to my awesome game!
        Enjoy playing!
    kind: ConfigMap
    metadata:
      creationTimestamp: "2023-10-27T12:30:00Z"
      name: my-app-general-config
      namespace: default
      resourceVersion: "56789"
      uid: abcd-efgh-ijkl-mnop

Step 4: Pod Ko ConfigMap Access Karne Ke Liye File Banao Apne computer pe ek new file configmap-access-pod.yaml naam se banao aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct!

yaml
# File: configmap-access-pod.yaml

# Pod to demonstrate accessing ConfigMap as Environment Variables and as a Volume
apiVersion: v1
kind: Pod
metadata:
  name: config-test-pod # Pod's name
spec:
  containers:
  - name: config-consumer-container
    image: nginx # Using Nginx for demonstration
    env: # Define environment variables for this container
      - name: GAME_THEME # Name of the environment variable
        valueFrom:
          configMapKeyRef: # Get value from a ConfigMap key
            name: my-app-general-config # The name of the ConfigMap
            key: app_theme # The specific key within the ConfigMap whose value to use
      - name: LOG_LEVEL # Another environment variable
        valueFrom:
          configMapKeyRef:
            name: my-app-general-config
            key: log_level
    volumeMounts: # How to connect volumes to this container
      - name: config-data-volume # Name of the volume to mount (defined below)
        mountPath: "/etc/my-app-config" # Path inside the container where config files will appear
        readOnly: true # Good practice to keep config files read-only
  volumes: # Definition of volumes for the Pod
  - name: config-data-volume # Name of our volume
    configMap: # This volume will use a ConfigMap
      name: my-app-general-config # The name of the ConfigMap to use

Explanation (YAML file ke har section ki simplified jankari):

  • env: - name: GAME_THEME, valueFrom: configMapKeyRef: name: my-app-general-config, key: app_theme: Yahan my-app-general-config ConfigMap se app_theme key ki value nikal kar GAME_THEME naam ke environment variable mein daali jayegi.
  • volumeMounts: - name: config-data-volume, mountPath: "/etc/my-app-config": config-data-volume ko container ke andar /etc/my-app-config path pe mount kiya gaya hai.
  • volumes: - name: config-data-volume, configMap: name: my-app-general-config: config-data-volume my-app-general-config ConfigMap se data lega. Is mountPath pe app_theme, log_level, api_base_url, welcome_message naam ki files ban jayengi, jinmein unki respective config values hongi.

Step 5: Pod Ko Apply Karo

bash
kubectl apply -f configmap-access-pod.yaml

Explanation:

  • kubectl apply -f configmap-access-pod.yaml: This command creates the config-test-pod.
  • Result: pod/config-test-pod created message dikhega.

Step 6: Pod Ke Andar ConfigMap Access Verify Karoconfig-test-pod mein jao aur environment variables dekho:

bash
kubectl exec -it config-test-pod -- bash
# Ab Pod ke andar ho, yahan type karo:
printenv | grep GAME_THEME
printenv | grep LOG_LEVEL
exit # Pod se bahar aa jao

Explanation:

  • printenv | grep GAME_THEME: Tumhein GAME_THEME=dark dikhega.
  • printenv | grep LOG_LEVEL: Tumhein LOG_LEVEL=INFO dikhega.
  • Result: ConfigMap values successfully environment variables ban gaye hain!

Ab files bhi dekho:

bash
kubectl exec -it config-test-pod -- bash
# Ab Pod ke andar ho, yahan type karo:
ls /etc/my-app-config/
cat /etc/my-app-config/api_base_url
cat /etc/my-app-config/welcome_message
exit # Pod se bahar aa jao

Explanation:

  • ls /etc/my-app-config/: Tumhein api_base_url, app_theme, log_level, welcome_message naam ki files dikhengi.
  • cat /etc/my-app-config/api_base_url: Tumhein http://api.mygame.com/ dikhega.
  • cat /etc/my-app-config/welcome_message: Tumhein multi-line welcome_message dikhega.
  • Result: ConfigMap values successfully files ki tarah mount ho gaye hain!

Step 7: Cleanup - ConfigMap Ko Delete Karo Jab kaam khatam ho jaye, toh ConfigMap aur uske Pods ko delete kar do.

bash
kubectl delete -f configmap-access-pod.yaml
kubectl delete -f my-configmap.yaml

Explanation:

  • kubectl delete -f <file_name>: This command deletes the specified Kubernetes objects.

Secrets aur ConfigMaps dono apps ko external data provide karne ke liye use hote hain. Secrets sensitive data ke liye aur ConfigMaps non-sensitive data ke liye. Yeh apps ko flexible aur dynamic banate hain, kyunki tum settings ko bina app code change kiye badal sakte ho. Agle chapter mein hum ek baar wale aur scheduled tasks ke baare mein seekhenge! ⏰


Chapter 10: Ek Baar Wale aur Schedule Wale Kaam: Jobs aur CronJobs ⏰

Socho, tumhara game server Kubernetes mein chal raha hai. Kabhi-kabhi, tumhe kuch aise kaam karne hote hain jo app ke andar nahi hote, ya woh sirf ek baar ya ek specific time pe karne hote hain.

  • Ek Baar Wale Kaam: Jaise, game ke saare players ke scores ko calculate karke ek final report banana. Yeh kaam sirf ek baar karna hai. Ya ek script chalani hai jo database ko cleanup kare.
  • Schedule Wale Kaam: Jaise, har raat 12 baje game ke database ka backup lena. Ya har subah 6 baje analytics report generate karna. Yeh kaam roz ek hi time pe automatically hona chahiye.

Kubernetes mein, in do tarah ke tasks ke liye hum Jobs aur CronJobs use karte hain.

10.1 Jobs: One-Time Homework (Tasks that Run Once) 📚

Jobs kya hain?Job (pronounced: job) ek Kubernetes object hai. Yeh ek ya ek se zyada Pods ko chalaata hai jab tak woh kaam successfully complete na ho jaye.

  • Homework Assignment Analogy: Tumhein ek homework mila hai (Job). Jab tak tum use complete nahi kar lete, tum us pe kaam karte rahoge. Agar beech mein tumhari copy fat gayi ya pen toot gaya (Pod crash ho gaya), toh tum nayi copy pe phir se shuru karoge (Job use dobara chalaane ki koshish karega). Jab homework complete ho gaya, toh copy band kar ke rakh doge (Pod Completed ho jayega lekin delete nahi hoga).
  • Key Idea: Jobs ka main aim completions hai. Jab tak specified completions successful na ho jayein, Job Pods ko chalaata rahega.

Job ki Kuch Khaas Settings:

  • completions: Kitni baar yeh kaam successfully complete hona chahiye. Default 1 hota hai.
  • parallelism: Ek time pe kitne Pods ek saath chal sakte hain is Job ke liye. Default 1 hota hai.
  • backoffLimit: Agar Job ke Pods baar-baar fail ho rahe hain, toh kitni baar try karne ke baad Job ko Failed declare kar do. Default 6 hota hai.
  • activeDeadlineSeconds: Agar Job is time limit ke andar complete nahi hua, toh use Failed mark kar do.

Real-Life Example: Tum Pi (π) ke 2000 digits calculate karna chahte ho. Yeh ek lamba, ek baar wala calculation hai.

Step 1: Job Ki YAML File Banao Apne computer pe ek new file pi-calculator-job.yaml naam se banao aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct!

yaml
# File: pi-calculator-job.yaml

# API version for Job objects (batch/v1 for Jobs)
apiVersion: batch/v1
# Type of Kubernetes object: Job
kind: Job
# Metadata for our Job
metadata:
  # Name of our Job
  name: pi-calculator-job # This name identifies our specific task
# Specification for the Job
spec:
  # 'parallelism' tells Kubernetes how many Pods should run concurrently (at the same time) for this Job.
  # Here, 2 Pods will run in parallel to calculate Pi.
  parallelism: 2
  # 'completions' tells Kubernetes how many times the Job needs to complete successfully.
  # The Job will keep creating Pods until 10 Pods have successfully completed their task.
  completions: 10
  # 'backoffLimit' defines how many times the Job should retry running a Pod if it fails.
  # If a Pod fails 5 times, the Job will be considered failed and won't retry further.
  backoffLimit: 5
  # 'activeDeadlineSeconds' specifies the maximum time in seconds for the Job to be active.
  # If the Job doesn't complete within 100 seconds, it will be terminated.
  activeDeadlineSeconds: 100
  # 'template' is the blueprint for the Pods that this Job will create.
  template:
    # Specification for the Pods
    spec:
      containers:
      - name: pi-calculation-container # Name of the container inside the Pod
        image: perl # Using the 'perl' Docker image (which has the necessary math libraries)
        command: ["perl",  "-Mbignum=bpi", "-wle", "print bpi(2000)"]
        # Explanation of command:
        # `perl`: The Perl interpreter.
        # `-Mbignum=bpi`: Loads the 'bignum' module, specifically the 'bpi' function for high-precision Pi calculation.
        # `-wle`: Common Perl flags for warnings, loop, and newline.
        # `"print bpi(2000)"`: Prints Pi calculated to 2000 decimal places.
      # 'restartPolicy' for the Pods created by this Job.
      # 'Never' is typical for Jobs, as the Job controller manages retries.
      # If set to 'OnFailure', the Job's Pods would restart internally on failure,
      # but 'Never' allows the Job controller to create new Pods for failed attempts.
      restartPolicy: Never

Explanation (YAML file ke har section ki simplified jankari):

  • kind: Job: Hum ek Job bana rahe hain.
  • name: pi-calculator-job: Job ka naam pi-calculator-job hai.
  • spec:: Job ki settings.
    • parallelism: 2: Iska matlab hai ki ek time pe is Job ke liye 2 Pods ek saath chal sakte hain.
    • completions: 10: Iska matlab hai ki Job tab tak Pods ko chalaata rahega jab tak total 10 Pods successfully complete na ho jayein.
    • backoffLimit: 5: Agar koi Pod (ya task) fail ho gaya, toh Job use 5 baar tak dobara chalaane ki koshish karega. 5 baar fail hone ke baad, Job ko Failed declare kar dega.
    • activeDeadlineSeconds: 100: Agar yeh Job 100 seconds ke andar complete nahi hua, toh use Failed mark kar diya jayega (chahe woh abhi bhi chal raha ho).
    • template: spec: containers: - name: pi-calculation-container, image: perl, command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(2000)"]: perl image use kar rahe hain aur usmein ek command chala rahe hain jo Pi ke 2000 digits calculate karti hai.
    • restartPolicy: Never: Yeh Pod ke liye hai. Agar Pod fail ho toh khud restart mat ho, Job Controller use handle karega (naya Pod bana kar).

Step 2: Job Ko Apply Karo

bash
kubectl apply -f pi-calculator-job.yaml

Explanation:

  • kubectl apply -f pi-calculator-job.yaml: This command creates the pi-calculator-job.
  • Result: job.batch/pi-calculator-job created message dikhega.

Step 3: Pods aur Job Ki Status Dekho Pods ko watch karo, ek alag terminal mein. Isko chalta rehne do.

bash
kubectl get pods -w

Explanation:

  • kubectl get pods -w: This command will show live updates of your Pods.
  • What to observe: Tumhein pi-calculator-job- naam ke Pods dikhenge. Tum dekhoge ki ek time pe parallelism: 2 ki wajah se 2 Pods Running honge. Jab woh complete ho jayenge, toh STATUS Completed dikhega. Yeh process repeat hota rahega jab tak total completions: 10 Pods Completed na ho jayein.
    NAME                      READY   STATUS      RESTARTS   AGE
    pi-calculator-job-abcd    0/1     Completed   0          10s
    pi-calculator-job-efgh    0/1     Completed   0          10s
    pi-calculator-job-ijkl    0/1     Running     0          2s
    pi-calculator-job-mnop    0/1     Running     0          2s
    # ... more pods will be created and complete until 10 completions are met ...

kubectl get pods -w wale terminal ko Ctrl+C press karke band kar do.

Job ki status dekho:

bash
kubectl get jobs

Explanation:

  • kubectl get jobs: This command lists all Jobs.
  • Result: Tumhein pi-calculator-job dikhega. COMPLETIONS column mein 10/10 hona chahiye, matlab Job successfully complete ho gaya hai.
    NAME                 COMPLETIONS   DURATION   AGE
    pi-calculator-job    10/10         30s        40s
    • COMPLETIONS: 10/10 matlab 10 Pods successfully complete ho gaye hain, out of 10 desired.
    • DURATION: Job ko complete hone mein kitna time laga.

Step 4: Pod Ke Logs Dekho (Result) Job complete hone ke baad bhi Pods delete nahi hote (kyunki restartPolicy: Never tha). Tum unke logs dekh sakte ho, jahan Pi ke digits dikhenge. Kisi bhi pi-calculator-job- Pod ka poora naam copy karo (jaise pi-calculator-job-abcd).

bash
kubectl logs <pod-name-of-any-completed-pi-job>
# Example: kubectl logs pi-calculator-job-abcd

Explanation:

  • kubectl logs <pod_name>: This command shows the logs of the specified Pod.
  • Result: Tumhein Pi ke 2000 digits dikhenge! 🤯
    3.14159265358979323846264338327950288419716939937510... (and so on)

Step 5: Job Ko Delete Karo Jab kaam khatam ho jaye, toh Job ko delete kar do. Jab tum Job ko delete karte ho, toh uske saare Pods bhi delete ho jaate hain.

bash
kubectl delete -f pi-calculator-job.yaml

Explanation:

  • kubectl delete -f pi-calculator-job.yaml: This command deletes the pi-calculator-job.
  • Result: job.batch "pi-calculator-job" deleted message dikhega.

10.2 CronJobs: Tumhara Daily Alarm (Tasks that Run on Schedule) 🔔

CronJobs kya hain?CronJob (pronounced: kron-job) ek Kubernetes object hai jo Jobs ko schedule karta hai. Jaise tum apne phone mein alarm set karte ho har subah 7 baje ka. CronJob bhi waisa hi hai, yeh Jobs ko ek specific time pe (jaise har raat 12 baje) ya ek specific interval pe (jaise har ghante) chalaata hai.

  • Daily Alarm Analogy: Jaise tumhara daily alarm (CronJob) har subah 7 baje bajta hai (aur woh alarm bajna ek Job hai).
  • Purpose: CronJobs background tasks ke liye perfect hain jo regularly run honi chahiye, jaise database backups, report generation, data syncing.

Schedule Kaise Define Karenge? (Cron Format) CronJob ke schedule ko define karne ke liye crontab format use hota hai. Yeh kuch ajeeb sa dikhta hai, lekin bahut powerful hai. Ismein 5 stars * * * * * hote hain, aur har star ka matlab alag hota hai:

minute hour day_of_month month day_of_week

#  ┌───────────── minute (0 - 59)
#  │ ┌───────────── hour (0 - 23)
#  │ │ ┌───────────── day of the month (1 - 31)
#  │ │ │ ┌───────────── month (1 - 12)
#  │ │ │ │ ┌───────────── day of the week (0 - 6, Sunday=0 or 7)
#  │ │ │ │ │
#  * * * * *

Examples:

  • */1 * * * *: Har minute. (Jaise har 1 minute baad Hello print karo).
  • 0 */2 * * *: Har 2 ghante mein, exactly 0th minute pe (jaise 02:00, 04:00, 06:00, etc.)
  • 0 0 * * 0: Har Sunday subah 12 baje (midnight).
  • * means "every" (har)
  • / means "repetitive" (har X baad)

Step 1: CronJob Ki YAML File Banao Apne computer pe ek new file hello-cronjob.yaml naam se banao aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct!

yaml
# File: hello-cronjob.yaml

# API version for CronJob objects (batch/v1 for CronJobs)
apiVersion: batch/v1
# Type of Kubernetes object: CronJob
kind: CronJob
# Metadata for our CronJob
metadata:
  # Name of our CronJob
  name: hello-world-cronjob # This name identifies our scheduled task
# Specification for the CronJob
spec:
  # 'schedule' defines when the Job will run, using the crontab format.
  # "*/1 * * * *" means: "At every 1st minute of every hour, every day of the month, every month, and every day of the week."
  # In simple terms: Run every minute.
  schedule: "*/1 * * * *"
  # 'jobTemplate' defines the Job that will be created and executed by the CronJob.
  # This is essentially a Job definition, but nested inside the CronJob.
  jobTemplate:
    # Specification for the Job that will be created
    spec:
      # Template for the Pods that this Job will create
      template:
        # Specification for the Pods
        spec:
          containers:
          - name: hello-printer-container # Name of the container
            image: busybox # Using 'busybox' image for a simple task
            imagePullPolicy: IfNotPresent # Only pull image if it's not already present on the Node
            command: # Command to execute inside the container
            - /bin/sh # Start a shell interpreter
            - -c # Execute the following string as a command
            - "date; echo Hello from Kubernetes Cluster!" # Prints current date and a greeting message
          # 'restartPolicy' for the Pods created by this Job.
          # 'OnFailure' means: If the container fails (exits with non-zero code), it will be restarted.
          # 'Never' could also be used here, allowing the Job controller to manage retries by creating new Pods.
          restartPolicy: OnFailure

Explanation (YAML file ke har section ki simplified jankari):

  • kind: CronJob: Hum ek CronJob bana rahe hain.
  • name: hello-world-cronjob: CronJob ka naam hello-world-cronjob hai.
  • spec:: CronJob ki settings.
    • schedule: "*/1 * * * *": Yeh sabse important setting hai! Iska matlab hai ki har 1 minute mein Job chalao.
    • jobTemplate:: Yeh Job ki definition hai jo CronJob har minute banayega. Yeh bilkul waisa hi Job hai jaisa humne pichhle section mein seekha tha, bas yeh CronJob ke andar nested hai.
    • template: spec: containers: - name: hello-printer-container, image: busybox, command: ["/bin/sh", "-c", "date; echo Hello from Kubernetes Cluster!"]: busybox image use kar rahe hain aur ismein ek simple command chalayenge jo current date aur "Hello from Kubernetes Cluster!" message print karegi.
    • restartPolicy: OnFailure: Agar Pod fail ho, toh Job use restart karega.

Step 2: CronJob Ko Apply Karo

bash
kubectl apply -f hello-cronjob.yaml

Explanation:

  • kubectl apply -f hello-cronjob.yaml: This command creates the hello-world-cronjob.
  • Result: cronjob.batch/hello-world-cronjob created message dikhega.

Step 3: CronJob aur Pods Ki Status Dekho CronJobs ki status dekho:

bash
kubectl get cronjobs

Explanation:

  • kubectl get cronjobs: This command lists all CronJobs.
  • Result: Tumhein hello-world-cronjob dikhega. SCHEDULE column mein */1 * * * * dikhega.
    NAME                 SCHEDULE    SUSPEND   FORBIDDEN   AGE
    hello-world-cronjob  */1 * * * *   False     False       10s

Pods ko watch karo, ek alag terminal mein. Isko chalta rehne do.

bash
kubectl get pods -w

Explanation:

  • kubectl get pods -w: This command will show live updates of your Pods.
  • What to observe: Tumhein dikhega ki har minute ek naya Pod hello-world-cronjob- se shuru ho kar banega, Running hoga, aur phir Completed ho jayega. (Aksar Pods ke naam ke baad ek timestamp ya hash hota hai, jaise hello-world-cronjob-1678881234-abcd).
    NAME                                READY   STATUS      RESTARTS   AGE
    hello-world-cronjob-1678881234-abcd   0/1     Completed   0          40s
    hello-world-cronjob-1678881294-efgh   0/1     ContainerCreating 0          5s

kubectl get pods -w wale terminal ko Ctrl+C press karke band kar do.

Step 4: Pod Ke Logs Dekho (Result) Kisi bhi hello-world-cronjob- Pod ka poora naam copy karo (jo Completed ho gaya ho) aur logs dekho:

bash
kubectl logs <pod-name-of-any-completed-cronjob-pod>
# Example: kubectl logs hello-world-cronjob-1678881234-abcd

Explanation:

  • kubectl logs <pod_name>: This command shows the logs of the specified Pod.
  • Result: Tumhein current date aur "Hello from Kubernetes Cluster!" message dikhega.
    Fri Oct 27 12:45:00 UTC 2023
    Hello from Kubernetes Cluster!

Step 5: CronJob Ko Delete Karo Jab kaam khatam ho jaye, toh CronJob ko delete kar do. Jab tum CronJob ko delete karte ho, toh uske saare Jobs aur unke Pods bhi delete ho jaate hain.

bash
kubectl delete -f hello-cronjob.yaml

Explanation:

  • kubectl delete -f hello-cronjob.yaml: This command deletes the hello-world-cronjob.
  • Result: cronjob.batch "hello-world-cronjob" deleted message dikhega.

Jobs aur CronJobs bahut kaam aate hain jab tumhe automated tasks ya background processes chalane hon Kubernetes mein. Yeh tumhe manually tasks run karne ya servers pe logon kar ke scripts chalane se bachate hain. Bahut convenient, hai na? Agle chapter mein hum seekhenge ki apps ko har Node pe kaise chalate hain! 🌐


Chapter 11: Har Computer Pe Ek App: DaemonSets 🌐

Socho, tumhare paas ek school hai aur usmein bahut saare computers (Nodes) hain. Ab tumhe har computer pe ek antivirus software install karna hai. Kya tum har computer pe manually jaakar install karoge? Nahi, yeh toh bahut mushkil hoga, khaas kar agar school mein 1000 computers hon! 😫

Ya phir, tumhe har computer ke logs ko collect karke ek central server pe bhejna hai. Har computer pe log collector install karna aur use manage karna kitna mushkil hoga!

Yahin pe Kubernetes ka DaemonSet (pronounced: dee-mun-set) kaam aata hai!

11.1 DaemonSets Kya Hote Hain? (Like Antivirus on Every PC) 🛡️

  • DaemonSet: DaemonSet ek Kubernetes object hai jo yeh ensure karta hai ki tumhara ek particular app (Pod) har Node (computer) par chal raha ho. Aur agar tum cluster mein naya Node add karte ho, toh woh app automatically us naye Node pe bhi chalu ho jata hai, bina kisi manual effort ke!
  • Antivirus Analogy: DaemonSet bilkul ek antivirus software ki tarah hai. Jab tum school mein naya computer laate ho, toh antivirus automatically us pe install ho jata hai. Aur agar koi purana computer kharab ho gaya, toh us pe antivirus bhi band ho jata hai (jab tak woh theek na ho ya remove na ho).
  • Key Idea: DaemonSets ka goal hai "one Pod per Node".

Real-Life Example: Clusters mein monitoring agents (jo Nodes ki health aur performance check karte hain), log collectors (jo logs collect karke central server pe bhejte hain), ya network plugins (jo Pods ke beech networking manage karte hain) hote hain jo har Node pe chalne chahiye. DaemonSets in apps ko manage karne ke liye perfect hain.

Step 1: DaemonSet Ki YAML File Banao Apne computer pe ek new file log-daemonset.yaml naam se banao aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct!

yaml
# File: log-daemonset.yaml

# API version for DaemonSet objects (apps/v1 for DaemonSets)
apiVersion: apps/v1
# Type of Kubernetes object: DaemonSet
kind: DaemonSet
# Metadata for our DaemonSet
metadata:
  name: fluentd-log-collector # Name of our DaemonSet
  labels:
    app: fluentd-logging # Label for the DaemonSet itself
# Specification for the DaemonSet
spec:
  # 'selector' tells the DaemonSet which Pods it should manage.
  # This MUST match the labels in the Pod template below.
  selector:
    matchLabels:
      name: fluentd-agent # This DaemonSet will manage Pods with 'name: fluentd-agent' label
  # 'template' is the blueprint for the Pods that this DaemonSet will create on each Node.
  template:
    metadata:
      labels:
        name: fluentd-agent # Pods created by this DaemonSet will have this label (MUST match selector)
    # Specification for the Pods
    spec:
      # 'tolerations' allow a Pod to be scheduled on Nodes that have a 'taint'.
      # Master nodes usually have a 'taint' (node-role.kubernetes.io/master:NoSchedule)
      # to prevent regular Pods from running on them.
      # If you want this DaemonSet to also run on Master nodes, you need to add this toleration.
      tolerations:
      - key: node-role.kubernetes.io/master # Key of the taint on the Master node
        effect: NoSchedule # Effect of the taint (prevents scheduling if not tolerated)
                           # Removing this if your Master node is not tainted or you don't want it to run on Master
      containers:
      - name: fluentd-log-agent # Name of the container inside the Pod
        # Image for the log collector (Fluentd)
        image: quay.io/fluentd_elasticsearch/fluentd:v2.5.2 # Fluentd log agent image
        resources: # Resource limitations for the container (CPU and Memory)
          limits:
            memory: 200Mi # Maximum 200 Megabytes of memory
          requests:
            cpu: 100m # Request 100 millicores of CPU (100m = 0.1 CPU core)
            memory: 200Mi # Request 200 Megabytes of memory
        # 'volumeMounts' define how the container accesses volumes.
        # Here, we are mounting hostPath volumes to collect logs from the Node's file system.
        volumeMounts:
        - name: varlog-host # Name of the volume to mount (defined below)
          mountPath: /var/log # Path inside the container where Node's /var/log will be visible
        - name: docker-containers-log-host # Another volume
          mountPath: /var/lib/docker/containers # Path inside the container where Node's docker logs will be visible
          readOnly: true # IMPORTANT: Ensure this volume is read-only to prevent accidental modification of host files
      terminationGracePeriodSeconds: 30 # Time given to the Pod to shut down gracefully
      # 'volumes' define the actual storage volumes that the Pod can use.
      # Here, we use 'hostPath' volumes to directly access directories on the Node's file system.
      volumes:
      - name: varlog-host # Name of our first volume
        hostPath: # Type of volume: hostPath (accesses a path on the host Node)
          path: /var/log # The actual path on the Node's file system
      - name: docker-containers-log-host # Name of our second volume
        hostPath:
          path: /var/lib/docker/containers # The actual path on the Node's file system for Docker container logs

Explanation (YAML file ke har section ki simplified jankari):

  • kind: DaemonSet: Hum ek DaemonSet bana rahe hain.
  • name: fluentd-log-collector: DaemonSet ka naam fluentd-log-collector hai.
  • selector: matchLabels: name: fluentd-agent: DaemonSet name: fluentd-agent label wale Pods ko manage karega. (Yeh label Pod template mein bhi hona chahiye).
  • template:: Ismein Pod ki blueprint hai.
    • metadata: labels: name: fluentd-agent: Pods ko yeh label diya gaya hai, jo selector se match karta hai.
    • spec: tolerations:: Yeh important hai! tolerations Pods ko un Nodes pe chalne ki permission dete hain jinpe taints lage hote hain (taints Chapter 14 mein detailed hain). Kubernetes Master Nodes pe by default node-role.kubernetes.io/master:NoSchedule ka taint hota hai, matlab normal Pods unpe nahi chal sakte. Agar tumhe fluentd jaise log collectors ko Master Node pe bhi chalana hai (jo ki achha practice hai), toh yeh toleration add karna padega.
    • containers: - name: fluentd-log-agent, image: quay.io/fluentd_elasticsearch/fluentd:v2.5.2: Hum fluentd naam ka ek log collector app use kar rahe hain.
    • resources: limits: memory: 200Mi, requests: cpu: 100m, memory: 200Mi: Yeh container ke liye CPU aur Memory limits aur requests define karta hai.
    • volumeMounts aur volumes (type hostPath): Yeh bahut important hai! hostPath type ke volumes use hote hain jab tumhe Pod ko Node ke actual file system (folders) se connect karna ho. Yahan, fluentd agent Node ke /var/log (system logs) aur /var/lib/docker/containers (Docker container ke logs) folders ko access karega. readOnly: true ka matlab hai ki Pod in files ko sirf padh sakta hai, change nahi kar sakta, jo security ke liye achha hai.

Step 2: DaemonSet Ko Apply Karo

bash
kubectl apply -f log-daemonset.yaml

Explanation:

  • kubectl apply -f log-daemonset.yaml: This command creates the fluentd-log-collector DaemonSet.
  • Result: daemonset.apps/fluentd-log-collector created message dikhega.

Step 3: DaemonSet aur Pods Ki Status Dekho Chalo, dekhte hain ki hamara DaemonSet successfully bana aur usne Pods banaye ya nahi. kubectl get daemonset se tum DaemonSet ki summary dekh sakte ho, aur kubectl get pods -o wide se Pods ki detail.

bash
kubectl get daemonset

Explanation:

  • kubectl get daemonset: This command lists all DaemonSets.
  • Result: Tumhein fluentd-log-collector dikhega.
    NAME                    DESIRED   CURRENT   READY   UP-TO-DATE   AVAILABLE   NODE SELECTOR   AGE
    fluentd-log-collector   1         1         1       1            1           <none>          15s
    • DESIRED: Kitne Pods chalne chahiye (har Node pe ek).
    • CURRENT: Kitne Pods abhi chal rahe hain.
    • READY: Kitne Pods ready hain.
    • Minikube mein: DESIRED, CURRENT, READY count 1 hona chahiye, kyunki Minikube mein by default sirf ek hi Node hota hai.

Pods ki list dekho (-o wide se Node ka naam bhi dikhega):

bash
kubectl get pods -o wide

Explanation:

  • kubectl get pods -o wide: This command lists all Pods with detailed info.
  • Result: Tumhein fluentd-log-collector- naam ka ek Pod Running dikhega, aur uski NODE minikube dikhegi.
    NAME                                     READY   STATUS    RESTARTS   AGE   IP           NODE       NOMINATED NODE   READINESS GATES
    fluentd-log-collector-abcdef             1/1     Running   0          30s   172.17.0.7   minikube   <none>           <none>

Step 4: Naya Node Add Karo (Minikube mein Magic!) Ab, hum Minikube mein ek naya Node add karenge. Socho, jaise school mein ek naya computer aaya. DaemonSet ka magic dekho!

Pehle, ek alag terminal window open karo aur usmein Pods ko watch karo. Isko chalta rehne do.

bash
kubectl get pods -w

Explanation:

  • Is terminal mein tum Pods ki live updates dekh paoge.

Ab, original terminal mein wapas jao aur Minikube mein naya Node add karo:

bash
minikube node add

Explanation:

  • minikube node add: Yeh command Minikube ke andar ek naya virtual Node banayega. Ismein thoda time lag sakta hai, jaise ek naya computer set up hone mein.
  • What happens: Minikube ek naya Node bana kar use cluster mein add karega. Jaise hi naya Node Ready hoga, fluentd-log-collector DaemonSet dekhega ki "Oh! Ek naya Node aaya hai, aur ispe fluentd-agent Pod nahi hai." Toh, DaemonSet automatically us naye Node pe fluentd-agent Pod ki ek copy bana dega!
  • Result: Tumhein minikube-m02 (ya jo bhi naya Node naam hai) jaisa kuch dikhega. Aur minikube node add command ke chalte hi, kubectl get pods -w wale terminal mein tumhe fluentd-log-collector- ka ek naya Pod ContainerCreating se Running state mein aayega, aur uski NODE minikube-m02 (ya jo bhi naya Node naam hai) hogi! 🎉
    NAME                                     READY   STATUS             RESTARTS   AGE   IP           NODE
    fluentd-log-collector-abcdef             1/1     Running            0          2m    172.17.0.7   minikube
    fluentd-log-collector-newhash-uvwx       0/1     ContainerCreating  0          5s    <none>       minikube-m02 # New Pod for the new Node!
    # ... after a few seconds ...
    fluentd-log-collector-newhash-uvwx       1/1     Running            0          15s   172.17.0.8   minikube-m02
    kubectl get pods -w wale terminal ko Ctrl+C press karke band kar do.

Step 5: Node Ko Delete Karo Jab kaam khatam ho jaye, toh naye Node ko delete kar do. DaemonSet phir se automatic behavior dikhayega.

bash
minikube node delete minikube-m02 # Ya jo bhi tumhare naye Node ka naam hai

Explanation:

  • minikube node delete <node_name>: This command deletes the specified Node from the Minikube cluster.
  • What happens: Node minikube-m02 delete ho jayega. fluentd-log-collector DaemonSet dekhega ki ab minikube-m02 Node nahi hai, toh woh us Node pe chal rahe fluentd-agent Pod ko bhi delete kar dega.
  • Result: Tumhein minikube-m02 deleted message dikhega. kubectl get pods se dekhoge toh fluentd-log-collector- ka woh Pod gayab ho jayega.

Step 6: Cleanup - DaemonSet Ko Delete Karo Jab kaam khatam ho jaye, toh DaemonSet ko delete kar do.

bash
kubectl delete -f log-daemonset.yaml

Explanation:

  • kubectl delete -f log-daemonset.yaml: This command deletes the fluentd-log-collector DaemonSet and any Pods it might still be managing.

DaemonSets bahut useful hain jab tumhe cluster ke har Node pe koi background process ya agent chalana ho. Yeh automatic hote hain aur cluster ke Nodes ke saath sync mein rehte hain, chahe Nodes add hon ya remove hon. Agle chapter mein hum data ko hamesha ke liye save karna seekhenge! 💾


Chapter 12: Data ko Mehfooz Rakhna: Persistent Volumes (PV) aur Persistent Volume Claims (PVC) 💾

Pichhle chapters mein humne Deployments se apps ki copies banani seekhi. Agar tumhara game server ya database Kubernetes mein chal raha hai, aur usmein players ka score, unki progress, ya dusra important data store hota hai.

Humne Chapter 4 mein emptyDir aur Chapter 11 mein hostPath volumes dekhe the. Yaad hai?

  • emptyDir: Pod delete toh data gayab. Temporary!
  • hostPath: Node ke local storage pe data rakhta hai. Agar woh Node kharab ho gaya ya Pod kisi doosre Node pe chala gaya, toh data lost ho sakta hai.

Problem: Agar game server wala Pod crash ho gaya ya delete ho gaya, aur uske saath saara data bhi chala gaya toh? Sab players ka progress gayab! 😱 Ye toh bahut buri baat hai! Humara data permanent (persistent) hona chahiye.

Yahin pe Kubernetes ke Persistent Volumes (PV) (pronounced: per-sis-tent vo-lyooms) aur Persistent Volume Claims (PVC) (pronounced: per-sis-tent vo-lyoom klaims) kaam aate hain. Socho, jaise tumhare ghar mein ek magic hard drive hai jo computer band hone ke baad bhi data ko save rakhti hai.

12.1 Data ka Magic Hard Drive (Permanent Storage) 🪄

  • Persistent Volume (PV): PV ek actual physical storage area hai jo Kubernetes cluster ke bahar exist karta hai. Yeh Network-attached storage (NAS) ho sakta hai, jaise ek bada hard drive jo network se connect hota hai, ya cloud storage (AWS EBS, Google Persistent Disk, Azure Disk). PV Kubernetes ko batata hai ki "mere paas itni storage hai, yahan pe."
    • Storage Room Analogy: PV ek bada sa storage room hai jo tumhare ghar (Kubernetes cluster) ke bahar hai. Ismein tum apna saara important saaman rakhte ho, aur woh hamesha wahi rehta hai, chahe tum ghar (Pods) badal bhi lo ya ghar (Nodes) toot bhi jaye.
  • Persistent Volume Claim (PVC): PVC ek request hai jo tumhara app (Pod) karta hai Kubernetes se, ki "Mujhe itni storage chahiye, aur woh is type ki honi chahiye!" PVC Pod aur actual storage (PV) ke beech ek bridge ka kaam karta hai.
    • Request Form Analogy: PVC ek request form hai jo tum storage room (PV) mein space maangne ke liye bharte ho. Tum batate ho ki tumhe kitni space chahiye aur woh kaisi honi chahiye (jaise read/write permission). Tumhe yeh batane ki zarurat nahi ki storage room kahan hai, bas tumhein space chahiye.

Kyun Do Cheezein? (PV aur PVC)? Socho, school mein library (PV) hai. Usmein bahut saari books (storage) hain. Lekin tum seedhe book nahi utha sakte. Tumhe librarian (Kubernetes) ko ek form (PVC) dena padta hai ki "Mujhe yeh book chahiye." Isse fayda kya hai?

  • Separation of Duties: Jo log storage banate hain (System Administrators ya Infrastructure Engineers), woh PV banate hain (unhein pata hota hai ki storage kahan se aa raha hai). Jo log apps chalate hain (Developers), woh bas PVC se request karte hain (unhein nahi pata hota ki asal mein storage kahan se aa raha hai, bas unhein mil jaata hai). Isse sabka kaam easy ho jaata hai.
  • Flexibility: Kubernetes automatically tumhare request (PVC) se best available storage (PV) ko match kar deta hai.

Real-Life Example: Ek database, jaise MySQL, ko data store karna hota hai jo Pod delete hone ke baad bhi rahe. MySQL अपना सारा data /var/lib/mysql folder में store करता है।

12.2 Simulating an NFS Server for Minikube (Our Fake Storage) 🧪

Real clusters mein, PVs Network File System (NFS) servers ya cloud storage (AWS EBS, Azure Disk) se connect hote hain. Minikube ek single-node environment hai, toh usmein real external storage ko connect karna mushkil ho sakta hai. Isliye, hum ek Docker container mein ek chhota sa NFS server chalayenge, jo hamare liye ek "fake" storage server ki tarah kaam karega.

Step 1: NFS Server Simulate Karne Ke Liye Docker Setup Karo Pehle ensure karo ki tumhare computer pe Docker installed hai aur running hai. Agar nahi hai, toh Google pe search karo "Install Docker Desktop" (Windows/macOS ke liye) ya "Install Docker Engine Ubuntu".

bash
# Command 1: Create a Docker Volume.
# This is a persistent storage managed by Docker, which our NFS server container will use.
# So, even if the NFS container is deleted, this data volume will persist.
docker volume create minikube-nfs-data

Explanation:

  • docker volume create minikube-nfs-data: This command creates a named Docker volume called minikube-nfs-data. This volume will be the actual place where our "fake" NFS server stores its data. It's like creating an empty hard drive for our server.
bash
# Command 2: Create a Docker Network with a specific IP range.
# We want our NFS server container to have a fixed, known IP address (10.255.255.10).
# This is important because our Kubernetes PV will need to know this IP.
docker network create --driver=bridge --subnet=10.255.255.0/24 --ip-range=10.255.255.0/24 --gateway=10.255.255.10 minikube-nfs-net

Explanation:

  • docker network create: This command creates a new Docker network.
  • --driver=bridge: Specifies the network driver (standard for local networks).
  • --subnet=10.255.255.0/24: Defines the IP address range for this network (e.g., 10.255.255.0 to 10.255.255.255).
  • --ip-range=10.255.255.0/24: Defines the range from which IPs for containers on this network will be assigned.
  • --gateway=10.255.255.10: This is crucial! It sets the gateway IP for this network. When we run our NFS container on this network, it will likely get this IP address. We will use 10.255.255.10 as our NFS server's IP in the PV definition.
  • minikube-nfs-net: The name of our new Docker network.
bash
# Command 3: Run the NFS server container.
# This container acts as our "fake" NFS server that Kubernetes will connect to.
docker run -dit --privileged --restart unless-stopped -e SHARED_DIRECTORY=/data -v minikube-nfs-data:/data --network minikube-nfs-net -p 2049:2049 --name nfs-server-sim ozgurozturknet/nfs:latest

Explanation:

  • docker run: This command creates and runs a new Docker container.
  • -d: detached mode, matlab container background mein chalega.
  • -i: interactive mode.
  • -t: tty (terminal) mode.
  • --privileged: Gives the container extra permissions, sometimes needed for NFS.
  • --restart unless-stopped: Agar container crash ho ya Docker restart ho, toh container automatically restart ho jayega, jab tak hum usko manually stop na karein.
  • -e SHARED_DIRECTORY=/data: Sets an environment variable inside the container, telling the NFS server that /data is the directory to share.
  • -v minikube-nfs-data:/data: Connects our Docker volume. minikube-nfs-data (jo humne Step 1 mein banaya tha) ko container ke andar /data directory pe mount karta hai. Matlab, jo bhi data /data mein store hoga container ke andar, woh minikube-nfs-data volume mein save hoga.
  • --network minikube-nfs-net: Connects our container to the minikube-nfs-net network (jo humne Step 2 mein banaya tha). Isse container ko 10.255.255.10 IP mil jayega.
  • -p 2049:2049: port mapping. Hamare computer ke port 2049 ko container ke port 2049 se jodta hai. NFS server default roop se port 2049 use karta hai.
  • --name nfs-server-sim: Container ka naam nfs-server-sim rakhta hai.
  • ozgurozturknet/nfs:latest: Docker image jo hum use kar rahe hain, yeh ek pehle se bana hua chhota NFS server hai.
  • Result: nfs-server-sim naam ka Docker container background mein chalna shuru ho jayega. Tum docker ps chala ke confirm kar sakte ho. Iska IP 10.255.255.10 hoga.
    CONTAINER ID   IMAGE                    COMMAND                  CREATED         STATUS         PORTS                    NAMES
    b1234567890a   ozgurozturknet/nfs:latest "/usr/sbin/rpcbind -f…"   2 minutes ago   Up 2 minutes   0.0.0.0:2049->2049/tcp   nfs-server-sim

12.3 PV: Tumhara Storage Room (The Actual Storage Unit) 📦

Ab jab hamara "fake" NFS server ready hai, chalo Kubernetes mein PersistentVolume (PV) define karte hain. Yeh PV Kubernetes ko batayega ki "mere paas yeh storage available hai, jiska IP 10.255.255.10 hai aur shared folder / hai."

Step 2: Persistent Volume (PV) File Banao Apne computer pe ek new file mysql-pv.yaml naam se banao aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct!

yaml
# File: mysql-pv.yaml

# API version for PersistentVolume objects (v1 for PVs)
apiVersion: v1
# Type of Kubernetes object: PersistentVolume
kind: PersistentVolume
# Metadata for our PersistentVolume
metadata:
   # Name of our PersistentVolume. This is a unique name within the cluster.
   name: mysql-storage-pv
   # Labels for the PV. These labels can be used by PersistentVolumeClaims (PVCs)
   # to select a specific PV.
   labels:
     app: mysql # We are labeling this PV as suitable for MySQL applications
# Specification for the PersistentVolume
spec:
  # 'capacity' defines the size of the storage that this PV represents.
  capacity:
    storage: 5Gi # This PV provides 5 Gigibytes (GiB) of storage.
                 # 'Gi' (Gibibytes) is power of 2 (1024^3 bytes), 'GB' (Gigabytes) is power of 10 (1000^3 bytes).
  # 'accessModes' define how the storage can be mounted and accessed by Nodes/Pods.
  # Different types:
  # - ReadWriteOnce (RWO): Can be mounted as read-write by a single Node. (Most common for databases)
  # - ReadOnlyMany (ROX): Can be mounted as read-only by many Nodes.
  # - ReadWriteMany (RWX): Can be mounted as read-write by many Nodes. (Less common, requires specific storage solutions)
  accessModes:
    - ReadWriteOnce # This storage can be mounted read-write by only one Node at a time.
  # 'persistentVolumeReclaimPolicy' defines what happens to the PV and its data
  # when the PersistentVolumeClaim (PVC) that uses it is deleted.
  # - Retain: The PV and its data are retained. You have to manually clean up. (Safest for critical data)
  # - Recycle: The data on the volume is deleted, and the PV becomes available for reuse. (Less common now)
  # - Delete: The PV and the underlying storage asset (e.g., cloud disk) are deleted. (Common for dynamically provisioned volumes)
  persistentVolumeReclaimPolicy: Retain # Here, we choose 'Retain' to ensure our data is not deleted automatically.
  # 'nfs' defines the NFS (Network File System) specific configuration for this PV.
  # This tells Kubernetes that this PV is backed by an NFS server.
  nfs:
    path: / # The shared directory path on the NFS server. Our simulated NFS server shares the '/' directory.
    server: 10.255.255.10 # The IP address of our NFS server (this is our Docker container's IP).

Explanation (YAML file ke har section ki simplified jankari):

  • kind: PersistentVolume: Hum ek PersistentVolume (PV) bana rahe hain.
  • name: mysql-storage-pv: PV ka naam mysql-storage-pv hai.
  • labels: app: mysql: Is PV ko app: mysql label diya gaya hai. PVCs is label ko use karke is PV ko dhundh sakti hain.
  • spec:: PV ki settings.
    • capacity: storage: 5Gi: Yeh PV 5 Gigibytes (GiB) ki storage provide karta hai.
    • accessModes: - ReadWriteOnce: Is storage ko ek time pe sirf ek hi Node read aur write kar sakta hai. MySQL jaise databases ke liye yeh common hai.
    • persistentVolumeReclaimPolicy: Retain: Yeh bahut important hai! Iska matlab hai ki jab PersistentVolumeClaim (PVC) jo is PV ko use kar raha hai, delete ho jayega, tab bhi yeh PV aur uske andar ka data retain (mehfooz) rahega. Data delete nahi hoga automatically. Delete policy mein PV aur data dono delete ho jaate hain.
    • nfs: path: /, server: 10.255.255.10: Yeh batata hai ki yeh storage NFS server se aa raha hai. server mein hamare simulated NFS server (Docker container) ka IP address (10.255.255.10) hai, aur path / hai, kyunki hamara NFS server /data folder ko shared_directory ke roop mein expose kar raha hai (jo container ke andar / se mapped hai).

Step 3: PV Ko Apply Karo

bash
kubectl apply -f mysql-pv.yaml

Explanation:

  • kubectl apply -f mysql-pv.yaml: This command creates the mysql-storage-pv.
  • Result: persistentvolume/mysql-storage-pv created message dikhega.

Step 4: PV Ki Status Dekho

bash
kubectl get pv

Explanation:

  • kubectl get pv: This command lists all Persistent Volumes.
  • Result: Tumhein mysql-storage-pv dikhega. STATUS Available hona chahiye, matlab PV ban gaya hai aur abhi kisi ne use claim nahi kiya hai.
    NAME              CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS      CLAIM   STORAGECLASS   REASON   AGE
    mysql-storage-pv  5Gi        RWO            Retain           Available                          20s

12.4 PVC: Tumhara Request Form (Asking for Storage) 📝

Ab jab PV available hai, Pods use seedha use nahi kar sakte. Pods ko PersistentVolumeClaim (PVC) karna padta hai. PVC ek request form hai jo Pods ki taraf se storage maangta hai.

Step 5: Persistent Volume Claim (PVC) File Banao Apne computer pe ek new file mysql-pvc.yaml naam se banao aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct!

yaml
# File: mysql-pvc.yaml

# API version for PersistentVolumeClaim objects (v1 for PVCs)
apiVersion: v1
# Type of Kubernetes object: PersistentVolumeClaim
kind: PersistentVolumeClaim
# Metadata for our PersistentVolumeClaim
metadata:
  # Name of our PersistentVolumeClaim
  name: mysql-data-claim # This is the name our Pods will use to request storage
# Specification for the PersistentVolumeClaim
spec:
  # 'accessModes' define how the requested storage should be mounted.
  # This MUST match the access modes defined in the PersistentVolume.
  accessModes:
    - ReadWriteOnce # We are requesting storage that can be read-write by a single Node.
  # 'volumeMode' specifies whether the volume should be a filesystem or a block device.
  volumeMode: Filesystem # We need a standard filesystem for our database.
  # 'resources' define the storage capacity requested by the PVC.
  resources:
    requests:
      storage: 5Gi # We are requesting 5 GiB of storage. This should match or be less than the PV's capacity.
  # 'storageClassName' is used for dynamic provisioning (creating PVs automatically).
  # Since we manually created our PV, we set this to an empty string "".
  # In cloud environments, you might set this to "standard", "premium", etc.
  storageClassName: ""
  # 'selector' is used to select a specific PersistentVolume (PV) based on its labels.
  # Our PV (mysql-storage-pv) has the label 'app: mysql', so this PVC will try to bind to it.
  selector:
    matchLabels:
      app: mysql # This PVC will try to find a PV with the label 'app: mysql'

Explanation (YAML file ke har section ki simplified jankari):

  • kind: PersistentVolumeClaim: Hum ek PersistentVolumeClaim (PVC) bana rahe hain.
  • name: mysql-data-claim: PVC ka naam mysql-data-claim hai. Pods isi naam se storage request karenge.
  • spec:: PVC ki settings.
    • accessModes: - ReadWriteOnce: Hum ReadWriteOnce access mode wali storage maang rahe hain. Yeh PV ke accessModes se match hona chahiye.
    • volumeMode: Filesystem: Hum Filesystem type ki storage maang rahe hain.
    • resources: requests: storage: 5Gi: Hum 5 GiB ki storage request kar rahe hain. Yeh PV ki capacity se match honi chahiye.
    • storageClassName: "": Abhi hum StorageClass use nahi kar rahe hain (jo PVs ko automatically banata hai). Jab hum manual PV banate hain, toh isko empty rakhte hain.
    • selector: matchLabels: app: mysql: Yeh important hai! Yeh PVC us PersistentVolume (PV) ko dhundhega jiska label app: mysql hai. Hamara mysql-storage-pv is label ko match karta hai.

Step 6: PVC Ko Apply Karo

bash
kubectl apply -f mysql-pvc.yaml

Explanation:

  • kubectl apply -f mysql-pvc.yaml: This command creates the mysql-data-claim PVC.
  • Result: persistentvolumeclaim/mysql-data-claim created message dikhega.

Step 7: PV aur PVC Ki Status Dekho (Binding) Ab, dekho ki tumhara PVC, PV se Bound hua ya nahi.

bash
kubectl get pv
kubectl get pvc

Explanation:

  • kubectl get pv: Lists Persistent Volumes.
  • kubectl get pvc: Lists Persistent Volume Claims.
  • Result: Tum dekhoge ki mysql-storage-pv ka STATUS Available se Bound ho jayega. Aur mysql-data-claim PVC ka STATUS bhi Bound dikhayega, aur VOLUME column mein mysql-storage-pv ka naam dikhega. Iska matlab hai ki tumhari storage request successfully PV se Bound ho gayi hai! 🎉
    kubectl get pv
    NAME              CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM                       STORAGECLASS   REASON   AGE
    mysql-storage-pv  5Gi        RWO            Retain           Bound    default/mysql-data-claim                   2m
    
    kubectl get pvc
    NAME              STATUS   VOLUME            CAPACITY   ACCESS MODES   STORAGECLASS   AGE
    mysql-data-claim  Bound    mysql-storage-pv  5Gi        RWO                           10s

12.5 Using PVC in Your App (Connecting Storage to Your App) 🔗

Ab jab PVC Bound ho gaya hai, hum usko apne app (MySQL Deployment) mein use kar sakte hain.

Step 8: MySQL Deployment Ke Saath PVC Ko Use Karne Ke Liye File Banao Apne computer pe ek new file mysql-deployment.yaml naam se banao aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct! (Yeh file labs/persistentvolume/deploy.yaml se li gayi hai, jismein Secret bhi use ho raha hai MySQL password ke liye).

yaml
# File: mysql-deployment.yaml

# Secret object for MySQL root password (sensitive data)
apiVersion: v1
kind: Secret
metadata:
  name: mysql-root-password-secret # Name of our Secret
type: Opaque # General-purpose secret type
stringData:
  password: MySuperSecurePassword! # IMPORTANT: Use a strong password!
---
# Deployment for our MySQL database server
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mysql-database-server # Name of our Deployment
  labels:
    app: mysql-server # Label for the Deployment itself
spec:
  replicas: 1 # We want only 1 copy of our MySQL server (databases are often single instance or managed by StatefulSet)
  selector:
    matchLabels:
      app: mysql-server # This Deployment will manage Pods with 'app: mysql-server' label
  strategy:
    type: Recreate # For databases, 'Recreate' strategy is often used to ensure data consistency during updates.
  template: # Blueprint for the Pod that this Deployment will create
    metadata:
      labels:
        app: mysql-server # Pods created by this Deployment will have this label
    spec:
      containers:
        - name: mysql-container # Name of the container inside the Pod
          image: mysql:latest # MySQL database image
          ports:
            - containerPort: 3306 # Default port for MySQL
          volumeMounts: # How to connect volumes to this container
            - mountPath: "/var/lib/mysql" # IMPORTANT: MySQL stores its data here.
                                          # We need to mount our persistent volume to this path.
              name: mysql-data-volume # Name of the volume to mount (defined below)
          env: # Define environment variables for the MySQL container
            - name: MYSQL_ROOT_PASSWORD # MySQL needs this environment variable to set the root password
              valueFrom:
                secretKeyRef: # Get the value from a Secret key
                  name: mysql-root-password-secret # The name of our Secret
                  key: password # The specific key within the Secret (where our password is stored)
      volumes: # Definition of volumes for the Pod
        - name: mysql-data-volume # Name of our volume
          persistentVolumeClaim: # This volume will use a PersistentVolumeClaim
            claimName: mysql-data-claim # The name of the PVC we created earlier (mysql-data-claim)

Explanation (YAML file ke har section ki simplified jankari):

  • Secret (mysql-root-password-secret): Pehle humne ek Secret define kiya hai MySQL_ROOT_PASSWORD ke liye. Yeh password MySuperSecurePassword! hai (tum isko badal sakte ho).
  • Deployment (mysql-database-server):
    • replicas: 1: MySQL ka ek hi instance chalayenge.
    • strategy: type: Recreate: Database updates ke liye Recreate strategy use ki gayi hai taaki data consistency ensure ho.
    • container: mysql-container, image: mysql:latest, ports: - containerPort: 3306: MySQL server chalega.
    • volumeMounts: - mountPath: "/var/lib/mysql", name: mysql-data-volume: Yeh bahut important hai! MySQL apna data /var/lib/mysql folder mein store karta hai. Humne mysql-data-volume ko isi path pe mount kiya hai, taaki MySQL ka data hamare persistent storage pe save ho.
    • env: - name: MYSQL_ROOT_PASSWORD, valueFrom: secretKeyRef: name: mysql-root-password-secret, key: password: MySQL container ko uska root password MYSQL_ROOT_PASSWORD environment variable se milega, jo mysql-root-password-secret se aa raha hai.
    • volumes: - name: mysql-data-volume, persistentVolumeClaim: claimName: mysql-data-claim: Yahan hum mysql-data-volume ko define kar rahe hain aur use mysql-data-claim PVC se connect kar rahe hain. Iska matlab hai ki is Pod ka data mysql-data-claim PVC (aur uske Bound PV) pe save hoga.

Step 9: MySQL Deployment Ko Apply Karo

bash
kubectl apply -f mysql-deployment.yaml

Explanation:

  • kubectl apply -f mysql-deployment.yaml: This command creates the Secret and the MySQL Deployment.
  • Result: secret/mysql-root-password-secret created and deployment.apps/mysql-database-server created messages dikhenge.

Step 10: MySQL Pod Mein Data Add Karo Ab, hum MySQL database mein kuch data daalenge. Phir is Pod ko delete karke verify karenge ki data persists (mehfooz rehta) hai.

Pehle, MySQL Pod ka naam pata karo (jo mysql-database-server- se shuru hoga):

bash
kubectl get pods -l app=mysql-server

Example Result: mysql-database-server-abcd1234-xyz56

Ab, us Pod ke andar interactive terminal session open karo aur MySQL CLI (Command Line Interface) use karke data add karo:

bash
kubectl exec -it <mysql-pod-name> -- bash
# Example: kubectl exec -it mysql-database-server-abcd1234-xyz56 -- bash

# Ab tum Pod ke andar ho. MySQL CLI se connect karo:
mysql -p # Password prompt aayega. Type karo: MySuperSecurePassword! (jo tumne secret mein diya tha)

# Ab tum MySQL CLI ke andar ho. Ye commands type karo:
CREATE DATABASE my_game_db; # Ek naya database banao
USE my_game_db; # Us database ko use karo
CREATE TABLE players (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255)); # Players table banao
INSERT INTO players (name) VALUES ('Player1'), ('Player2'); # Kuch players add karo
SELECT * FROM players; # Players table se data dekho
EXIT; # MySQL CLI se bahar aao

exit # Pod se bahar aao

Explanation:

  • Humne my_game_db naam ka ek database banaya.
  • Usmein players naam ki table banayi.
  • Player1 aur Player2 naam ke do players add kiye.
  • SELECT * FROM players; se confirm kiya ki data add ho gaya hai.
  • Result: Tumhein Player1 aur Player2 dikhne chahiye.
    +----+---------+
    | id | name    |
    +----+---------+
    |  1 | Player1 |
    |  2 | Player2 |
    +----+---------+
    2 rows in set (0.00 sec)

Step 11: MySQL Pod Ko Delete Karo Ab sabse important test! Pod ko delete kar do. Yaad rakhna, Deployment replicas: 1 hone ki wajah se naya Pod automatically bana dega.

bash
kubectl delete deployment mysql-database-server

Explanation:

  • kubectl delete deployment mysql-database-server: This command deletes the Deployment mysql-database-server.
  • What happens: Deployment ke saare Pods delete ho jayenge. Lekin data mysql-data-claim PVC (aur uske Bound PV) pe hai, toh woh safe hai.
  • Result: deployment.apps "mysql-database-server" deleted message dikhega.

Step 12: Naya MySQL Pod Banao aur Data Check Karo (Persistence Verify Karo!) Deployment ko phir se apply karo. Kubernetes naya Pod banayega, aur woh naya Pod automatically usi PVC se connect ho jayega (aur uske data se!).

bash
kubectl apply -f mysql-deployment.yaml
kubectl get pods -w # Wait for Pod to be Running

Explanation:

  • Naya Pod mysql-database-server- naam se banega. Wait karo jab tak woh Running status mein na aa jaye.

Ab, naye MySQL Pod ke andar jao aur data check karo:

bash
kubectl exec -it <new-mysql-pod-name> -- bash
# Example: kubectl exec -it mysql-database-server-xyz5678-ijkl -- bash

# Ab Pod ke andar ho:
mysql -p # Password type karo: MySuperSecurePassword!
USE my_game_db;
SELECT * FROM players;
EXIT; # MySQL CLI se bahar aao

exit # Pod se bahar aao

Explanation:

  • Result: Tumhein ab bhi Player1 aur Player2 dikhne chahiye! 🎉 Iska matlab hai tumhara data Persistent Volume (PV) pe safe hai, chahe Pod kitni bhi baar delete ho jaye ya restart ho jaye. This is the power of Persistent Volumes!

Step 13: Cleanup - Saare Resources Delete Karo Jab kaam khatam ho jaye, toh saare Kubernetes objects aur Docker NFS simulation ko delete karo. Order important hai!

  1. Deployment delete karo: Isse MySQL Pod delete hoga.
  2. PVC delete karo: Isse mysql-data-claim delete hoga.
  3. PV delete karo: Isse mysql-storage-pv delete hoga. (Agar persistentVolumeReclaimPolicy: Retain hai toh data minikube-nfs-data Docker volume mein rahega).
  4. Docker NFS Server ko stop aur remove karo:
  5. Docker NFS Data volume aur network delete karo:
bash
# 1. Delete MySQL Deployment (this also deletes the Pod)
kubectl delete -f mysql-deployment.yaml

# 2. Delete the PersistentVolumeClaim (PVC)
kubectl delete -f mysql-pvc.yaml

# 3. Delete the PersistentVolume (PV)
kubectl delete -f mysql-pv.yaml

# 4. Stop and remove the Docker NFS server container
docker stop nfs-server-sim
docker rm nfs-server-sim

# 5. Remove the Docker volume and network that were used for NFS data
docker volume rm minikube-nfs-data
docker network rm minikube-nfs-net

Explanation:

  • Order is important to avoid errors. First, the app using the storage (Deployment/Pod), then the claim (PVC), then the actual storage definition (PV). Finally, clean up the Docker components.

Persistent Volumes aur Persistent Volume Claims apps ke liye data ko hamesha ke liye store karne ke liye bahut important hain. Ye tumhare data ko safe rakhte hain, chahe tumhare apps (Pods) Kubernetes mein kahin bhi move hon. Agle chapter mein hum kuch khaas apps ke baare mein seekhenge jinhein stable names aur storage ki zaroorat hoti hai (jaise databases)! 🐾


Chapter 13: Naam Wale Apps aur Unka Khaas Data: StatefulSets 🐾

Pichhle chapter mein humne Deployments dekhe. Deployments apps ki copies banate hain (jaise web-app-deployment-5j6k7, web-app-deployment-l8m9n). Har copy ka naam random hota hai, aur agar koi copy delete ho jaye, toh naye naam se nayi copy ban jaati hai. Yeh theek hai web servers jaise apps ke liye jinhein "stateless" apps kehte hain (matlab, unke paas koi khaas personal data nahi hota).

Lekin socho, tumhara ek game server hai (jaise ek database server) jiske paas apna khaas data hai, aur use hamesha ek hi naam chahiye. Jaise tumhare ghar mein pets hote hain. Tumhare paas Dog1, Dog2, Dog3 nahi hote, tumhare paas Buddy, Milo, Rocky hote hain. Har pet ka apna naam hota hai aur uska apna bed, apna bowl. Agar Buddy thodi der ke liye kahin chala gaya, toh Buddy hi wapas aana chahiye, koi naya random dog nahi.

Yahin pe Kubernetes ka StatefulSet (pronounced: steit-ful-set) kaam aata hai!

13.1 StatefulSets Kya Hote Hain? (Like Named Pets with their Own Beds) 🐕

  • StatefulSet: StatefulSet ek Kubernetes object hai. Yeh apps ki copies ko manage karta hai jinhein stable, unique names aur persistent storage ki zaroorat hoti hai. Yeh databases (jaise MySQL, Cassandra), message queues, ya distributed systems jaise "stateful" apps ke liye use hota hai.
  • Named Pets Analogy: StatefulSet bilkul ek pet farm ki tarah hai jahan har pet ka apna naam (e.g., cassandra-0, cassandra-1, cassandra-2) aur apna ghar (persistent storage) hota hai. Agar koi pet thodi der ke liye farm se bahar bhi jaaye (restart ho), toh woh wapas apne hi naam aur ghar mein aata hai.
  • Key Idea: StatefulSets provide stable identity (name) and stable persistent storage for each replica (copy) of your application.

StatefulSet ki Kuch Khaas Baatein (Deployments se differences):

  1. Stable, Unique, and Ordered Names: Har Pod ko ek stable, predictable naam milta hai, jaise app-0, app-1, app-2. Yeh naam kabhi badalta nahi.
  2. Ordered Creation and Deletion:
    • Creation: Pods ek strict order mein bante hain (e.g., app-0 pehle, phir app-1, phir app-2). Agla Pod tabhi banega jab pichhla wala Running aur Ready ho jaye.
    • Deletion: Jab scale down karte hain, toh Pods reverse order mein delete hote hain (app-2 pehle, phir app-1, phir app-0).
  3. Unique Persistent Storage: Har Pod (replica) ko apna unique Persistent Volume Claim (PVC) milta hai, jiska naam bhi Pod ke naam se linked hota hai. Matlab, app-0 ka apna storage होगा, app-1 का अपना, aur yeh storage unke naam se attached rehta hai.
  4. Headless Service Required: StatefulSet ko Pods se connect karne ke liye ek special type ki Service chahiye hoti hai, jise Headless Service kehte hain.

Real-Life Example: Cassandra ek popular distributed database hai. Iske instances ko stable names aur unique storage chahiye hota hai taaki woh aapas mein theek se communicate kar sakein aur data ko consistent rakh sakein.

Step 1: StatefulSet Ki YAML File Banao Apne computer pe ek new file cassandra-statefulset.yaml naam se banao aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct! (Yeh labs/statefulset/statefulset.yaml se li gayi hai).

yaml
# File: cassandra-statefulset.yaml

# Headless Service for the StatefulSet.
# This Service is crucial for StatefulSets as it provides stable network identity (DNS names) for each Pod.
# It doesn't have its own ClusterIP but directly returns the IPs of the Pods it manages.
apiVersion: v1
kind: Service
metadata:
  labels:
    app: cassandra # Label for the Service
  name: cassandra-service # Name of the Service. StatefulSet will reference this name.
spec:
  clusterIP: None # THIS MAKES IT A HEADLESS SERVICE. No single IP for the service, direct access to Pod IPs.
  ports:
  - port: 9042 # Default port for Cassandra
  selector:
    app: cassandra # This Service will select Pods with 'app: cassandra' label
---
# StatefulSet for our Cassandra database
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: cassandra-app # Name of our StatefulSet
  labels:
    app: cassandra # Label for the StatefulSet itself
spec:
  # 'serviceName' MUST refer to a Headless Service that manages the network domain for the Pods.
  # This enables stable DNS names like 'cassandra-app-0.cassandra-service'.
  serviceName: cassandra-service # References the Headless Service defined above
  # Number of replicas (copies) of our Cassandra application.
  # Each replica will get a stable name (cassandra-app-0, cassandra-app-1) and unique storage.
  replicas: 2
  # 'selector' tells the StatefulSet which Pods it should manage.
  # This MUST match the labels in the Pod template below.
  selector:
    matchLabels:
      app: cassandra
  # 'template' is the blueprint for the Pods that this StatefulSet will create.
  template:
    metadata:
      labels:
        app: cassandra # Pods created by this StatefulSet will have this label
    spec:
      # 'terminationGracePeriodSeconds' defines the time given to the Pod to shut down gracefully.
      # For databases, a longer period (e.g., 1800s = 30 minutes) can be necessary for data sync.
      terminationGracePeriodSeconds: 1800
      containers:
      - name: cassandra-container # Name of the container inside the Pod
        # Image for the Cassandra database
        image: gcr.io/google-samples/cassandra:v13 # A sample Cassandra image
        imagePullPolicy: Always # Always try to pull the latest image
        ports:
        - containerPort: 7000 # Cassandra internal communication ports
          name: intra-node
        - containerPort: 7001
          name: tls-intra-node
        - containerPort: 7199
          name: jmx
        - containerPort: 9042 # Main Cassandra client port (CQL)
          name: cql
        resources: # Resource limitations for the container
          limits:
            cpu: "500m" # Max 0.5 CPU core
            memory: 1Gi # Max 1 Gigabyte of memory
          requests:
            cpu: "500m" # Request 0.5 CPU core
            memory: 1Gi # Request 1 Gigabyte of memory
        securityContext: # Security settings for the container
          capabilities:
            add:
              - IPC_LOCK # Required for some database operations
        lifecycle: # Define actions during different phases of container lifecycle
          preStop: # Commands to run just before the container is terminated
            exec:
              command:
              - /bin/sh
              - -c
              - nodetool drain # Cassandra specific command to drain data before shutdown
        env: # Environment variables for Cassandra configuration
          - name: MAX_HEAP_SIZE
            value: 512M
          - name: HEAP_NEWSIZE
            value: 100M
          - name: CASSANDRA_SEEDS
            value: "cassandra-app-0.cassandra-service.default.svc.cluster.local" # How Cassandra instances find each other
          - name: CASSANDRA_CLUSTER_NAME
            value: "K8Demo"
          - name: CASSANDRA_DC
            value: "DC1-K8Demo"
          - name: CASSANDRA_RACK
            value: "Rack1-K8Demo"
          - name: POD_IP
            valueFrom:
              fieldRef:
                fieldPath: status.podIP
        readinessProbe: # Check if Cassandra is ready to serve requests
          exec:
            command:
            - /bin/bash
            - -c
            - /ready-probe.sh # A script inside the Cassandra image to check its readiness
          initialDelaySeconds: 15
          timeoutSeconds: 5
        volumeMounts: # How to connect volumes to this container
        - name: cassandra-data # Name of the volume to mount (defined below in volumeClaimTemplates)
          mountPath: /cassandra_data # Cassandra's data directory inside the container
  
  # 'volumeClaimTemplates' is unique to StatefulSets.
  # For each replica (Pod) created by this StatefulSet, a UNIQUE PersistentVolumeClaim (PVC)
  # will be automatically created based on this template.
  # This ensures that each Pod has its own stable, persistent storage.
  volumeClaimTemplates:
  - metadata:
      name: cassandra-data # Name of the PVC that will be created for each replica
    spec:
      accessModes: [ "ReadWriteOnce" ] # PVC will request ReadWriteOnce access mode
      storageClassName: standard # Minikube's default StorageClass. In real clusters, use a specific one.
      resources:
        requests:
          storage: 1Gi # Each replica will request 1 Gigibyte of storage

Explanation (YAML file ke har section ki simplified jankari):

  • Headless Service (cassandra-service):
    • kind: Service, name: cassandra-service: cassandra-service naam ki Service.
    • clusterIP: None: THIS MAKES IT A HEADLESS SERVICE. Iska apna koi single ClusterIP nahi hota. Jab tum cassandra-service ko DNS se query karte ho, toh woh cassandra-app-0 aur cassandra-app-1 jaise Pods ke seedha IP addresses return karti hai. Yeh StatefulSet Pods ko aapas mein stable DNS names (cassandra-app-0.cassandra-service.default.svc.cluster.local) se baat karne mein help karta hai.
  • StatefulSet (cassandra-app):
    • kind: StatefulSet, name: cassandra-app: cassandra-app naam ka StatefulSet.
    • serviceName: cassandra-service: Yeh Headless Service se link karta hai. StatefulSet ko batata hai ki cassandra-service iske Pods ke liye network identity provide karegi.
    • replicas: 2: Hum Cassandra database ki 2 copies (replicas) chalana chahte hain. StatefulSet inhein cassandra-app-0 aur cassandra-app-1 naam dega.
    • template:: Pod ki blueprint.
      • image: gcr.io/google-samples/cassandra:v13: Cassandra database ka image.
      • volumeMounts: - name: cassandra-data, mountPath: /cassandra_data: Container ke andar /cassandra_data path pe data mount hoga.
    • volumeClaimTemplates:: Yeh StatefulSet ka sabse khaas feature hai! Ismein hum ek PVC ka template define karte hain. StatefulSet automatically har replica (Pod) ke liye is template se ek unique PVC bana deta hai, jiska naam Pod ke naam se linked hota hai (jaise cassandra-data-cassandra-app-0, cassandra-data-cassandra-app-1).
      • metadata: name: cassandra-data: PVC ka naam cassandra-data- prefix se shuru hoga.
      • spec: storageClassName: standard: Minikube mein standard ek default StorageClass hota hai jo automatically storage (PVs) provide karta hai. Real cluster mein tum apni custom StorageClass use kar sakte ho.
      • resources: requests: storage: 1Gi: Har replica ko 1 Gigibyte storage milega.

Step 2: StatefulSet Ko Apply Karo

bash
kubectl apply -f cassandra-statefulset.yaml

Explanation:

  • kubectl apply -f cassandra-statefulset.yaml: This command creates the Headless Service and the StatefulSet.
  • Result: service/cassandra-service created and statefulset.apps/cassandra-app created messages dikhenge.

Step 3: StatefulSet, Pods aur PVCs Ki Status Dekho (Ordered Creation) Pods ko watch karo, ek alag terminal mein.

bash
kubectl get pods -w

Explanation:

  • kubectl get pods -w: This command will show live updates of your Pods.
  • What to observe: Tumhein cassandra-app-0 aur cassandra-app-1 naam ke Pods dikhenge. Tum dekhoge ki cassandra-app-0 pehle Running hoga. Jab woh Running aur Ready ho jayega, tabhi cassandra-app-1 ban na shuru hoga. Yahi StatefulSet ka ordered creation behavior hai.
    NAME            READY   STATUS              RESTARTS   AGE
    cassandra-app-0   0/1     ContainerCreating   0          5s
    # ... after cassandra-app-0 is Running and Ready ...
    cassandra-app-0   1/1     Running             0          40s
    cassandra-app-1   0/1     ContainerCreating   0          5s # cassandra-app-1 starts ONLY after cassandra-app-0 is ready
    # ... after cassandra-app-1 is Running and Ready ...
    cassandra-app-1   1/1     Running             0          40s

kubectl get pods -w wale terminal ko Ctrl+C press karke band kar do.

Ab, StatefulSet ki status dekho:

bash
kubectl get statefulset

Explanation:

  • kubectl get statefulset: This command lists all StatefulSets.
  • Result: Tumhein cassandra-app StatefulSet READY 2/2 dikhega.
    NAME          READY   AGE
    cassandra-app   2/2     1m

Ab, PVCs ki status dekho. Har replica ke liye ek unique PVC bana hoga:

bash
kubectl get pvc

Explanation:

  • kubectl get pvc: This command lists all Persistent Volume Claims.
  • Result: Tumhein cassandra-data-cassandra-app-0 aur cassandra-data-cassandra-app-1 naam ke do PVCs dikhenge. Har PVC Bound to uska apna storage. (Is case mein, Minikube ne dynamically PVs bana diye hain, kyunki storageClassName: standard use kiya tha).
    NAME                          STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   AGE
    cassandra-data-cassandra-app-0  Bound    pvc-abcd1234-abcd-abcd-abcd-abcd1234abcd   1Gi        RWO            standard       1m
    cassandra-data-cassandra-app-1  Bound    pvc-efgh5678-efgh-efgh-efgh-efgh5678efgh   1Gi        RWO            standard       40s
    Notice karo ki PVCs ke naam Pods ke naam (cassandra-app-0, cassandra-app-1) se linked hain. Yahi stable storage identity hai.

13.2 Headless Service: StatefulSet ka Dost (For Direct Pod Access) 🤝

Headless Service (cassandra-service) StatefulSet ke liye bahut important hai. Iska clusterIP: None hai, matlab iska apna koi IP nahi hota. Balki, jab tum is Service ko DNS se query karte ho, toh yeh seedha un Pods ke IP addresses return karti hai jinhein yeh manage karti hai.

Step 4: Pods Ko Ping Karo Unke Stable Naam Secassandra-app-0 Pod ke andar jao aur cassandra-app-1 Pod ko ping karo uske stable DNS naam se. Yeh Headless Service ki wajah se possible hai.

bash
kubectl exec -it cassandra-app-0 -- bash
# Ab Pod ke andar ho.
# Ping karne ke liye 'ping' command install karna pad sakta hai in busybox/debian based images
# apt update && apt install -y iputils-ping
# yum install -y iputils-ping
# Then run:
ping cassandra-app-1.cassandra-service.default.svc.cluster.local
# Or simply (shorter version):
ping cassandra-app-1.cassandra-service
exit # Pod se bahar aa jao

Explanation:

  • ping cassandra-app-1.cassandra-service: cassandra-app-1 Pod ka stable DNS naam hai, aur cassandra-service Headless Service ka naam. .default.svc.cluster.local Kubernetes ka default domain hai.
  • Result: Tum cassandra-app-1 ko successfully ping kar paoge uske stable DNS naam se. Iska matlab hai ki har Cassandra replica ko apni ek stable identity (naam) mil gayi hai, jisse woh aapas mein communicate kar sakte hain.

13.3 Volume Claim Templates: Har Pet ka Apna Bed (Unique Persistent Storage) 🛏️

StatefulSets mein volumeClaimTemplates use hote hain. Iska matlab hai ki har Pod (replica) ke liye automatically ek unique Persistent Volume Claim (PVC) ban jayega. Yeh ensure karta hai ki cassandra-app-0 ka data cassandra-data-cassandra-app-0 PVC pe save ho, aur cassandra-app-1 ka data cassandra-data-cassandra-app-1 PVC pe save ho. Har pet ka apna bed! 🛏️

Step 5: StatefulSet Ko Scale Down Karo (Ordered Deletion) Chalo, 2 copies se 1 copy karte hain. Dekho ki deletion kaise ordered hota hai.

bash
kubectl scale statefulset cassandra-app --replicas=1

Explanation:

  • kubectl scale statefulset cassandra-app --replicas=1: This command scales down the StatefulSet.
  • What happens: Deployment ke opposite, StatefulSet Pods ko reverse order mein delete karta hai. Yani, cassandra-app-1 pehle delete hoga. cassandra-app-0 wahi rahega.
  • Result: statefulset.apps/cassandra-app scaled message dikhega. kubectl get pods -w se dekhoge toh cassandra-app-1 Terminating dikhega aur cassandra-app-0 Running hi rahega.

Step 6: StatefulSet Ko Scale Up Karo Phir Se (Ordered Creation) Ab 1 copy se 2 copies karte hain phir se. Dekho ki creation kaise ordered hota hai.

bash
kubectl scale statefulset cassandra-app --replicas=2

Explanation:

  • kubectl scale statefulset cassandra-app --replicas=2: This command scales up the StatefulSet.
  • What happens: StatefulSet cassandra-app-1 Pod ko phir se banayega, kyunki cassandra-app-0 already hai. Naya Pod cassandra-app-1 naam se hi banega (stable name).
  • Result: statefulset.apps/cassandra-app scaled message dikhega. kubectl get pods -w se dekhoge toh cassandra-app-1 ContainerCreating se Running aayega.

Step 7: Cleanup - StatefulSet aur PVCs Ko Delete Karo Jab kaam khatam ho jaye, toh StatefulSet aur uske associated PVCs ko delete kar do. Order important hai!

bash
# 1. Delete the StatefulSet first (this deletes the Pods)
kubectl delete -f cassandra-statefulset.yaml

Explanation:

  • kubectl delete -f cassandra-statefulset.yaml: This command deletes the cassandra-app StatefulSet and the cassandra-service.
  • Important: StatefulSet delete karne se uske Pods delete ho jayenge, lekin uske banaye hue PVCs (cassandra-data-cassandra-app-0 aur cassandra-data-cassandra-app-1) automatically delete nahi honge! Tumhein unhein manually delete karna padega taaki data safe rahe ya agar tum wapas banaya toh wahi data mile. Yeh persistentVolumeReclaimPolicy: Retain ka effect hai.

Ab, PVCs ko delete karo:

bash
kubectl delete pvc cassandra-data-cassandra-app-0
kubectl delete pvc cassandra-data-cassandra-app-1

Explanation:

  • kubectl delete pvc <pvc_name>: This command deletes the specified Persistent Volume Claims.
  • Result: persistentvolumeclaim "cassandra-data-cassandra-app-0" deleted jaisa message dikhega. kubectl get pvc se confirm kar sakte ho.

StatefulSets un apps ke liye bane hain jinhein names aur data stable rakhne ki zaroorat hoti hai. Yeh distributed databases, message queues jaise complex systems ko Kubernetes mein manage karna easy banate hain. Agle chapter mein hum apps ko Nodes pe specific tarike se assign karna seekhenge! 🛋️


Chapter 14: Apps ko Kahan Rakhna Hai: Node Affinity aur Taint/Toleration 🛋️

Pichhle chapters mein humne dekha ki Kubernetes (Scheduler) khud decide karta hai ki Pods ko kis Node (computer) pe chalana hai. Lekin kabhi-kabhi, tumhe kuch khaas Pods ko khaas Nodes pe hi chalana hota hai.

Socho, tumhare paas bahut saare toys hain, aur tum unhein apne room mein alag-alag shelves pe rakhna chahte ho.

  • Kuch shelves Fragile Toys Only wali hain (jinpe tum Strong Toys ko nahi rakhna chahte).
  • Kuch shelves Car Toys Only wali hain (jinpe tum Doll Toys ko nahi rakhna chahte).
  • Aur kuch toys sirf khaas shelves pe hi fit hote hain ya unhein wohi shelves pasand hain.

Yahin pe Kubernetes ke Node Affinity aur Taint/Toleration kaam aate hain!

14.1 Node Affinity: "Sirf Yahan Baitho!" (Preferring Specific Computers) 🪑

Node Affinity kya hai?Node Affinity (pronounced: node a-fin-ih-tee) Pods ko batati hai ki woh kis type ke Node par chalna pasand karengi. Yeh Pod ko NodeSelector se zyada flexible tarika deta hai Nodes choose karne ka.

  • Classroom Analogy: Jaise classroom mein kuch seats (Nodes) hain jinpe Smart Student ka label laga hai. Tum My Genius App naam ke Pod ko bolte ho, "Agar Smart Student seat mile toh achha hai!"
  • Purpose: Node Affinity use karte hain jab tumhein Pods ko khaas hardware (jaise GPU wale Nodes), ya specific operating system (Linux ya Windows), ya specific locations (jaise us-east-1 region ke Nodes) par chalana ho.

Node Affinity Kaise Kaam Karta Hai? Pehle, hum Nodes ko labels dete hain (Chapter 3 mein seekha tha). Jaise: kubectl label node minikube type=production. Phir, Pod ki YAML file mein nodeAffinity define karte hain.

Node Affinity ke Do Main Types:

  1. Required Affinity (Zaroori): requiredDuringSchedulingIgnoredDuringExecution

    • Kaise kaam karta hai: Iska matlab hai, "Agar mujhe mere pasand ka Node nahi mila, toh main Pod nahi chalaunga (Pending mein hi rahoonga)." Yeh ek strict rule hai.
    • IgnoredDuringExecution ka matlab: Agar ek baar Pod chal gaya, aur Node ka label badal gaya (yaani Node ki condition change ho gayi), toh Pod chalta rahega. Kubernetes us Pod ko us Node se remove nahi karega, woh sirf nayi scheduling ke time rules dekhega.
    • Analogy: Jaise, "Agar Red chair nahi mili toh main baithunga hi nahi." Lekin agar ek baar Red chair mil gayi, aur uska colour badal ke Blue ho gaya (label change), toh bhi tum us pe baithe rahoge.
    • Use Case: Critical apps jinhein khaas hardware ya environment chahiye.
  2. Preferred Affinity (Pasandida): preferredDuringSchedulingIgnoredDuringExecution

    • Kaise kaam karta hai: Iska matlab hai, "Agar mujhe mere pasand ka Node mila toh achha hai, warna koi bhi chalega." Yeh ek soft rule hai.
    • weight: Tum weight bhi de sakte ho (1 se 100 tak). Jiska weight zyada, woh rule zyada pasandida. Agar multiple preferred rules hain, toh high weight wala rule pehle try hoga.
    • Analogy: Jaise, "Agar Red chair mili toh achha hai (weight 100), warna Blue chair (weight 50) bhi chal jayegi, warna koi bhi chalegi."
    • Use Case: Apps jo better performance ke liye kuch Nodes prefer karte hain, lekin agar woh available na hon toh kahin bhi chal sakte hain.

Match Expressions (Rules):matchExpressions define karte hain ki Pod ko kis Node label se match karna hai.

  • operator: In: Node ka label value di gayi list mein se ek hona chahiye. (e.g., app: production ya app: test)
  • operator: NotIn: Node ka label value di gayi list mein se nahi hona chahiye.
  • operator: Exists: Node pe woh label key honi chahiye, value kuch bhi ho.
  • operator: DoesNotExist: Node pe woh label key nahi honi chahiye.

Step 1: Minikube Node Ko Label Karo Minikube mein sirf ek hi Node hota hai, jiska naam minikube hai. Hum usko label denge, jaise woh production environment ke liye ho.

bash
kubectl label node minikube app=production

Explanation:

  • kubectl label node minikube app=production: This command adds a label app: production to the minikube Node.
  • Result: node/minikube labeled message dikhega.

Verify karo ki label laga hai ya nahi:

bash
kubectl get node minikube --show-labels

Explanation:

  • --show-labels: This flag shows all labels on the Node.
  • Result: Tumhein app=production label dikhega.
    NAME       STATUS   ROLES           AGE   VERSION   LABELS
    minikube   Ready    control-plane   5m    v1.26.3   app=production,...

Step 2: Node Affinity Pods File Banao Apne computer pe ek new file node-affinity-pods.yaml naam se banao aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct!

yaml
# File: node-affinity-pods.yaml

# Pod 1: Demonstrates Required Node Affinity
apiVersion: v1
kind: Pod
metadata:
  name: required-affinity-pod # Pod's name
spec:
  containers:
  - name: nginx-required-container
    image: nginx:latest
  affinity: # Defines affinity rules for the Pod
    nodeAffinity: # Rules related to Nodes
      # 'requiredDuringSchedulingIgnoredDuringExecution':
      # - Required: Pod will ONLY be scheduled on a Node that satisfies these rules.
      # - IgnoredDuringExecution: If the Node's labels change AFTER the Pod is scheduled,
      #   the Pod will continue to run on that Node. Kubernetes will not evict it.
      requiredDuringSchedulingIgnoredDuringExecution:
        # 'nodeSelectorTerms': A list of conditions. If ANY of these conditions is met, the Node is suitable.
        nodeSelectorTerms:
        - matchExpressions: # List of expressions that must be true for the Node
          - key: app # Check the label with key 'app'
            operator: In # Operator: 'In' means the value must be in the list provided
            values:
            - production # The Node's 'app' label must be 'production'
---
# Pod 2: Demonstrates Preferred (Soft) Node Affinity
apiVersion: v1
kind: Pod
metadata:
  name: preferred-affinity-pod # Pod's name
spec:
  containers:
  - name: nginx-preferred-container
    image: nginx:latest
  affinity: # Defines affinity rules for the Pod
    nodeAffinity: # Rules related to Nodes
      # 'preferredDuringSchedulingIgnoredDuringExecution':
      # - Preferred: Pod will TRY to be scheduled on a Node that satisfies these rules.
      # - IgnoredDuringExecution: Same as above.
      # If no suitable Node is found, the Pod will still be scheduled on any available Node.
      preferredDuringSchedulingIgnoredDuringExecution:
      # A list of preferences. Kubernetes will try to satisfy these preferences based on 'weight'.
      - weight: 100 # Highest weight means higher preference. (Range 1-100)
        preference:
          matchExpressions:
          - key: app
            operator: In
            values:
            - production # Prefer Nodes where 'app' label is 'production'
      # You can add more preferences with different weights
      - weight: 50 # Lower preference
        preference:
          matchExpressions:
          - key: environment
            operator: In
            values:
            - test # Also prefer Nodes where 'environment' label is 'test' (if production is not available)

Explanation (YAML file ke har section ki simplified jankari):

  • Pod 1 (required-affinity-pod - Required Affinity):
    • nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution:: Yeh strict rule hai! Iska matlab hai ki required-affinity-pod tabhi Node pe schedule hoga jab use app: production label wala Node milega. Agar nahi mila, toh Pending mein hi rahega.
    • nodeSelectorTerms: - matchExpressions: - key: app, operator: In, values: - production: Rule define karta hai ki Node ke paas app naam ka label hona chahiye aur uski value production honi chahiye.
  • Pod 2 (preferred-affinity-pod - Preferred Affinity):
    • nodeAffinity: preferredDuringSchedulingIgnoredDuringExecution:: Yeh soft rule hai! Iska matlab hai ki preferred-affinity-pod app: production label wale Node par chalna pasand karega (kyunki weight: 100 hai). Lekin agar woh Node available nahi hai, toh kisi bhi doosre Node par chal jayega.
    • weight: 100: Is preference ko zyada priority milegi.

Step 3: Node Affinity Pods Ko Apply Karo

bash
kubectl apply -f node-affinity-pods.yaml

Explanation:

  • kubectl apply -f node-affinity-pods.yaml: This command creates both Pods.
  • Result: pod/required-affinity-pod created and pod/preferred-affinity-pod created messages dikhenge.

Step 4: Pod Status Dekho

bash
kubectl get pods -o wide

Explanation:

  • kubectl get pods -o wide: This command lists Pods with their Node information.
  • Result: Tum dekhoge ki required-affinity-pod aur preferred-affinity-pod dono Running honi chahiye aur unki NODE``minikube dikhna chahiye, kyunki humne minikube Node ko app: production label diya tha.
    NAME                   READY   STATUS    RESTARTS   AGE   IP           NODE       NOMINATED NODE   READINESS GATES
    preferred-affinity-pod 1/1     Running   0          10s   172.17.0.5   minikube   <none>           <none>
    required-affinity-pod  1/1     Running   0          10s   172.17.0.4   minikube   <none>           <none>
    • Reason: Dono Pods ko app: production label wala Node minikube mil gaya. required-affinity-pod ko zaroori tha, woh mil gaya. preferred-affinity-pod ne prefer kiya, woh bhi mil gaya. Sab khush! 😊

Step 5: Node Label Hatao (Changes During Execution - IgnoredDuringExecution) Ab dekho IgnoredDuringExecution ka kya matlab hai. Hum minikube Node se app label hata denge jabki Pods already chal rahe hain.

bash
kubectl label node minikube app-

Explanation:

  • kubectl label node minikube app-: app- ka matlab hai app naam ka label minikube Node se remove karo.
  • Result: node/minikube labeled message dikhega.

Verify karo ki label hata hai ya nahi:

bash
kubectl get node minikube --show-labels

Explanation: Tumhein app=production label ab minikube Node pe nahi dikhega.

Phir se Pod status dekho:

bash
kubectl get pods -o wide

Explanation:

  • Result: Tum dekhoge ki Pods ab bhi Running honi chahiye aur minikube Node par hi honi chahiye! 🤔
    NAME                   READY   STATUS    RESTARTS   AGE   IP           NODE       NOMINATED NODE   READINESS GATES
    preferred-affinity-pod 1/1     Running   0          2m    172.17.0.5   minikube   <none>           <none>
    required-affinity-pod  1/1     Running   0          2m    172.17.0.4   minikube   <none>           <none>
    • Why? Kyunki IgnoredDuringExecution ka matlab hai, "Ek baar Pod schedule (yani Node pe place) ho gaya toh, agar Node ke labels baad mein change bhi ho jayein, toh bhi us Pod ko us Node se hataya nahi jayega." Kubernetes sirf nayi Pods schedule karte waqt rules dekhta hai. Purani Pods jo already chal rahi hain, unko disturb nahi karta.

Step 6: Pods Ko Delete Karo aur Phir Se Apply Karo (Bina Label ke Node par Scheduling) Ab hum Pods ko delete karenge aur phir se apply karenge, jab minikube Node pe app=production label nahi hai. Dekho kya hota hai.

bash
kubectl delete -f node-affinity-pods.yaml

Explanation:

  • kubectl delete -f node-affinity-pods.yaml: This command deletes both Pods.

Ab, Pods ko phir se apply karo:

bash
kubectl apply -f node-affinity-pods.yaml

Explanation:

  • kubectl apply -f node-affinity-pods.yaml: This command creates both Pods again.

Pods ki status dekho (ek alag terminal mein kubectl get pods -w chala sakte ho):

bash
kubectl get pods -o wide

Explanation:

  • Result:
    • required-affinity-pod Pending mein rahega! ⏳ Kyunki requiredDuringSchedulingIgnoredDuringExecution rule strict hai. Use app: production label wala Node zaroori hai, aur abhi minikube Node pe woh label nahi hai.
    • preferred-affinity-pod Running ho jayega. Kyunki preferredDuringSchedulingIgnoredDuringExecution rule soft hai. Usne prefer kiya tha, lekin jab nahi mila, toh woh kisi bhi available Node (minikube) par chal gaya.
    NAME                   READY   STATUS    RESTARTS   AGE   IP       NODE       NOMINATED NODE   READINESS GATES
    preferred-affinity-pod 1/1     Running   0          10s   ...      minikube   <none>           <none>
    required-affinity-pod  0/1     Pending   0          10s   <none>   <none>     <none>           <none>

Step 7: Node Ko Phir Se Label Karo (required-affinity-pod ko chalu karne ke liye)required-affinity-pod ko Running karne ke liye, hamein minikube Node ko phir se app: production label dena padega.

bash
kubectl label node minikube app=production

Explanation:

  • kubectl label node minikube app=production: This command adds the app: production label back to the minikube Node.
  • What happens: Jaise hi label lagega, Kubernetes scheduler dekhega ki required-affinity-pod ab schedule ho sakta hai.
  • Result: required-affinity-pod ContainerCreating se Running state mein aa jayega! 🎉
    NAME                   READY   STATUS            RESTARTS   AGE   IP           NODE       NOMINATED NODE   READINESS GATES
    preferred-affinity-pod 1/1     Running           0          1m    ...          minikube   <none>           <none>
    required-affinity-pod  0/1     ContainerCreating 0          1m    <none>       <none>     <none>           <none>
    # ... after a few seconds ...
    required-affinity-pod  1/1     Running           0          1m    172.17.0.X   minikube   <none>           <none>

Step 8: Cleanup for Node Affinity Section

bash
kubectl delete -f node-affinity-pods.yaml # Delete all Pods
kubectl label node minikube app- # Remove the label from minikube node

Explanation:

  • kubectl delete -f node-affinity-pods.yaml: This deletes both Pods.
  • kubectl label node minikube app-: This removes the app label from the minikube Node, cleaning up the changes we made.

14.2 Taint aur Toleration: "Yahan Mat Aana!" (Keeping Apps Away from Computers) 🚫

Taint aur Toleration kya hain?Taint (pronounced: teint) aur Toleration (pronounced: toh-luh-rei-shun) Node Affinity ke opposite hain.

  • Node Affinity: Pods ko Nodes pe attract karta hai.

  • Taint: Nodes ko Pods ko repel (dur dhakelna) karne ki permission deta hai.

  • Toleration: Pods ko un Taints ko "tolerate" (bardasht) karne ki permission deta hai, taaki woh un Nodes pe chal sakein jinpe Taints lage hain.

  • Signboard Analogy:

    • Taint: Node par lagaya jaata hai. Jaise ek shelf pe tum "Fragile Toys Only" ka sign lagaate ho, toh baaki toys wahan nahi aayenge. Yeh Node ko batata hai ki us par kaunse Pods ko nahi aana chahiye.
    • Toleration: Pod par lagaya jaata hai. Jaise tumhara ek toy bahut strong hai, toh tum usko "Fragile Toys Only" shelf pe rakh sakte ho, kyunki woh us rule ko tolerate karta hai.

Kyun Use Karte Hain?

  • Specialized Nodes: Kuch Nodes sirf khaas kaam ke liye hote hain, jaise GPUs (Graphics Processing Units) wale Nodes jo sirf AI ya graphics apps ke liye hain. Tum un Nodes pe Taint laga sakte ho taaki normal apps unpe na chalein aur woh valuable resources free rahen.
  • Master Nodes Protection: Kubernetes Master Nodes pe by default ek Taint होता है (node-role.kubernetes.io/master:NoSchedule), taaki normal Pods unpe na chalein aur woh control plane ke important kaam pe focus kar sakein. Sirf system-level Pods ya woh Pods jo us specific Taint ko tolerate karte hain, Master Node pe chal sakte hain.

Taint Effect Types: Taint ke teen main effect types hote hain, jo batate hain ki Node kitna "strictly" Pods ko dur rakhega:

  1. NoSchedule:

    • Kaise kaam karta hai: "Agar Pod is Taint ko tolerate nahi karta, toh woh is Node par schedule nahi ho sakta (hamesha Pending mein rahega)."
    • Existing Pods: Agar Pod already chal raha hai aur phir NoSchedule Taint laga, toh woh Pod chalta rahega. NoSchedule sirf nayi scheduling ko affect karta hai.
    • Analogy: "Agar tumhare paas VIP pass nahi hai, toh tum is line mein lag nahi sakte." (But if you're already in line, you can stay).
  2. PreferNoSchedule:

    • Kaise kaam karta hai: "Agar Pod is Taint ko tolerate nahi karta, toh Node usko is Node par schedule karna prefer nahi karega. Lekin agar koi aur Node available nahi hai, toh chal jayega."
    • Analogy: "VIP pass nahi hai? Hum prefer karenge tum is line mein na lago. Lekin agar koi aur line nahi hai, toh theek hai, aa jao."
  3. NoExecute:

    • Kaise kaam karta hai: "Agar Pod is Taint ko tolerate nahi karta, toh woh is Node par schedule nahi ho sakta. Aur agar Pod already chal raha hai aur phir NoExecute Taint laga, toh woh Pod terminate ho jayega aur us Node se hata diya jayega!"
    • Analogy: "VIP pass nahi hai? Tum is line mein lag nahi sakte. Aur agar tum pehle se line mein ho, toh abhi ke abhi line se bahar niklo!" (Very strict, like a bouncer).
    • Use Case: Node ko maintenance ke liye drain karna ho, ya Node ki health kharab ho jaye.

Toleration Kaise Define Karein: Pods apni YAML file mein tolerations define karte hain. tolerations Taint ke key, operator, value, aur effect se match karte hain.

yaml
spec:
  containers:
  - name: my-app
    image: my-image
  tolerations: # Pod ki tolerations list
  - key: "my-taint-key" # Taint ki key se match
    operator: "Equal" # Operator 'Equal' ya 'Exists' ho sakta hai
    value: "my-taint-value" # Taint ki value se match (agar operator 'Equal' hai)
    effect: "NoSchedule" # Taint ke effect se match
    # Agar Pod ki toleration Taint se match karti hai, toh Pod us tainted Node pe chal sakta hai.

Step 1: Minikube Node Ko Taint Karo (NoSchedule effect ke saath) Ab hum minikube Node pe ek Taint lagayenge. Iska matlab hai ki ab koi bhi naya Pod (jo is Taint ko tolerate nahi karta) minikube Node pe schedule nahi hoga.

bash
kubectl taint node minikube dedicated=critical:NoSchedule

Explanation:

  • kubectl taint node minikube dedicated=critical:NoSchedule: This command adds a Taint to the minikube Node.
    • key: dedicated
    • value: critical
    • effect: NoSchedule
  • Result: node/minikube tainted message dikhega.

Verify karo ki Taint laga hai ya nahi:

bash
kubectl describe node minikube | grep -i Taints

Explanation:

  • grep -i Taints: grep command Taints word ko search karega (case-insensitive due to -i).
  • Result: Tumhein Taints: dedicated=critical:NoSchedule dikhega.

Step 2: Ek Pod Banao Jo Taint Ko Tolerate Nahi Karta Chalo, ek simple Pod banaate hain jiski YAML file mein koi tolerations nahi hain. Yeh Pod is dedicated=critical:NoSchedule Taint ko tolerate nahi karta.

Apne computer pe ek new file no-toleration-pod.yaml naam se banao aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct!

yaml
# File: no-toleration-pod.yaml

# Pod that does NOT have any tolerations defined.
# It will NOT be scheduled on a Node that has a 'NoSchedule' taint
# unless that taint is removed.
apiVersion: v1
kind: Pod
metadata:
  name: untolerated-app-pod # Pod's name
spec:
  containers:
  - name: nginx-untolerated-container
    image: nginx:latest
    ports:
    - containerPort: 80

Explanation:

  • Is Pod definition mein tolerations section nahi hai. Iska matlab hai ki yeh Pod dedicated=critical:NoSchedule Taint ko tolerate nahi karta.

Step 3: Untolerated Pod Ko Apply Karo

bash
kubectl apply -f no-toleration-pod.yaml

Explanation:

  • kubectl apply -f no-toleration-pod.yaml: This command creates the untolerated-app-pod.
  • Result: pod/untolerated-app-pod created message dikhega.

Step 4: Untolerated Pod Status Dekho (Pending hoga!) Pods ki status dekho. Ek alag terminal mein kubectl get pods -w chala sakte ho.

bash
kubectl get pods -o wide

Explanation:

  • Result: Tum dekhoge ki untolerated-app-pod Pending status mein rahega! ⏳ Aur NODE column blank hoga.
    NAME                READY   STATUS    RESTARTS   AGE   IP       NODE       NOMINATED NODE   READINESS GATES
    untolerated-app-pod 0/1     Pending   0          10s   <none>   <none>     <none>           <none>
    • Why Pending? Kyunki minikube Node pe dedicated=critical:NoSchedule Taint laga hai, aur untolerated-app-pod is Taint ko tolerate nahi karta. Kubernetes scheduler ise minikube Node pe schedule nahi kar sakta, aur Minikube mein aur koi Node hai nahi, toh yeh Pending mein hi atka rahega.

Step 5: Taint Ko Tolerate Karne Wale Pods Banao Ab hum do Pods banaate hain jinmein tolerations define kiye gaye hain, taaki woh dedicated=critical:NoSchedule Taint ko tolerate kar sakein.

Apne computer pe ek new file tolerated-pods.yaml naam se banao aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct!

yaml
# File: tolerated-pods.yaml

# Pod 1: Tolerates the specific Taint key, value, and effect (Equal operator)
apiVersion: v1
kind: Pod
metadata:
  name: tolerated-app-equal-pod # Pod's name
spec:
  containers:
  - name: nginx-tolerant-equal-container
    image: nginx:latest
    ports:
    - containerPort: 80
  tolerations: # This Pod defines tolerations
  - key: "dedicated" # Key of the Taint to tolerate
    operator: "Equal" # Operator: 'Equal' means both key and value must match
    value: "critical" # Value of the Taint to tolerate
    effect: "NoSchedule" # Effect of the Taint to tolerate
---
# Pod 2: Tolerates a Taint with a specific key, regardless of its value (Exists operator)
apiVersion: v1
kind: Pod
metadata:
  name: tolerated-app-exists-pod # Pod's name
spec:
  containers:
  - name: nginx-tolerant-exists-container
    image: nginx:latest
    ports:
    - containerPort: 80
  tolerations: # This Pod defines tolerations
  - key: "dedicated" # Key of the Taint to tolerate
    operator: "Exists" # Operator: 'Exists' means only the key must match, value can be anything
    effect: "NoSchedule" # Effect of the Taint to tolerate

Explanation (YAML file ke har section ki simplified jankari):

  • Pod 1 (tolerated-app-equal-pod - Equal Operator):
    • tolerations: - key: "dedicated", operator: "Equal", value: "critical", effect: "NoSchedule": Yeh Pod dedicated=critical:NoSchedule Taint ko Equal operator se tolerate karta hai. Matlab, Taint की key (dedicated), value (critical), aur effect (NoSchedule) sab match hone chahiye.
  • Pod 2 (tolerated-app-exists-pod - Exists Operator):
    • tolerations: - key: "dedicated", operator: "Exists", effect: "NoSchedule": Yeh Pod dedicated key wale kisi bhi NoSchedule Taint को tolerate करता है, chahe uski value kuch bhi ho (jaise dedicated=production:NoSchedule ya dedicated=test:NoSchedule). Exists operator sirf key ko check karta hai.

Step 6: Tolerant Pods Ko Apply Karo

bash
kubectl apply -f tolerated-pods.yaml

Explanation:

  • kubectl apply -f tolerated-pods.yaml: This command creates both tolerant Pods.
  • Result: pod/tolerated-app-equal-pod created and pod/tolerated-app-exists-pod created messages dikhenge.

Step 7: Pod Status Dekho (Tolerant Pods Running honge!)

bash
kubectl get pods -o wide

Explanation:

  • Result: Tum dekhoge ki tolerated-app-equal-pod aur tolerated-app-exists-pod dono Running honge aur minikube Node par hi honge! 🎉
    NAME                       READY   STATUS    RESTARTS   AGE   IP           NODE       NOMINATED NODE   READINESS GATES
    tolerated-app-equal-pod    1/1     Running   0          10s   172.17.0.X   minikube   <none>           <none>
    tolerated-app-exists-pod   1/1     Running   0          10s   172.17.0.Y   minikube   <none>           <none>
    untolerated-app-pod        0/1     Pending   0          2m    <none>       <none>     <none>           <none>
    • Why Running? Kyunki yeh Pods dedicated=critical:NoSchedule Taint ko tolerate karte hain, Kubernetes scheduler ne unhein minikube Node pe schedule kar diya. untolerated-app-pod ab bhi Pending mein rahega.

Step 8: Node Taint Change Karo NoSchedule se NoExecute (Eviction ka Magic!) Ab dekho NoExecute effect ka magic! Yeh un Pods ko Node se hatata hai jo is Taint ko tolerate nahi karte, chahe woh pehle se chal rahe hon.

Pehle, ensure karo untolerated-app-pod Pending hai. Ab Node ke Taint को NoSchedule से NoExecute में बदल दो:

bash
kubectl taint node minikube dedicated=critical:NoExecute --overwrite

Explanation:

  • kubectl taint node minikube dedicated=critical:NoExecute: Taint ko dedicated=critical:NoExecute pe update karo.
  • --overwrite: Zaroori hai agar Taint dedicated key se pehle se laga ho, usko overwrite karne ke liye.
  • Result: node/minikube tainted message dikhega.

Pods ki status dekho (ek alag terminal mein kubectl get pods -w chalao):

bash
kubectl get pods -w

Explanation:

  • What to observe:
    • untolerated-app-pod (jo pehle Pending tha) ab bhi Pending ya Terminating dikhega. NoExecute ka matlab hai ki ab woh kabhi schedule nahi hoga, agar woh kisi wajah se chal bhi raha hota toh terminate ho jata.
    • tolerated-app-equal-pod aur tolerated-app-exists-pod Running hi rahenge, kyunki woh tolerate karte hain.
    # If untolerated-app-pod was already Pending:
    NAME                       READY   STATUS    RESTARTS   AGE
    tolerated-app-equal-pod    1/1     Running   0          1m
    tolerated-app-exists-pod   1/1     Running   0          1m
    untolerated-app-pod        0/1     Pending   0          3m (remains Pending)
    • Scenario (for demonstration): Agar untolerated-app-pod kisi wajah se chal raha hota (Running status mein hota) aur phir tum NoExecute Taint lagate, toh woh Pod Terminating ho jata aur Node se evict (hataya) kar diya jata! Try this if you want:
      1. Node से Taint हटाओ: kubectl taint node minikube dedicated-
      2. no-toleration-pod.yaml को apply करो: kubectl apply -f no-toleration-pod.yaml (यह Running हो जाएगा)
      3. अब Node पर NoExecute Taint लगाओ: kubectl taint node minikube dedicated=critical:NoExecute
      4. देखो kubectl get pods -w में: untolerated-app-pod Terminating हो जाएगा! यह NoExecute का power है।

Step 9: Cleanup - Saare Resources Delete Karo Jab kaam khatam ho jaye, toh saare Pods ko delete karo aur Node se Taint hata do.

bash
# 1. Delete all Pods created in this chapter
kubectl delete -f no-toleration-pod.yaml
kubectl delete -f tolerated-pods.yaml

# 2. Remove the taint from the minikube Node
kubectl taint node minikube dedicated- # Remove the 'dedicated' taint

Explanation:

  • kubectl delete -f <file_name>: Deletes the specified Pods.
  • kubectl taint node minikube dedicated-: Removes the Taint with dedicated key from the minikube Node.

Node Affinity aur Taint/Toleration tumhe apne apps ko Nodes pe bahut smartly place karne ki power dete hain, ya unhein kuch khaas Nodes se dur rakhne ki. Yeh bahut important hain complex Kubernetes environments mein, khaas kar jab tumhare paas special hardware wale Nodes hon. Agle chapter mein hum bahar ki duniya se apne apps tak pahunchne ka raasta banana seekhenge! 🚦


Chapter 15: Bahar Ki Duniya Se Apps ko Milana: Ingress 🚦

Pichhle chapters mein humne dekha ki Service (jaise NodePort Service, Chapter 7) ka use karke tum apne apps ko cluster ke bahar se access kar sakte ho. NodePort mein users Node ke IP address aur ek specific port (NodePort, jaise 30080) se connect karte hain.

Lekin, agar tumhare paas bahut saari websites ya games hain, aur har website ki apni Service hai?

  • mygame.com -> Node IP:30001
  • myblog.com -> Node IP:30002
  • myshop.com -> Node IP:30003

Users ko itne saare Node IP aur NodePort numbers yaad rakhne padenge, aur har baar Node IP:Port type karna padega. Yeh toh bahut mushkil hai aur professional bhi nahi lagta! 😫

Yahin pe Kubernetes ka Ingress (pronounced: in-gress) kaam aata hai!

15.1 Ingress Kya Hai? (Like a Theme Park Entrance for your Website) 🎪

  • Ingress: Ingress ek Kubernetes object hai. Yeh bahar ki duniya se (internet se) tumhare Kubernetes cluster ke andar chal rahe Services tak traffic ko manage aur route karta hai. Socho, jaise ek bahut bada theme park hai (tumhara Kubernetes cluster). Park ke andar bahut saari rides (tumhare apps, yaani Pods) hain, aur har ride ka apna ticket counter (Service) hai.
    • Ingress is theme park ka main entrance gate hai. Tumhein har ride ke alag-alag ticket counter pe jaane ki zaroorat nahi. Tum bas main gate pe aate ho aur gate keeper (Ingress Controller) tumhe sahi ride tak guide kar deta hai, tumne kaunsi ride maangi hai uske naam se.
  • Key Idea: Ingress tumhe single entry point (ek hi IP address ya domain name) deta hai, aur phir woh incoming traffic ko sahi Service (aur uske pichhe ke Pods) tak bhej deta hai, based on:
    • Domain Name (Host-based routing): Jaise mygame.com ko Game Service pe bhejo, aur myblog.com ko Blog Service pe.
    • URL Path (Path-based routing): Jaise mywebsite.com/shop ko Shop Service pe bhejo, aur mywebsite.com/blog ko Blog Service pe.
  • Load Balancing and SSL/TLS Termination: Ingress advanced features bhi provide karta hai jaise Load Balancing (traffic ko evenly distribute karna) aur SSL/TLS Termination (secure communication, jisse https:// kaam karta hai).

15.2 Ingress Controller: The Smart Gatekeeper 👮

Ingress ko chalane ke liye, tumhe ek Ingress Controller chahiye hota hai. Yeh ek special app hai jo cluster ke andar chalta hai aur Ingress rules ko implement karta hai.

  • Ingress Controller kya hai? Yeh ek real application hai (jaise Nginx, HAProxy, Traefik) jo traffic ko receive karta hai aur phir Ingress object mein likhe rules ke hisaab se use sahi Service tak forward karta hai.
  • Minikube mein: Minikube mein by default Nginx Ingress Controller hota hai, jise hum minikube addons enable ingress command se chalu kar sakte hain.

Step 1: Minikube mein Ingress Addon Enable Karo Pehle ensure karo ki Minikube chal raha hai. Agar band hai toh minikube start karo. Ab, Ingress Controller addon ko enable karo:

bash
minikube addons enable ingress

Explanation:

  • minikube addons enable ingress: This command installs the Nginx Ingress Controller (a specialized web server that reads Ingress rules) into your Minikube cluster.
  • What happens: Minikube ingress addon se related Deployments aur Services banaega. Ismein thoda time lag sakta hai.
  • Result: ingress is enabled message dikhega.

Verify karo ki Ingress Controller ke Pods Running hain:

bash
kubectl get pods -n ingress-nginx

Explanation:

  • kubectl get pods -n ingress-nginx: ingress-nginx ek special namespace hai jahan Ingress Controller ke Pods chalte hain.
  • Result: Tumhein ingress-nginx-controller- naam ka ek Pod Running dikhega.
    NAME                             READY   STATUS    RESTARTS   AGE
    ingress-nginx-controller-abcde   1/1     Running   0          1m

Step 2: Frontend Apps (Deployments aur Services) Banao Hum do simple web apps banayenge: ek "Blue App" aur ek "Green App". Har app apna ek chhota web page dikhayega. Har app ke liye apna Deployment aur Service banayenge.

Apne computer pe ek new file color-apps-deploy-svc.yaml naam se banao aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct! (Yeh labs/ingress/deploy.yaml se li gayi hai).

yaml
# File: color-apps-deploy-svc.yaml

# Deployment for the Blue App
apiVersion: apps/v1
kind: Deployment
metadata:
  name: blue-app-deployment
  labels:
    app: blue-app
spec:
  replicas: 2 # We want 2 copies of our blue app
  selector:
    matchLabels:
      app: blue-app
  template:
    metadata:
      labels:
        app: blue-app
    spec:
      containers:
      - name: blue-container
        # This is a custom image that simply serves a blue web page.
        # You can create your own or use this for demonstration.
        image: ozgurozturknet/k8s:blue
        ports:
        - containerPort: 80 # This app listens on port 80
---
# Service for the Blue App
apiVersion: v1
kind: Service
metadata:
  name: blue-service # Name of the Service for the blue app
spec:
  selector:
    app: blue-app # This Service selects Pods with 'app: blue-app' label
  ports:
    - protocol: TCP
      port: 80 # Service port
      targetPort: 80 # Pod port
---
# Deployment for the Green App
apiVersion: apps/v1
kind: Deployment
metadata:
  name: green-app-deployment
  labels:
    app: green-app
spec:
  replicas: 2 # We want 2 copies of our green app
  selector:
    matchLabels:
      app: green-app
  template:
    metadata:
      labels:
        app: green-app
    spec:
      containers:
      - name: green-container
        # This is a custom image that simply serves a green web page.
        image: ozgurozturknet/k8s:green
        ports:
        - containerPort: 80 # This app listens on port 80
---
# Service for the Green App
apiVersion: v1
kind: Service
metadata:
  name: green-service # Name of the Service for the green app
spec:
  selector:
    app: green-app # This Service selects Pods with 'app: green-app' label
  ports:
    - protocol: TCP
      port: 80 # Service port
      targetPort: 80 # Pod port

Explanation (YAML file ke har section ki simplified jankari):

  • Blue App: blue-app-deployment (2 copies of ozgurozturknet/k8s:blue image) aur blue-service.
  • Green App: green-app-deployment (2 copies of ozgurozturknet/k8s:green image) aur green-service.
  • Dono apps port 80 pe chalenge aur unki Services bhi port 80 pe hongi.

Step 3: Deployments aur Services Ko Apply Karo

bash
kubectl apply -f color-apps-deploy-svc.yaml

Explanation:

  • kubectl apply -f color-apps-deploy-svc.yaml: This command creates all the Deployments and Services for our color apps.
  • Result: Messages like deployment.apps/blue-app-deployment created, service/blue-service created, etc. dikhenge.

Verify karo ki Pods Running hain:

bash
kubectl get pods -w

Explanation: Wait for all blue-app-deployment and green-app-deployment Pods to be Running. Then press Ctrl+C.

Step 4: Ingress Rule File Banao Ab hum Ingress rule banaenge. Yeh Ingress batayega ki jab mycolorapp.com/blue request aaye toh blue-service pe bhejo, aur jab mycolorapp.com/green request aaye toh green-service pe bhejo.

Apne computer pe ek new file color-apps-ingress.yaml naam se banao aur usmein yeh code copy paste karo. Make sure spacing (indentation) is correct! (Yeh labs/ingress/appingress.yaml se li gayi hai).

yaml
# File: color-apps-ingress.yaml

# API version for Ingress objects (networking.k8s.io/v1 for Ingress)
apiVersion: networking.k8s.io/v1
# Type of Kubernetes object: Ingress
kind: Ingress
# Metadata for our Ingress
metadata:
  # Name of our Ingress
  name: color-apps-ingress # This name identifies our Ingress rule
  # Annotations provide extra configuration for the Ingress Controller.
  # This specific annotation is for the Nginx Ingress Controller.
  # 'rewrite-target: /' means that if a request comes in for "/blue" or "/green",
  # the Ingress Controller will rewrite the path to just "/" before sending it to the backend Service.
  # For example, "/blue" becomes "/" for blue-service, which simplifies backend app logic.
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$1 # '$1' is a regex group, capturing part of the path
                                                    # For simple path forwarding, often just '/' is enough,
                                                    # but this regex version is more robust for trailing slashes.
spec:
  # Rules for routing HTTP traffic.
  rules:
    # 'host' specifies the domain name for which this rule applies.
    # When a request comes for 'mycolorapp.com', this rule will be checked.
    - host: mycolorapp.com # We will use this domain name to access our apps
      # 'http' section defines rules for HTTP traffic
      http:
        # 'paths' defines a list of routing rules based on the URL path.
        paths:
          # Rule for '/blue' path
          - path: /blue # When the URL path starts with '/blue' (e.g., mycolorapp.com/blue)
            # 'pathType: Prefix' means any path starting with '/blue' will match (e.g., /blue/page1)
            pathType: Prefix
            # 'backend' specifies the Service where the traffic should be routed.
            backend:
              service:
                name: blue-service # Route traffic to 'blue-service'
                port:
                  number: 80 # On port 80 of 'blue-service'
          # Rule for '/green' path
          - path: /green # When the URL path starts with '/green' (e.g., mycolorapp.com/green)
            pathType: Prefix
            backend:
              service:
                name: green-service # Route traffic to 'green-service'
                port:
                  number: 80 # On port 80 of 'green-service'

Explanation (YAML file ke har section ki simplified jankari):

  • kind: Ingress: Hum ek Ingress object bana rahe hain.
  • name: color-apps-ingress: Ingress ka naam color-apps-ingress hai.
  • annotations: nginx.ingress.kubernetes.io/rewrite-target: /$1: Yeh Nginx Ingress Controller ke liye ek special setting hai! Iska matlab hai ki jab request /blue pe aaye, toh Ingress Controller us path ko rewrite karke Service ko sirf / path pe hi bhejega. Example: agar request mycolorapp.com/blue pe aayi, toh Ingress Controller use blue-service pe bhejega, lekin blue-service ko path / milega. /$1 ek regex feature hai jo URL ka path capture karta hai.
  • spec: rules:: Yahan hum traffic routing rules define karte hain.
    • - host: mycolorapp.com: Yeh domain name hai. Jab mycolorapp.com domain se request aayegi, toh is rule ko check kiya jayega.
    • http: paths:: Is domain ke liye, URL path ke hisaab se route karo.
      • - path: /blue, pathType: Prefix, backend: service: name: blue-service, port: number: 80: Jab URL path /blue se shuru ho (jaise mycolorapp.com/blue ya mycolorapp.com/blue/home), toh traffic ko blue-service ke port 80 pe bhejo.
      • - path: /green, pathType: Prefix, backend: service: name: green-service, port: number: 80: Jab URL path /green se shuru ho, toh traffic ko green-service ke port 80 pe bhejo.

Step 5: Ingress Rule Ko Apply Karo

bash
kubectl apply -f color-apps-ingress.yaml

Explanation:

  • kubectl apply -f color-apps-ingress.yaml: This command creates the color-apps-ingress Ingress rule.
  • Result: ingress.networking.k8s.io/color-apps-ingress created message dikhega.

Step 6: Ingress Ka IP Address Pata Karo Ab humein Ingress Controller ka IP address chahiye, jise hum apne computer ke hosts file mein add karenge.

bash
kubectl get ingress

Explanation:

  • kubectl get ingress: This command lists all Ingress objects.
  • Result: Tumhein color-apps-ingress dikhega. ADDRESS column mein ek IP address hoga. Minikube mein yeh Minikube ka IP address ya Load Balancer ka IP address ho sakta hai. Is IP ko copy kar lo.
    NAME                 CLASS    HOSTS          ADDRESS         PORTS   AGE
    color-apps-ingress   <none>   mycolorapp.com 192.168.49.2    80      10s
    • ADDRESS: Yeh IP address copy kar lo! Tumhare case mein koi alag IP hoga. For Minikube, it's usually the Minikube VM's IP.

15.3 Host File Editing: Your Computer's Phonebook ☎️

Jab tum apne browser mein mycolorapp.com type karte ho, toh tumhara computer pehle check karta hai ki mycolorapp.com ka IP address kya hai. Yeh check karne ke liye, woh sabse pehle apni hosts file dekhta hai. hosts file tumhare computer ki ek choti phonebook jaisi hai, jahan tum domain names ko IP addresses se map kar sakte ho.

Hum Ingress Controller ke IP address ko mycolorapp.com se map karenge hosts file mein, taaki jab tum mycolorapp.com type karo, toh tumhara computer seedha Ingress Controller tak pahunche.

Step 7: hosts File Edit Karo Yeh step operating system-specific hai:

  • Windows pe:
    1. Notepad ko "Run as administrator" karke open karo. Yeh bahut zaruri hai!
    2. File -> Open pe click karo.
    3. Address bar mein type karo: C:\Windows\System32\drivers\etc\hosts aur Enter press karo. hosts file select karke Open karo.
  • Linux/macOS pe:
    1. Terminal open karo.
    2. sudo nano /etc/hosts (ya sudo vi /etc/hosts) type karke Enter press karo. Apna password daalo.

File ke end mein yeh line add karo (replace <INGRESS_IP_ADDRESS> with the IP address jo tumne Step 6 mein copy kiya tha):

<INGRESS_IP_ADDRESS> mycolorapp.com

Example: Agar tumhara Ingress IP 192.168.49.2 hai, toh line hogi:

192.168.49.2 mycolorapp.com

File save kar do:

  • Notepad pe (Windows): File -> Save.
  • Nano pe (Linux/macOS): Ctrl+X, Y press karo, phir Enter.

Step 8: Browser Mein Apps Access Karo (Magic!) Ab apne web browser (jaise Chrome, Firefox) ko open karo aur address bar mein type karo:

  • http://mycolorapp.com/blue
  • http://mycolorapp.com/green

Explanation:

  • http://mycolorapp.com/blue: Tumhara computer mycolorapp.com ka IP address hosts file se lega (jo Ingress Controller ka IP hai). Request Ingress Controller tak jayegi.
  • Ingress Controller mycolorapp.com domain aur /blue path ko dekhega. Apne rule (color-apps-ingress) ke hisaab se, woh request ko blue-service pe bhejega.
  • blue-service us request ko blue-app-deployment ke kisi bhi available Pod tak forward kar dega.
  • Result: Tumhe dikhega ki /blue URL pe blue app ka page dikhta hai aur /green URL pe green app ka page dikhta hai! 🎉 Ingress ne automatically traffic ko sahi Service pe bhej diya, aur tumhe multiple ports yaad rakhne ki zarurat nahi padi.

Step 9: Cleanup - Saare Resources Delete Karo Jab kaam khatam ho jaye, toh saare Kubernetes objects aur hosts file entry ko delete karo.

bash
# 1. Delete the Ingress rule
kubectl delete -f color-apps-ingress.yaml

# 2. Delete the Deployments and Services for the color apps
kubectl delete -f color-apps-deploy-svc.yaml

# 3. Disable the Minikube Ingress addon (optional, but good for cleanup)
minikube addons disable ingress

# 4. REMOVE THE ENTRY FROM YOUR HOSTS FILE! (VERY IMPORTANT)
#    Go back to your hosts file (Step 7) and delete the line you added:
#    <INGRESS_IP_ADDRESS> mycolorapp.com
#    Save the hosts file. Otherwise, you might not be able to access real websites later if they have the same domain name.

Explanation:

  • kubectl delete -f <file_name>: Deletes the specified Kubernetes objects.
  • minikube addons disable ingress: Turns off the Ingress Controller.
  • hosts file cleanup: Yeh bahut zaroori hai! Agar tum hosts file se entry nahi hataoge, toh mycolorapp.com hamesha tumhare Ingress Controller ke IP pe hi resolve hoga, aur tum phir real mycolorapp.com website (agar koi exist karti hai) ko access nahi kar paoge.

Ingress websites aur apps ko internet pe expose karne ka ek bahut hi powerful tareeka hai, khaas kar jab tumhare paas bahut saari Services hon. Yeh URLs aur domain names ke hisaab se traffic manage karta hai, aur tumhein single entry point deta hai. Ab tum apps ko bahar ki duniya se connect karna bhi seekh gaye ho! Agle chapter mein hum Kubernetes ko ek bade control panel ki tarah dekhna seekhenge! 📊



Chapter 16: K8s ki Control Panel: Dashboard 📊

Pichhle chapters mein humne Deployments, Services, Pods, aur bahut saare Kubernetes objects banaaye hain. Jab tum kubectl get pods ya kubectl get deployments jaise commands chalate ho, toh tumhe saari information text format mein terminal pe dikhti hai.

Lekin, agar tumhara cluster bahut bada ho gaya, jismein 1000 Pods chal rahe hain? Har cheez ko commands se dekhna, uski health check karna, errors dhundhna, yeh sab bahut mushkil aur thaka dene wala kaam ho sakta hai. 😫

Kya koi aisa tareeka hai jahan hum apne poore Kubernetes cluster ko ek saath, ek graphical, interactive screen pe dekh sakein? Jaisa koi video game khelte waqt uska scoreboard ya map dikhta hai, jahan tum sab kuch ek nazar mein dekh sakte ho?

Haan! Kubernetes mein ek Dashboard hota hai!

16.1 Dashboard Kya Hai? (Like a Video Game Scoreboard for your Cluster) 🎮

  • Kubernetes Dashboard: Kubernetes Dashboard ek web-based UI (User Interface) hai. Yeh tumhare Kubernetes cluster ka ek graphical view dikhata hai. Socho, jaise tumhara favourite video game ka scoreboard ya map, jahan tum apne saare scores, current game status, players ki list, aur map pe kya ho raha hai, sab kuch ek screen pe dekh sakte ho.
  • Purpose:
    • Visual Overview: Tum saare Kubernetes objects (Pods, Deployments, Services, etc.) ko ek hi jagah, organized tareeke se dekh sakte ho.
    • Health at a Glance: Unki current STATUS (Running, Pending, Failed), RESTARTS count, aur overall health ko easily check kar sakte ho.
    • Resource Usage: Nodes aur Pods kitni CPU aur Memory use kar rahe hain, yeh graphs mein dekh sakte ho (agar metrics-server installed hai).
    • Detailed Information: Kisi bhi object pe click karke uski detailed information, events (kya-kya hua uske saath), aur logs ko web UI mein hi dekh sakte ho.
    • Basic Management: Naye objects bana sakte ho ya existing ones ko edit kar sakte ho (lekin shuru mein sirf dekhna aur learn karna achha hai).
    • Troubleshooting: Problems (jaise Pod stuck ho gaya) ko dhundhne aur solve karne mein bahut help karta hai.

Minikube mein Dashboard Enable Karna: Minikube mein Dashboard enable karna bahut easy hai, kyunki yeh ek built-in addon hai.

Step 1: Minikube Dashboard Addon Enable Karo Pehle ensure karo ki Minikube chal raha hai. Agar band hai toh minikube start karo. Ab, Dashboard addon ko enable karo:

bash
minikube addons enable dashboard

Explanation:

  • minikube addons enable dashboard: Yeh command Kubernetes Dashboard ko Minikube cluster mein install kar dega.
  • What happens: Minikube background mein Dashboard application ke liye zaruri Deployments, Services, aur other Kubernetes objects ko create karega. Ismein thoda time lag sakta hai, jaise koi naya software install hone mein time lagta hai.
  • Result: dashboard is enabled message dikhega.

Step 2: Metrics Server Addon Enable Karo (Optional but Recommended) Dashboard ko Pods aur Nodes ka CPU aur Memory usage graphs mein dikhane ke liye, metrics-server ki zaroorat hoti hai. Agar tum metrics-server enable nahi karoge, toh Dashboard chalega, lekin graphs empty dikhenge. Isko bhi enable kar lo:

bash
minikube addons enable metrics-server

Explanation:

  • minikube addons enable metrics-server: Yeh command metrics-server application ko install karta hai, jo cluster ke resources (CPU, Memory) ka data collect karta hai.
  • Result: metrics-server is enabled message dikhega.

Verify karo ki Dashboard aur Metrics Server ke Pods Running hain. Dashboard kubernetes-dashboard namespace mein chalta hai, aur Metrics Server kube-system namespace mein.

bash
kubectl get pods -n kubernetes-dashboard
kubectl get pods -n kube-system -l k8s-app=metrics-server

Explanation:

  • kubectl get pods -n kubernetes-dashboard: Lists Pods in the kubernetes-dashboard namespace. Tumhein kubernetes-dashboard- naam ka Pod Running dikhega.
  • kubectl get pods -n kube-system -l k8s-app=metrics-server: Lists Pods in kube-system namespace with label k8s-app=metrics-server. Tumhein metrics-server- naam ka Pod Running dikhega.
  • Result: Dono commands ke outputs mein Running status dikhna chahiye.

Step 3: Dashboard Open Karo (Browser mein) Ab, Dashboard ko apne browser mein open karne ke liye:

bash
minikube dashboard

Explanation:

  • minikube dashboard: Yeh command automatically tumhare default web browser mein Kubernetes Dashboard open kar dega.
  • What happens: Minikube ek temporary kubectl proxy session start karega jo Dashboard ko tumhare computer se accessible banayega, aur phir browser ko us URL pe open kar dega.
  • Result: Tumhare browser mein Kubernetes Dashboard ka login page open hoga. URL kuch aisa hoga: http://127.0.0.1:port_number/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/.

16.2 Dashboard Login: Getting the Secret Key 🔑

Jab Dashboard open hoga, toh tumhe login karne ke liye Kubeconfig ya Token option dikhega. Token se login karna zyada convenient hai Minikube ke liye. Token ek secret key (password jaisa) hoti hai jo tumhe apne aap generate karni padegi.

Step 1: Dashboard User aur Permissions Banao Humein ek special user (ServiceAccount) banana padega jise Dashboard access karne ki permission ho. Hum us user ko cluster-admin permissions denge taaki woh cluster mein sab kuch dekh sake (aur kar sake, lekin abhi hum sirf dekhne ke liye use karenge).

Apne terminal mein yeh commands type karo:

bash
# 1. Create a Service Account for the Dashboard user
# ServiceAccount ek special user hai jo apps use karte hain Kubernetes se baat karne ke liye.
kubectl create serviceaccount minikube-dashboard-user

Explanation:

  • kubectl create serviceaccount minikube-dashboard-user: This creates a ServiceAccount named minikube-dashboard-user.
  • Result: serviceaccount/minikube-dashboard-user created
bash
# 2. Give 'cluster-admin' role to this Service Account
# ClusterRoleBinding user ko permissions deta hai (yahan 'cluster-admin' role).
# 'cluster-admin' role matlab, is user ke paas cluster mein sab kuch karne ki power hai.
# Default namespace mein bana rahe hain.
kubectl create clusterrolebinding minikube-dashboard-rolebinding --clusterrole=cluster-admin --serviceaccount=default:minikube-dashboard-user

Explanation:

  • kubectl create clusterrolebinding minikube-dashboard-rolebinding: This creates a ClusterRoleBinding named minikube-dashboard-rolebinding.
  • --clusterrole=cluster-admin: Binds this user to the built-in cluster-admin role.
  • --serviceaccount=default:minikube-dashboard-user: Specifies which ServiceAccount (in which namespace) is being bound to the role.
  • Result: clusterrolebinding.rbac.authorization.k8s.io/minikube-dashboard-rolebinding created

Step 2: Dashboard User Ka Secret Token Extract Karo Ab humne user bana liya aur permissions bhi de di. Ab is user ka secret token nikalna hai, jisse hum Dashboard mein login karenge.

bash
kubectl get secret $(kubectl get serviceaccount minikube-dashboard-user -o jsonpath="{.secrets[0].name}") -o jsonpath="{.data.token}" | base64 --decode

Explanation:

  • Inner command (kubectl get serviceaccount ...):
    • kubectl get serviceaccount minikube-dashboard-user -o jsonpath="{.secrets[0].name}": This command gets the minikube-dashboard-user ServiceAccount's details and extracts the name of its first associated secret (which contains the token).
  • Outer command (kubectl get secret ... | base64 --decode):
    • kubectl get secret <secret_name_from_above> -o jsonpath="{.data.token}": This gets the content of that secret and extracts the actual token from its data field.
    • | base64 --decode: The token is stored as base64 encoded. This pipes the encoded token to base64 --decode command, which decodes it into a readable string.
  • Result: Tumhein ek bahut lamba sa alphanumeric string (key) dikhega. Is poore string ko copy kar lo! Yeh tumhara Dashboard login token hai.
    eyJhbGciOiJSUzI1NiIsImtpZCI6InVvQk... (a very long string) ...

Step 3: Dashboard Mein Login Karo

  1. Apne browser mein Kubernetes Dashboard ka login page kholo (jo minikube dashboard command se open hua tha).
  2. Token option select karo.
  3. Jo lamba string (token) tumne Step 2 mein copy kiya tha, usko Enter token box mein paste karo.
  4. Sign in button pe click karo.

Result: Wah! 🎉 Tumhara Kubernetes Dashboard open ho jayega! Tumhe cluster ka ek beautiful graphical overview dikhega.

Dashboard mein Kya-kya Dekh Sakte Ho: Dashboard mein tumhe left side pe ek navigation bar milegi. Usmein tum bahut saari cheezein dekh sakte ho:

  • Overview: Pure cluster ka summary, kitne Nodes hain, kitne Pods chal rahe hain, kitne Deployments hain.
  • Workloads: Tumhare saare Deployments, Pods, DaemonSets, StatefulSets, Jobs, CronJobs. Unki health, kitne restart hue, kaunse Node pe chal rahe hain, resource usage graphs (agar Metrics Server enabled hai).
  • Services: Tumhare saare Services (ClusterIP, NodePort, LoadBalancer), Ingresses. Unke IP addresses, ports.
  • Storage: Tumhare Persistent Volumes aur Persistent Volume Claims.
  • Config & Storage: ConfigMaps aur Secrets (bas unke names dikhenge, content secret rahega).
  • Cluster (Left Nav Bar mein):
    • Nodes: Tumhare cluster ke saare physical/virtual Nodes. Unki CPU, Memory usage graphs.
    • Namespaces: Alag-alag namespaces.
    • Roles, Role Bindings, Service Accounts: Security se related cheezein.
    • Events: Cluster mein kya-kya ho raha hai, uski live list.

Example: Pods Dekhna: Left side pe Workloads -> Pods pe click karo. Tumhe saare Pods ki list dikhegi. Kisi bhi Pod pe click karke uski detailed info, events (kya hua uske saath), aur logs bhi web UI mein hi dekh sakte ho. Try it!

Kubernetes Dashboard tumhare liye ek superpower hai. Yeh cluster ko "live" dekhne, monitor karne, aur samajhne mein help karta hai, bina har baar command type kiye.

Cleanup: Jab kaam khatam ho jaye, toh Minikube addons ko disable kar do aur jo user banaya tha, use delete kar do.

bash
# 1. Disable the Minikube Dashboard addon
minikube addons disable dashboard

# 2. Disable the Minikube Metrics Server addon
minikube addons disable metrics-server

# 3. Delete the Service Account and ClusterRoleBinding we created for Dashboard login
kubectl delete serviceaccount minikube-dashboard-user
kubectl delete clusterrolebinding minikube-dashboard-rolebinding

Explanation:

  • minikube addons disable <addon_name>: Turns off the specified Minikube addon.
  • kubectl delete serviceaccount <name>: Deletes the ServiceAccount.
  • kubectl delete clusterrolebinding <name>: Deletes the ClusterRoleBinding.

Ab tum apne cluster ka control panel bhi samajh gaye ho. Agle chapter mein hum apps ko install karne ka sabse easy tareeka seekhenge – jaise phone mein app store hota hai! 🛍️


Chapter 17: Apps ka App Store: Helm 🛍️

Pichhle chapters mein humne Deployments, Services, ConfigMaps, aur bahut saare Kubernetes objects ko banaane ke liye YAML files likhi hain. Imagine karo, tumhe ek bada app install karna hai, jaise WordPress (ek website banane ka software). WordPress ko chalane ke liye tumhe:

  • Ek Deployment chahiye (WordPress server ke liye)
  • Ek Service chahiye (users tak pahunchne ke liye)
  • Ek PersistentVolumeClaim chahiye (website ka data save karne ke liye)
  • Ek Secret chahiye (database password ke liye)
  • Ek Deployment aur Service database ke liye (MySQL ya MariaDB)
  • Aur ho sakta hai kuch ConfigMaps ya Ingress rules bhi!

Itni saari YAML files likhna aur unko ek saath manage karna, phir unko update karna kitna mushkil hoga! 😫

Yahin pe Kubernetes ka "App Store" aata hai, jiska naam hai Helm!

17.1 Helm Kya Hai? (Like Google Play Store for Kubernetes Apps) 📱

  • Helm: Helm Kubernetes ke liye ek package manager hai. Jaise tumhare phone mein Google Play Store ya Apple App Store hai, jahan tum games aur apps download karte ho, waise hi Kubernetes mein Helm hai. Yeh Kubernetes applications ko easily deploy (install), manage, aur upgrade karne mein help karta hai.
  • Key Idea: Helm ek single command se complex Kubernetes applications ko install kar deta hai. Socho, jaise tum App Store pe Install pe click karte ho, aur game automatically download, install, aur ready ho jata hai, bina tumhe uski files aur settings manually manage kiye.

17.2 Helm Installation (On Your Computer) 💻

Helm ek tool hai jise tumhare computer pe install karna hoga, jahan se tum kubectl commands chalate ho.

Step 1: Helm Install Karo (Linux/Ubuntu pe) Apne terminal mein yeh commands type karo.

bash
# 1. Helm signing key add karo
# Yeh command Helm repository ki public key download karta hai.
# Isse tumhara system verify kar pata hai ki jo packages tum download kar rahe ho woh genuine hain.
curl https://baltocdn.com/helm/signing.asc | sudo apt-key add -

Explanation:

  • curl ... | sudo apt-key add -: Downloads the GPG key and adds it to your system's trusted keys.
  • Result: OK message dikhega.
bash
# 2. Add Helm's stable Debian repository
# Yeh command Helm ke official software repository ko tumhare system ke sources list mein add karta hai.
# Isse tum apt package manager se Helm ko install kar paoge.
sudo apt-get install apt-transport-https --yes
echo "deb https://baltocdn.com/helm/stable/debian/ all main" | sudo tee /etc/apt/sources.list.d/helm-stable-debian.list

Explanation:

  • sudo apt-get install apt-transport-https --yes: Installs a utility to handle HTTPS repositories.
  • echo "deb ..." | sudo tee ...: Adds the Helm repository URL to your system's list of software sources.
  • Result: No specific output, or it shows the deb line.
bash
# 3. Update your package list
# Yeh command tumhare system ke package lists ko update karta hai.
# Isse tumhare system ko naye Helm repository ke packages ke baare mein pata chalega.
sudo apt-get update

Explanation:

  • sudo apt-get update: Refreshes the list of available packages from all configured repositories.
  • Result: Tumhein packages update hone ke messages dikhenge.
bash
# 4. Install Helm
# Ab tum Helm ko install kar sakte ho.
sudo apt-get install helm

Explanation:

  • sudo apt-get install helm: Installs the Helm package.
  • Result: Setting up helm... jaisa message dikhega.
bash
# 5. Helm version check karo (confirm installation)
# Yeh command confirm karega ki Helm successfully install hua hai aur uska version kya hai.
helm version

Explanation:

  • helm version: Shows the installed Helm client version.
  • Result: Tumhein Helm client ka version dikhega, jaise version.BuildInfo{Version:"v3.10.0", ...}.
    version.BuildInfo{Version:"v3.10.0", GitCommit:"9248363200959cd3c857380ad734005089fa0bb2", GitTreeState:"clean", GoVersion:"go1.19.1", Compiler:"gc", Platform:"linux/amd64"}
    Helm ab tumhare computer pe ready hai! 🎉

17.3 Important Helm Terms: Charts, Repositories, Releases 🗺️

Helm ko use karne se pehle, kuch important terms samajh lo:

  • Chart: Helm mein applications ko "Charts" kehte hain. Chart ek packet hota hai jismein ek app ko Kubernetes mein chalane ke liye saari zaruri files (YAML definitions) hoti hain, jaise Deployment, Service, ConfigMap, Pods, PersistentVolumeClaims, sab kuch! Socho, jaise App Store mein ek game.apk file hoti hai, waise hi Helm mein ek game.chart file hoti hai.
    • Analogy: Ek ready-made Lego set box jismein saare parts aur instructions (YAML files) hain ek model banane ke liye.
  • Repository: Yeh woh jagah hoti hai jahan Helm Charts store hote hain. Jaise App Store mein alag-alag developers ke apps hote hain. Tum Artifact Hub (https://artifacthub.io/) pe jaake publicly available charts search kar sakte ho. Yeh ek bada online Helm Chart store hai.
    • Analogy: Google Play Store ya Apple App Store.
  • Release: Jab tum ek Chart install karte ho Kubernetes mein (using helm install), toh us installed instance ko "Release" kehte hain. Agar tum ek hi Chart ko do baar install karte ho (jaise WordPress ko do alag-alag websites ke liye), toh har install ka apna alag Release hota hai aur uska apna naam.
    • Analogy: Tumne "Minecraft" game ko download aur install kiya. Ab woh tumhare phone pe ek "Release" hai. Agar tum us game ka "Lite" version bhi install kar lo, toh woh doosri "Release" hai.

17.4 Installing a Real App with Helm (Jenkins Example) 🚀

Chalo, ab Helm ka use karke ek real aur thoda complex app install karte hain: Jenkins. Jenkins ek popular tool hai jo software banane aur deploy karne mein help karta hai. Uske liye bahut saare Kubernetes objects chahiye hote hain, lekin Helm use ek command se install kar dega.

Step 1: Helm Repository Add Karo Humein Jenkins ke official Helm Charts ko apne local Helm configuration mein add karna padega.

bash
helm repo add jenkins https://charts.jenkins.io

Explanation:

  • helm repo add: Yeh command ek naya repository (online store) add karta hai Helm mein.
  • jenkins: Yeh is repository ka name hai jo humne choose kiya hai. Tum koi bhi naam de sakte ho, jaise my-jenkins-store.
  • https://charts.jenkins.io: Yeh Jenkins Charts repository ka official URL hai.
  • Result: jenkins" has been added to your repositories message dikhega.

Step 2: Repositories Update Karo Jab tum naya repo add karte ho, toh Helm ko batana padta hai ki woh naye Charts ki list download kar le.

bash
helm repo update

Explanation:

  • helm repo update: Yeh command Helm ko batata hai ki saare configured repositories se latest Charts ki list download kar lo.
  • Result: Successfully got an update from the "jenkins" chart repository jaisa message dikhega.

Step 3: Charts Search Karo (Optional, but good for discovery) Chalo, dekhte hain ki jenkins repository mein Jenkins ka Chart available hai ya nahi.

bash
helm search repo jenkins

Explanation:

  • helm search repo: Yeh command tumhare local Helm repositories mein search karta hai.
  • jenkins: Woh keyword jiske liye search karna hai.
  • Result: Tumhein jenkins/jenkins jaisa kuch dikhega, saath mein Chart ka version aur description.
    NAME           CHART VERSION APP VERSION DESCRIPTION
    jenkins/jenkins 4.2.0         2.414.1     Jenkins is a CI/CD server that enables autom...

Step 4: Jenkins Chart Install Karo Ab sabse exciting part! Jenkins Chart ko install karte hain. Ismein Jenkins ka Deployment, Service, Persistent Volume Claim, aur bahut kuch automatically ban jayega.

bash
helm install my-jenkins-master jenkins/jenkins

Explanation:

  • helm install: Yeh command ek Chart ko Kubernetes cluster mein install karta hai.
  • my-jenkins-master: Yeh tumhare Release ka naam hai. Tum koi bhi naam de sakte ho, jaise my-cool-ci-server. Yeh naam unique hona chahiye aur isse tum baad mein is installed Jenkins instance ko manage kar paoge.
  • jenkins/jenkins: Yeh batata hai ki kis repository (jenkins) ka kaunsa Chart (jenkins) install karna hai.
  • What happens: Helm jenkins/jenkins Chart ko padhega, uske andar ki saari YAML templates (Deployment, Service, PVC, etc.) ko generate karega, aur unhein Kubernetes API server ko bhej dega. Kubernetes phir un objects ko cluster mein bana dega. Is process mein thoda time lag sakta hai.
  • Result: Tumhein installation ka summary dikhega, jismein NAME, LAST DEPLOYED, NAMESPACE, STATUS, NOTES jaise details honge. NOTES section mein aksar important instructions hoti hain, jaise password kaise access karein ya Service ko kaise access karein.

Step 5: Dekho Kya-kya Bana Hai! Ab kubectl se check karo ki Helm ne Kubernetes mein kya-kya bana diya hai:

bash
kubectl get pods
kubectl get svc
kubectl get deployment
kubectl get pvc

Explanation:

  • kubectl get pods: Tumhein my-jenkins-master-jenkins- naam ka ek ya do Pods Running dikhenge.
  • kubectl get svc: Tumhein my-jenkins-master-jenkins naam ki Service ClusterIP type ki dikhegi.
  • kubectl get deployment: Tumhein my-jenkins-master-jenkins naam ka Deployment dikhega.
  • kubectl get pvc: Tumhein my-jenkins-master-jenkins- naam ka ek PVC (PersistentVolumeClaim) Bound dikhega, jise Jenkins apna data store karne ke liye use karega.
  • Result: Yeh dikhata hai ki Helm ne ek hi command se itni saari cheezein automatically bana di hain, jo agar tum manually banate toh bahut saari YAML files likhni padti! 🤯

Step 6: Jenkins Ko Access Karo Jenkins web UI ko access karne ke liye, tumhe uska admin password chahiye aur phir port-forwarding karna padega.

Jenkins admin password pata karo: Jo Helm install ka NOTES section dikha tha, usmein password access karne ki instructions hoti hain. Usko follow karo, ya yeh command use karo (aksar kaam karti hai):

bash
kubectl get secret --namespace default my-jenkins-master-jenkins -o jsonpath="{.data.jenkins-admin-password}" | base64 --decode

Explanation:

  • kubectl get secret: Secret object fetch karne ka command.
  • --namespace default: Specified namespace.
  • my-jenkins-master-jenkins: Jenkins installation ka default secret naam.
  • -o jsonpath="{.data.jenkins-admin-password}": JSONPath expression jo secret ke data field se jenkins-admin-password key ki value extract karta hai.
  • | base64 --decode: Extract ki gayi value base64 encoded hoti hai, toh use decode karte hain.
  • Result: Tumhein Jenkins admin password dikhega (ek alphanumeric string). Is password ko copy kar lo! (Default username admin hota hai).

Port-forwarding karo taaki tum Jenkins ko apne browser mein dekh sako: Ek naya terminal window open karo aur usmein yeh command type karo. Isko chalta rehne do.

bash
kubectl port-forward svc/my-jenkins-master-jenkins 8080:8080

Explanation:

  • kubectl port-forward: Port forwarding command.
  • svc/my-jenkins-master-jenkins: Target Service. svc/ prefix batata hai ki hum Service ka naam de rahe hain.
  • 8080:8080: Apne computer ke port 8080 ko my-jenkins-master-jenkins Service ke andar ke port 8080 se connect karo.
  • Result: Tumhein Forwarding from 127.0.0.1:8080 -> 8080 jaisa message dikhega.

Ab, apne web browser (jaise Chrome, Firefox) mein http://localhost:8080 open karo. Tumhe Jenkins login page dikhega. admin username aur jo password copy kiya tha, usse login karo! 🎉

Helm ke Kuch Aur Cool Commands:

  • List all installed Releases:
    bash
    helm list
    Explanation: Yeh tumhare cluster mein saare installed Release (apps) ki list dikhayega, jaise my-jenkins-master.
  • Get Status of a Release:
    bash
    helm status my-jenkins-master
    Explanation: Yeh my-jenkins-master release ki detailed status dikhayega, uske banaye hue Kubernetes objects aur unki health.
  • Upgrade a Release: Agar Jenkins ka naya version aaya, toh tum use upgrade kar sakte ho, ya uski configuration change kar sakte ho:
    bash
    # Update all repos first to get latest chart versions
    helm repo update
    # Upgrade Jenkins to the latest available chart version
    helm upgrade my-jenkins-master jenkins/jenkins
    Explanation: Yeh command my-jenkins-master release ko jenkins/jenkins Chart ke latest version pe update kar dega (RollingUpdate strategy use karega).
  • Uninstall a Release: Agar Jenkins ko uninstall karna hai:
    bash
    helm uninstall my-jenkins-master
    Explanation: Yeh command my-jenkins-master release se bani hui saari Kubernetes objects (Pods, Deployments, Services, PVCs, Secrets, ConfigMaps) ko delete kar dega. Isse poora Jenkins setup clean ho jayega. Result: release "my-jenkins-master" uninstalled message dikhega.

Step 7: Cleanup - Jenkins Release aur Port Forwarding Stop Karo Jab kaam khatam ho jaye, toh Jenkins ko uninstall karo aur port forwarding stop karo.

bash
# 1. Uninstall the Jenkins Helm Release
helm uninstall my-jenkins-master

# 2. Stop the port-forwarding in the other terminal
#    Go to the terminal where `kubectl port-forward` is running and press `Ctrl+C`.

Explanation:

  • helm uninstall my-jenkins-master: This cleans up all Kubernetes objects created by the Jenkins Helm chart.

Helm apps ko Kubernetes mein install aur manage karne ka sabse asaan aur professional tareeka hai. Yeh tumhe complex configurations se bachata hai aur time save karta hai. Ab tum apps ko App Store se install karna bhi seekh gaye ho! Agle chapter mein hum brief mein dekhenge ki real Kubernetes cluster kaise banate hain! 🏗️


Chapter 18: Apna K8s Playground Banana: Kubeadm (Real Cluster Setup - Advanced Overview) 🏗️

Ab tak, humne Minikube pe Kubernetes ke baare mein bahut kuch seekha. Minikube ek single-computer playground hai, jo practice aur development ke liye perfect hai. Lekin, real world mein, bade-bade companies real Kubernetes clusters use karti hain, jismein bahut saare bade computers (jinhein "Nodes" kehte hain) hote hain jo ek saath kaam karte hain.

Real cluster banana ek professional task hai aur thoda complex hota hai, khaas kar 10 saal ke bachhe ke liye shuru mein. Isliye, main tumhe bas ek chhota sa idea dunga ki yeh kaise hota hai, aur kaunsa tool use hota hai. Tumhe is chapter ke steps ko khud try karne ki zarurat nahi hai jab tak tum bade na ho jao aur advanced concepts na seekh lo.

18.1 Kubeadm Kya Hai? (Your Cluster Builder Tool) 🛠️

  • Kubeadm: Kubeadm (pronounced: koob-ay-dee-em) ek command-line tool hai jo Kubernetes cluster ko set up karne mein help karta hai. Yeh Kubernetes components ko install aur configure karta hai Nodes pe, taaki woh ek cluster bana sakein.
  • Analogy: Socho, jaise tumhare paas bahut saare empty Lego blocks hain (computers), aur Kubeadm ek tool hai jo unhein automatically ek bada aur complex Lego castle (Kubernetes cluster) banane mein help karta hai. Yeh components ko sahi jagah pe place karta hai aur unhein connect karta hai.

18.2 Simple Steps to Build a Real Cluster (Conceptual) 🧩

Real Kubernetes cluster banane mein kuch basic steps involved hote hain:

  1. Bade Computers Ready Karo (Nodes):

    • What you need: Tumhein kuch bade computers (servers) chahiye hote hain. Yeh physical computers ho sakte hain, ya "Virtual Machines" (VMs) ho sakte hain (jaise jo tum online rent karte ho, ya Multipass jaise tools se local computer pe banate ho).
    • Operating System: Har computer pe Linux (jaise Ubuntu, CentOS) install hota hai.
    • Preparation: Har Node pe networking, firewall rules set karna, aur swap (ek type ki virtual memory) ko disable karna padta hai, kyunki Kubernetes ko iski zarurat nahi.
  2. Kubernetes Ke Parts Install Karo:

    • Container Runtime: Har computer pe ek container runtime install karte hain. Yeh woh software hai jo actual containers ko chalata hai. Popular options hain Containerd (jo aajkal preferred hai) ya Docker.
    • Kubernetes Tools: Phir, har Node pe Kubernetes ke zaruri tools install karte hain:
      • kubeadm: Cluster ko initialize aur join karne ke liye.
      • kubelet: Har Node pe chalne wala agent jo Pods ko manage karta hai.
      • kubectl: Cluster se baat karne ke liye command-line tool.
  3. Master Node Banao (Control Plane):

    • Master Node: Cluster ka brain hota hai, jahan Kubernetes ke Control Plane components chalte hain (jaise API Server, Scheduler, Controller Manager).
    • Initialize Command: Ek computer ko Master Node banane ke liye, kubeadm init command run karte hain:
      bash
      # Example command on Master Node
      sudo kubeadm init --pod-network-cidr=192.168.0.0/16 --apiserver-advertise-address=<Master_Node_IP>
      Explanation:
      • sudo kubeadm init: Initializes the Master Node.
      • --pod-network-cidr=192.168.0.0/16: Pods ke liye ek network range define karta hai.
      • --apiserver-advertise-address=<Master_Node_IP>: Master Node ka IP address jahan se doosre Nodes connect honge.
    • Join Command: kubeadm init command successfully run hone ke baad, yeh tumhe ek "join command" deta hai. Yeh command Worker Nodes use karke Master Node se connect ho sakte hain.
  4. Worker Nodes Jodo:

    • Worker Nodes: Yeh woh computers hain jahan tumhare apps (Pods) actually chalte hain.
    • Join Command Execution: Har Worker Node pe Master Node se mila hua "join command" run karte hain:
      bash
      # Example command on Worker Node
      sudo kubeadm join <Master_IP>:6443 --token <token_id> --discovery-token-ca-cert-hash sha256:<hash_value>
      Explanation:
      • sudo kubeadm join: Worker Node ko cluster mein jod deta hai.
      • <Master_IP>:6443: Master Node ka address.
      • --token <token_id>: Ek temporary password jo join karne ke liye chahiye.
      • --discovery-token-ca-cert-hash sha256:<hash_value>: Master Node ki identity verify karne ke liye security hash.
  5. Network Plugin Install Karo:

    • CNI (Container Network Interface): Kubernetes ko Pods ke beech networking manage karne ke liye ek network plugin chahiye hota hai (jise CNI plugin kehte hain).
    • Popular Plugins: Calico ya Flannel jaise plugins bahut popular hain.
    • Installation: Master Node pe isko install karte hain (usually ek YAML file apply karke):
      bash
      # Example (Calico network plugin installation)
      kubectl apply -f https://docs.projectcalico.org/manifests/calico.yaml
      Explanation:
      • kubectl apply -f: This applies the Calico network plugin's configuration to the cluster.
    • What happens: Yeh plugin Pods ke liye network rules banata hai, unhein IPs deta hai, aur ensure karta hai ki Pods aapas mein aur Nodes se baat kar sakein.

Bas! In basic steps se ek real Kubernetes cluster ban jaata hai. Ab tum Master Node se kubectl get nodes chala ke dekh sakte ho ki saare Nodes Ready hain! 🎉

Kyun Yeh Advanced Hai?

  • Networking: Real computers pe networking set karna, IP addresses, firewalls, aur network plugins ko configure karna thoda tricky ho sakta hai.
  • Troubleshooting: Installation mein errors aa sakte hain (jaise image pull nahi hui, ports blocked hain) jinhein solve karna padta hai.
  • Maintenance: Real clusters ko maintain karna padta hai, unko update karna, problems solve karna, security ka khayal rakhna.
  • Variations: Alag-alag Linux distributions ya cloud providers ke liye steps thode alag ho sakte hain.

Lekin, agar tum bade ho kar Devops Engineer banna chahte ho, toh yeh sab seekhna bahut maza aayega! Abhi ke liye, Minikube pe practice karna hi best hai. Jo scripts tumne create_real_cluster/ folder mein dekhi hain, woh bahut saare commands ko ek saath chala kar is process ko automate karti hain.

Agle aur aakhri chapter mein, hum dekhenge ki apne Kubernetes cluster ko monitor kaise karte hain, yani uski health aur performance ka khayal kaise rakhte hain! 👁️


Chapter 19: Kya Ho Raha Hai Dekhna: Monitoring 👁️

Socho, tumhara game server Kubernetes mein chal raha hai, aur bahut saare players khel rahe hain. Tumhein kaise pata chalega ki server theek se chal raha hai ya nahi? Kya woh slow ho raha hai? Kya uski memory full ho rahi hai? Ya kya usmein koi error aa raha hai? 🤔

Sirf yeh dekhna کافی nahi ki Pod Running hai. Humein aur bhi detailed jankari chahiye hoti hai. Jaise:

  • Ek Node kitni CPU use kar raha hai?
  • Ek Pod kitni Memory le raha hai?
  • Kya hamari website pe suddenly bahut zyada visitors aa gaye hain?
  • Kya koi app errors de raha hai, lekin abhi tak crash nahi hua?
  • Kya koi app bahut zyada network data send/receive kar raha hai?

Iske liye hum Monitoring Tools use karte hain. Jaise tumhari smart watch tumhare heart rate, steps, calories burn, sab kuch monitor karti hai aur graphs mein dikhati hai.

Kubernetes mein monitoring ke liye bahut saare tools hain. Hum do sabse popular tools ke baare mein briefly discuss karenge: Prometheus aur Grafana.

19.1 Prometheus: Tumhara Data Collector (Gathering Information) 📈

Prometheus kya hai?Prometheus (pronounced: proh-mee-thyoo-s) ek open-source monitoring system hai. Yeh tumhare apps (Pods), Nodes (computers), aur poore Kubernetes cluster se metrics (yani numbers aur measurements) collect karta hai.

  • Data Collector Analogy: Prometheus ek super-smart detective ki tarah hai jo cluster ke har kone se jankari collect karta hai. Woh dekhta hai ki tumhare computer mein kitna juice (CPU) use ho raha hai, kitni memory (RAM) fill ho rahi hai, kitni files download ho rahi hain.
  • How it works: Prometheus apne agents ko har app aur Node pe bhejta hai jo wahan se data scrape (collect) karte hain aur Prometheus ke central server pe bhejte hain. Is data ko Prometheus apne database mein store karta hai.

19.2 Grafana: Tumhara Smart Screen (Showing Information Visually) 📊

Grafana kya hai?Grafana (pronounced: graf-ah-na) ek open-source visualization tool hai. Yeh woh data jo Prometheus collect karta hai, usko beautiful graphs, charts, aur interactive dashboards mein dikhata hai.

  • Smart Screen Analogy: Grafana ek smart screen hai jahan tumhare detective (Prometheus) ne jo bhi data collect kiya hai, woh sab kuch ek achhe tarike se dikhta hai. Tum dekh sakte ho ki CPU usage upar ja raha hai ya neeche, memory kab zyada ho rahi hai, network traffic kitna hai, sab kuch.
  • How it works: Grafana Prometheus se data fetch karta hai aur usko easy-to-understand dashboards mein convert karta hai. Tum khud ke custom dashboards bhi bana sakte ho.

Prometheus aur Grafana ka Combination: Prometheus data collect karta hai, aur Grafana us data ko display karta hai. Yeh dono tools ek saath milkar Kubernetes clusters ki health aur performance ko monitor karne ke liye ek bahut hi powerful solution banate hain.

19.3 Installing Prometheus and Grafana with Helm 📦

Prometheus aur Grafana ko manually install karna bahut complex ho sakta hai. Lekin Helm (Chapter 17) inko easily install kar deta hai. Ek single Helm Chart, jise kube-prometheus-stack kehte hain, Prometheus, Grafana, aur bahut saare related components ko automatically deploy kar deta hai.

Step 1: Helm Repository Add Karo Pehle Prometheus Community ke Helm Charts repository ko add karo.

bash
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts

Explanation:

  • helm repo add prometheus-community ...: Adds the official Helm repository for Prometheus charts.
  • Result: prometheus-community" has been added to your repositories

Step 2: Repositories Update Karo Naye charts ki list ko download karne ke liye repo ko update karo.

bash
helm repo update

Explanation:

  • helm repo update: Fetches the latest chart information from all added repositories.
  • Result: Successfully got an update from the "prometheus-community" chart repository

Step 3: Prometheus aur Grafana Ko Install Karo (using kube-prometheus-stack Chart) Ab, kube-prometheus-stack Chart ko install karte hain. Yeh Helm Chart ek hi baar mein Prometheus, Grafana, aur saare zaruri components (jaise node-exporter jo Node metrics collect karta hai, kube-state-metrics jo Kubernetes objects ke metrics collect karta hai) ko install kar dega.

bash
helm install my-cluster-monitor prometheus-community/kube-prometheus-stack

Explanation:

  • helm install my-cluster-monitor: Installs the chart and names this Release my-cluster-monitor.
  • prometheus-community/kube-prometheus-stack: The chart to install.
  • What happens: Helm is chart ko deploy karega, aur yeh cluster mein bahut saare Deployments, Services, Pods, ConfigMaps, Secrets, aur other Kubernetes objects create karega Prometheus, Grafana, aur unke dependencies ke liye. Ismein thoda time lag sakta hai, be patient!
  • Result: Installation summary aur NOTES section dikhega. NOTES section mein Grafana ko access karne ke liye instructions hongi (default username: admin, password: prom-operator).

Step 4: Check Pods Status Verify karo ki saare Pods Running hain. Yeh pods alag-alag namespaces mein honge (jaise default ya kube-prometheus-stack jo chart ne banaya hoga).

bash
kubectl get pods --all-namespaces -w

Explanation:

  • kubectl get pods --all-namespaces -w: Lists all Pods across all namespaces and watches for changes.
  • Result: Tumhein my-cluster-monitor-kube-prometheus-stack-prometheus-0, my-cluster-monitor-kube-prometheus-stack-grafana-, my-cluster-monitor-kube-prometheus-stack-kube-proxy-, my-cluster-monitor-kube-prometheus-stack-kube-state-metrics- jaise Pods Running dikhne chahiye.

Step 5: Grafana Dashboard Access Karo Grafana web UI ko access karne ke liye, tumhe port-forwarding karna padega.

Pehle, Grafana Service ka naam pata karo. Usually yeh Release name ke saath Grafana Service ka naam hota hai.

bash
kubectl get svc -l app.kubernetes.io/name=grafana

Example Result: my-cluster-monitor-grafana jaisa naam milega. (If your chart deployed in default namespace).

Ek naya terminal window open karo aur usmein Grafana Service ke liye port forwarding karo. Isko chalta rehne do.

bash
kubectl port-forward svc/<grafana-service-name> 3000:3000
# Example: kubectl port-forward svc/my-cluster-monitor-grafana 3000:3000

Explanation:

  • kubectl port-forward: Port forwarding command.
  • svc/<grafana-service-name>: Target Grafana Service.
  • 3000:3000: Apne computer ke port 3000 ko Grafana app ke andar ke port 3000 se connect karo.
  • Result: Tumhein Forwarding from 127.0.0.1:3000 -> 3000 jaisa message dikhega.

Ab, apne web browser mein http://localhost:3000 open karo. Tumhe Grafana login page dikhega.

  • Username: admin
  • Password: prom-operator (yeh default password hai, jo Helm chart ke NOTES mein bhi mention hota hai).

Login karne ke baad, tumko Grafana Dashboard dikhega! 🎉

Step 6: Grafana Mein Dashboards Explore Karo Grafana mein login karne ke baad, tumhe left side pe Dashboards icon (squares jaisa) dikhega. Uspar click karo, phir Manage pe click karo.

Tumhein bahut saare ready-made dashboards milenge, jaise:

  • Kubernetes / Compute Resources / Cluster
  • Kubernetes / Compute Resources / Namespace (Pods)
  • Kubernetes / Kubelet
  • Node Exporter / Use (Agar node-exporter chal raha hai)

Kisi bhi dashboard pe click karo. Tumhein apne Nodes aur Pods ka CPU, Memory, Disk, Network usage graphs mein dikhega! 🤩 Tum date range bhi change kar sakte ho (top right corner mein).

Example of what you might see:

  • CPU Usage: Blue lines dikhengi jo batayengi ki Node ya Pod kitni CPU use kar raha hai.
  • Memory Usage: Graphs dikhenge ki Node ya Pod kitni Memory use kar raha hai.
  • Network I/O: Kitna data send aur receive ho raha hai.

Yeh sab real-time mein dikhega, jisse tum apne cluster ki performance aur health ko track kar sakte ho.

Step 7: Cleanup - Prometheus/Grafana Release aur Port Forwarding Stop Karo Jab kaam khatam ho jaye, toh Grafana release ko uninstall karo aur port forwarding stop karo.

bash
# 1. Uninstall the Helm Release for Prometheus and Grafana
helm uninstall my-cluster-monitor

# 2. Stop the port-forwarding in the other terminal
#    Go to the terminal where `kubectl port-forward` is running and press `Ctrl+C`.

Explanation:

  • helm uninstall my-cluster-monitor: This cleans up all Kubernetes objects created by the kube-prometheus-stack Helm chart.

Monitoring tools Kubernetes ke liye bahut zaroori hain. Yeh tumhe apne apps aur cluster ki sehat aur performance ka hamesha khayal rakhne mein help karte hain, taaki tum problems ko chalu hone se pehle hi solve kar sako.

Congratulations! Tumne Kubernetes ke bahut saare complex topics ko simple tareeke se samajh liya hai, aur har step ko khud karke dekha hai. Ab tum sach mein ek future tech explorer ban gaye ho! 🎉


Glossary: Kubernetes Words jo Seekhe! 📖

Yahan kuch important words hain jo humne is ebook mein seekhe, simple Hinglish explanations aur fun analogies ke saath. Yeh tumhare liye ek mini-dictionary hai!

  • Kubernetes (K8s): Tumhara super-smart toy organizer. Ek system jo computer programs (apps/containers) ko automatically manage, scale, aur theek karta hai, taaki woh hamesha available rahen. (Analogy: Ek bade playgroup ka smart manager).
  • Container: Ek chhota sa packet jismein tumhara app aur usko chalane ke liye saari cheezein (files, instructions) packed hoti hain. Yeh app ko kahin bhi chalane mein help karta hai. (Analogy: Plastic toy box).
  • Minikube: Tumhara apna chhota sa Kubernetes playground jo tumhare computer pe hi chalta hai. (Analogy: Tumhare computer ke andar ka video game console).
  • Kubectl: Tumhari magic wand. Ek tool jo tumhare commands ko Kubernetes cluster tak pahunchata hai. (Analogy: TV ka remote control).
  • Pod: Tumhare app ka sabse chhota ghar Kubernetes mein. Ek ya ek se zyada containers ko apne andar rakhta hai. Har Pod ka apna unique IP hota hai. (Analogy: Ek chhota sa house for your app).
  • Imperative Way: Seedhe commands dekar apps chalana. Quick aur direct. (Analogy: Seedhe bolo "Ball feko!").
  • Declarative Way: YAML file mein plan likhkar apps chalana. Organized aur repeatable. (Analogy: Ek detailed plan ya list banana).
  • YAML (YAML Ain't Markup Language): Ek easy language jismein hum Kubernetes objects ke plans likhte hain. Spaces ka dhyaan rakhna zaruri hai.
  • Sidecar Pattern: Ek main container ke saath uska helper container ek hi Pod mein chalana. Dono shared resources use karte hain. (Analogy: Tumhara helpful chhota bhai).
  • Volume: Storage area jahan apps data save karte hain ya share karte hain.
  • EmptyDir Volume: Ek temporary storage area jo Pod ke andar banta hai aur Pod delete hone par gayab ho jaata hai. Containers ke beech data share karne ke liye best. (Analogy: Khali paper jo drawing ke baad throw kar diya).
  • HostPath Volume: Node (computer) ke actual local storage (folder) ko Pod ke andar mount karna.
  • Port Forwarding: Ek temporary "tunnel" banana jo tumhare computer ke port ko Pod ke andar chal rahe app ke port se jodta hai. (Analogy: Walkie-talkie channel).
  • Deployment: Apps ki factory. Kubernetes object jo Pods ki multiple copies ko manage, scale, aur update karta hai, taaki app hamesha available rahe. (Analogy: Toy factory jo cars banati hai).
  • ReplicaSet: Deployment ke pichhe ka chhota manager jo Pods ki desired count maintain karta hai. (Analogy: Factory ke andar ka production supervisor).
  • Rollout: App ka naya version smoothly deploy karna.
  • Rollback: App ko purane (working) version pe wapas le jaana, agar naye version mein problem ho. (Analogy: Time machine se pichhe jaana).
  • Recreate Strategy: Rollout ka tareeka jismein purane Pods delete hote hain, phir naye banate hain. Brief downtime ho sakta hai. (Analogy: Saare purane kapde utar ke ekdum se naye pehenna).
  • RollingUpdate Strategy: Rollout ka tareeka jismein Pods ek-ek karke update hote hain, bina app ko band kiye (zero downtime). Yeh default aur recommended hai. (Analogy: Ek-ek karke cars ko repair karwana, baaki cars road pe chalti rahengi).
  • Service: Apps ki communication system. Ek single, stable address jo incoming traffic ko Pods ke group tak bhejta hai. (Analogy: Post Office for your apps).
  • ClusterIP Service: Sirf cluster ke andar se access hone wali Service. Apps ko aapas mein baat karne ke liye. (Analogy: Ghar ka intercom).
  • NodePort Service: Har Node ke ek specific port pe access hone wali Service. Cluster ke bahar se access ke liye (thoda indirect). (Analogy: Ghar ke bahar ka public phone booth).
  • LoadBalancer Service: Cloud provider ke Load Balancer se external public IP dene wali Service. Public apps ke liye sabse best. (Analogy: Tumhari website ka apna public phone number).
  • Liveness Probe: App zinda hai aur chal raha hai (hang toh nahi ho gaya) yeh check karne wala mechanism. Dead app ko restart karta hai. (Analogy: Doctor's checkup, pulse check).
  • Readiness Probe: App requests handle karne ke liye ready hai ya nahi (fully loaded hai ya nahi) yeh check karne wala mechanism. Not ready app ko traffic nahi bhejta. (Analogy: Traffic light, Green light matlab ready to go).
  • Secret: Sensitive data (passwords, API keys) store karne wala Kubernetes object. Data base64 encoded hota hai. (Analogy: Tumhara secret locker).
  • ConfigMap: Non-sensitive configuration data (normal settings) store karne wala Kubernetes object. Data plain text mein store hota hai. (Analogy: Tumhari important notepad).
  • Job: Ek baar chalne wala task. Jab tak kaam successfully complete na ho, Pods ko chalaata hai. (Analogy: One-time homework assignment).
  • CronJob: Scheduled task. Jobs ko specific time pe (ya har interval pe) automatically chalaata hai. (Analogy: Tumhara daily alarm).
  • DaemonSet: Kubernetes object jo yeh ensure karta hai ki uska app (Pod) har Node (computer) par chal raha ho. (Analogy: Antivirus on every PC in the school).
  • Persistent Volume (PV): Cluster ke bahar ka actual physical storage area. Data permanent rehta hai. (Analogy: Magic hard drive ya bada storage room).
  • Persistent Volume Claim (PVC): Pod ki storage request. Ek form jisse app storage maangta hai. (Analogy: Storage room se space maangne ka request form).
  • StatefulSet: Apps ki copies ko manage karta hai jinhein stable, unique names aur unique persistent storage ki zaroorat hoti hai. Databases jaise apps ke liye. (Analogy: Named pets with their own beds).
  • Headless Service: StatefulSet ke liye ek special Service jiska apna IP nahi hota, balki woh Pods ke seedha IPs resolve karti hai.
  • Node Affinity: Pods ko batata hai ki woh kis type ke Node par chalna pasand karengi. (Analogy: "Sirf yahan baitho!").
  • Taint: Node par lagaya jaata hai, jo Pods ko us Node se repel (dur dhakelna) karta hai. (Analogy: "Yahan mat aana!" sign).
  • Toleration: Pod par lagaya jaata hai, jo use specific Taint ko "tolerate" (bardasht) karne ki permission deta hai, taaki woh us tainted Node pe chal sake.
  • Ingress: Cluster ke bahar se Services tak traffic manage aur route karne wala object. Single entry point deta hai. (Analogy: Theme Park ka main entrance gate).
  • Ingress Controller: Ingress rules ko implement karne wala app (e.g., Nginx). (Analogy: Smart gatekeeper).
  • Hosts File: Tumhare computer ki ek choti phonebook jahan tum domain names ko IP addresses se manually map kar sakte ho.
  • Helm: Kubernetes ke liye App Store (package manager). Apps ko "Charts" ke roop mein install karta hai. (Analogy: Google Play Store for Kubernetes apps).
  • Chart: Helm mein ek app ko deploy karne ke liye saari zaruri files ka packet. (Analogy: Ready-made Lego set box).
  • Repository: Helm Charts store karne ki online jagah.
  • Release: Kubernetes mein install kiya gaya ek Helm Chart. (Analogy: Ek game jo tumne phone pe install kiya).
  • Kubeadm: Tool jo real Kubernetes cluster set up karne mein help karta hai. (Analogy: Your Cluster Builder Tool).
  • Prometheus: Data collector. Cluster se performance metrics (CPU, Memory, Network usage) collect karta hai. (Analogy: Super-smart detective).
  • Grafana: Visualization tool. Prometheus ke data ko beautiful graphs aur dashboards mein dikhata hai. (Analogy: Tumhara smart screen ya scoreboard).

Summary: Kya Seekha aur Aage Kya Karein? 🚀

Wah! 🎉 Tumne Kubernetes ki amazing duniya mein ek bahut hi badhiya aur deep tour kiya hai! Tumne sirf concepts nahi seekhe, balki har step ko khud karke bhi dekha hai. Ab tum sach mein ek Kubernetes Explorer ban gaye ho!

Kya Seekha Tumne is Ebook se?

  • Containers aur Kubernetes ka Role: Samjha ki containers kaise apps ko pack karte hain aur Kubernetes unhein kaise manage karta hai.
  • Basic Kubernetes Objects: Pods (apps ke ghar), Deployments (apps ki factories), Services (communication network), aur unhein kubectl commands aur YAML files se kaise banate hain.
  • Advanced Features: Liveness/Readiness Probes (health checks), Secrets/ConfigMaps (settings management), Jobs/CronJobs (automated tasks), DaemonSets (apps on every Node), Persistent Volumes (permanent storage), aur StatefulSets (stable names aur data).
  • Networking: Ingress (external access) aur Service types ko kaise use karte hain.
  • Management Tools: Dashboard (visual overview) aur Helm (app store for K8s) ko kaise use karte hain.
  • Monitoring: Prometheus aur Grafana se cluster ki health aur performance kaise dekhte hain.
  • Hands-on Experience: Har concept ko real-time mein Minikube pe apply karke dekha, har command ko chalaya, aur har output ko samjha.

Ab Aage Kya Karein? (Your Next Steps!) Yeh toh bas shuruat hai! Kubernetes ek bahut badi aur interesting duniya hai, aur tumne abhi uski foundations seekh li hain.

  1. Practice, Practice, Practice: Jo bhi concepts tumne yahan seekhe hain, unhein minikube pe khud karke dekho, baar-baar. Jab tak tum bina kisi help ke har step ko confidently na kar pao. Commands ko type karo, YAML files banao, settings change karo, aur dekho kya hota hai.
  2. Experiment Karo: Different settings try karo. replicas change karo, image version badlo. maxUnavailable aur maxSurge ki values badal ke dekho RollingUpdate mein kya fark aata hai. Apni khud ki choti YAML files banao.
  3. Explore More:
    • Kubectl Cheatsheet: KubernetesCommandCheatSheet.md file mein aur bhi bahut saari commands hain. Unhein explore karo.
    • Helm Cheatsheet: HelmCheatsheet.md file bhi bahut useful hai.
    • Official Docs: Jab tum comfortable ho jao, toh Kubernetes ki official documentation (kubernetes.io) pe jaakar thoda aur gehraai mein concepts padho. Shuru mein mushkil lagegi, lekin ab tumhare paas basic understanding hai.
  4. Bade Projects Dekho: Apne bade bhai/behan ya teacher se poochho ki real companies Kubernetes ko kaise use karti hain, ya online case studies dekho.
  5. Build Your Own Simple App: Agar tumhe coding aati hai (Python, Node.js, etc.), toh apna ek chhota sa web app banao, usko Docker container mein pack karo, aur phir use Kubernetes pe deploy karo (Deployment, Service, Ingress sab use karke). Yeh tumhare liye sabse best learning experience hoga!
  6. Cloud Kubernetes: Jab tum confident ho jao, toh kisi cloud provider (Google Cloud, AWS, Azure) pe free tier account bana kar wahan apna chhota sa managed Kubernetes cluster (GKE, EKS, AKS) try karo. Wahan bahut saari cheezein automatic hoti hain!

Yaad rakhna, technology seekhna ek adventure hai, aur har naya concept ek naya treasure hai. Tumne abhi ek bahut bada treasure box open kiya hai. Keep exploring, keep learning, aur aise hi amazing cheezein banate raho!

All the best, mere future tech genius! Tum kar sakte ho! 😊🚀💡