<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Prabhu Jayakumar on Medium]]></title>
        <description><![CDATA[Stories by Prabhu Jayakumar on Medium]]></description>
        <link>https://medium.com/@prabhujayakumar?source=rss-6a2512a612e3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5xqC44PhGaZda9oR.</url>
            <title>Stories by Prabhu Jayakumar on Medium</title>
            <link>https://medium.com/@prabhujayakumar?source=rss-6a2512a612e3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:54:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prabhujayakumar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Securing AI on Kubernetes: Your Pods Are Gossiping Behind Your Back]]></title>
            <link>https://prabhujayakumar.medium.com/securing-ai-on-kubernetes-your-pods-are-gossiping-behind-your-back-2d930c05eae0?source=rss-6a2512a612e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d930c05eae0</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[kubernetes-security]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kubernetes-network-policy]]></category>
            <dc:creator><![CDATA[Prabhu Jayakumar]]></dc:creator>
            <pubDate>Fri, 29 May 2026 19:22:05 GMT</pubDate>
            <atom:updated>2026-05-29T19:22:05.488Z</atom:updated>
            <content:encoded><![CDATA[<p>Originally published <a href="https://prabhujayakumar.dev/blog/securing-ai-k8s-network-policy/">here</a>.</p><p>Every team is shipping AI on Kubernetes now — RAG pipelines, fine-tuning jobs, model serving at scale. But while everyone’s racing to deploy, almost nobody is asking: <em>“Who can talk to my vector database?”</em> In a world where your embeddings ARE your competitive moat, network-level security isn’t optional — it’s existential.</p><p>Throughout this post, we’ll use a typical three-tier RAG application as our running example — a <strong>Chat UI</strong> (Next.js) where users submit prompts, a <strong>RAG API</strong> (FastAPI) that retrieves context from embeddings and calls an external LLM provider like OpenAI, and a <strong>Vector DB</strong> (Qdrant) that stores your proprietary embeddings. It’s a stack you’ll find in production at countless AI startups — and it’s wide open by default.</p><p>That <strong>vector database</strong> storing your proprietary embeddings? It can freely call your <strong>public-facing chat interface</strong>. Nobody configured that. Nobody asked for that. It just happens — because in Kubernetes, the default networking model has the security posture of a coffee shop WiFi.</p><p>Every pod can talk to every other pod. Every namespace. Every port. That AI inference pipeline you spent weeks designing? Kubernetes treats it as a polite suggestion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*ZJ8vvNUmue4cFH2X.png" /></figure><p>Your architecture diagram has clean, directional arrows. Your actual network? It’s a group chat where everyone can DM everyone — including your vector database leaking proprietary embeddings to your public-facing chat endpoint.</p><p>Let’s fix that.</p><h3>The One Rule That Changes Everything</h3><p>Here’s the thing about Kubernetes NetworkPolicy that trips up even experienced engineers: it doesn’t work like a traditional firewall. There’s no “deny” rule. There’s no ordering. There’s just one rule:</p><blockquote><strong>The moment a pod is selected by ANY NetworkPolicy, all traffic not explicitly allowed becomes denied.</strong></blockquote><p>No NetworkPolicy on a pod? Wide open. Apply <em>one</em> policy? Immediate lockdown. Only traffic matching your rules gets through. Everything else hits a wall.</p><p>It’s like living in a building with no front door versus one with a bouncer. There’s no middle ground — it’s either “anyone walks in” or “name on the list, or you’re not getting in.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*piaUSK9RqGyoqn36.png" /></figure><p>This is powerful. And it’s also where you’ll shoot yourself in the foot if you’re not careful.</p><h3>Locking Down a Real App, One Door at a Time</h3><p>Theory is nice. Let’s break things and fix them with our RAG stack. The goal:</p><pre>What we WANT:        Chat UI ───► RAG API ───► Vector DB<br>                        (one-way chain — prompts flow in, context flows back)</pre><pre>   What we HAVE:        Chat UI ◄──► RAG API ◄──► Vector DB ◄──► Chat UI<br>                        (everyone talks to everyone, your embeddings are exposed)</pre><p>Three policies. Three YAML files. That’s all it takes to go from “anyone can exfiltrate your training data” to “zero-trust RAG pipeline.”</p><h3>Step 1 — Shut everything down</h3><pre>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: deny-all<br>  namespace: ai-platform<br>spec:<br>  podSelector: {}      # every pod in the namespace<br>  policyTypes:<br>  - Ingress            # + no ingress rules = nothing gets in</pre><p>Two things are doing the heavy lifting here. podSelector: {} — the empty selector — targets <strong>every</strong> pod in the namespace. And policyTypes: [Ingress] without any ingress rules is an explicit “deny all.” Run the connectivity test now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/0*sHD--Di1vXoKBcAZ.png" /></figure><p>Good. Everything’s broken. That’s exactly where we want to start.</p><h3>Step 2 — Open exactly two doors</h3><p>Now we surgically allow <strong>only</strong> the paths that should exist.</p><pre># Let Chat UI call RAG API (and nothing else)<br>spec:<br>  podSelector:                    # WHO receives traffic:<br>    matchLabels:                  #   → the RAG API<br>      app: rag-api<br>  ingress:<br>  - from:<br>    - podSelector:                # WHO sends traffic:<br>        matchLabels:              #   → the chat UI<br>          app: chat-ui<br>    ports:<br>    - port: 8000                  # on the FastAPI port only</pre><pre># Let RAG API call Vector DB (and nothing else)<br>spec:<br>  podSelector:                    # WHO receives traffic:<br>    matchLabels:                  #   → the vector database<br>      app: vector-db<br>  ingress:<br>  - from:<br>    - podSelector:                # WHO sends traffic:<br>        matchLabels:              #   → the RAG API<br>          app: rag-api<br>    ports:<br>    - port: 6333                  # Qdrant REST API port<br>    - port: 6334                  # Qdrant gRPC port (if using gRPC client)</pre><p>The YAML reads like a sentence: <em>“The RAG API accepts ingress from the chat UI on port 8000.”</em> That’s it. Nothing about the vector DB reaching the UI, nothing about random pods querying your embeddings. Every path not mentioned is dead.</p><blockquote><strong>Note:</strong> NetworkPolicy controls new connections, not return traffic. When Chat UI calls RAG API, the HTTP response flows back over the same established TCP connection — that’s allowed. What’s blocked is RAG API initiating a new connection to Chat UI.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*GotiySMDRZ1a3L0P.png" /></figure><p>Three policy files. Your architecture diagram and your actual network now match. That’s the whole point of NetworkPolicy — making reality agree with the whiteboard.</p><h3>Step 3 — Crossing the namespace border</h3><p>Your ML ops stack (model monitoring, drift detection, evaluation pipelines) lives in a separate namespace. It needs to query your RAG API for health checks and metrics. How do you let traffic cross namespace boundaries without opening the floodgates?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*oVb5wrVLE0l1TYs2.png" /></figure><p>The answer: namespaceSelector. It’s like a VIP pass, but for entire namespaces.</p><pre>spec:<br>  podSelector: {}                  # all pods in ai-platform<br>  ingress:<br>  - from:<br>    - namespaceSelector:<br>        matchLabels:<br>          purpose: ml-ops          # ← the namespace itself needs this label</pre><p>The namespace must be labeled — that’s your access control surface:</p><pre>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: ml-ops<br>  labels:<br>    purpose: ml-ops                # no label, no entry</pre><p>This reads: <em>“Any pod from any namespace labeled </em><em>purpose: ml-ops can reach any pod in ai-platform.&quot;</em> Not any pod from anywhere. Not any namespace. Just the one with the right badge.</p><h3>8 Policies That Look Identical and Do Completely Different Things</h3><p>Here’s where NetworkPolicy goes from “I get it” to “I need to lie down.”</p><p>I’m about to show you 8 policy snippets. Some differ by a single YAML line. Some differ by <em>the presence or absence of a dash</em>. The behavioral differences are enormous. This is the section you’ll wish you’d read before that 2 AM incident.</p><h3>The Scoreboard</h3><p>Before we dive into each, here’s what they all do. Stare at this table. Notice how rows 5 and 6 — which look almost identical — produce the same result for the wrong reasons. Notice how row 3 and 4 differ by one word.</p><p>#NameThe from SpecSame NSCross NSExternal1Allow Allingress: [{}]✅✅✅2Deny All<em>(no ingress key)</em>❌❌❌3Same NS OnlypodSelector: {}✅❌❌4Cluster InternalnamespaceSelector: {}✅✅❌5AND Trap ⚠️podSelector: {} + namespaceSelector: {} <em>(same item)</em>✅✅❌6OR LogicpodSelector: {} + namespaceSelector: {} <em>(separate items)</em>✅✅❌7Specific NSnamespaceSelector: {matchLabels}❌✅ ml-ops only❌8Specific Pod+NSnamespaceSelector + podSelector <em>(same item, with labels)</em>❌✅ model-monitor only❌</p><p>Now let’s look at <em>why</em>.</p><h3>🔍 Spot the Difference #1: Allow All vs. Deny All</h3><p>These two policies are identical except for <strong>one line</strong>. The result is the exact opposite.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*N1AyIIYGEgOq4ZS-.png" /></figure><p>ingress: [{}] is a rule that says “from: anywhere, on: any port.” It’s a blank check. No ingress key at all means “there are zero rules” — and zero rules means zero allowed traffic.</p><blockquote><strong>The mental model:</strong> - {} is a guest list that says “everybody.” No list at all means nobody gets in.</blockquote><h3>🔍 Spot the Difference #2: podSelector vs. namespaceSelector</h3><p>One word changes the blast radius from “this room” to “the entire building.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*sRz79QuFTTfpzumS.png" /></figure><p>podSelector: {} means “all pods” — but implicitly scoped to the policy’s own namespace. namespaceSelector: {} means “all namespaces” — which includes every pod in the cluster.</p><p>Same shape. Same empty {}. Wildly different doors you just opened.</p><h3>🔍 Spot the Difference #3: AND vs. OR — The Hyphen Trap</h3><p><strong>This is the single most dangerous subtlety in all of Kubernetes networking.</strong> Two policies that look <em>nearly identical</em> — but one has an extra hyphen, and that hyphen decides whether your security posture is “surgical” or “wide open.”</p><pre>AND LOGIC (one dash)                OR LOGIC (two dashes)<br>  ─────────────────────               ─────────────────────</pre><pre>  ingress:                            ingress:<br>  - from:                             - from:<br>    - podSelector: {}                   - podSelector: {}<br>      namespaceSelector: {}             - namespaceSelector: {}<br>                                        ▲<br>                                        │<br>                                   extra dash</pre><p><strong>One YAML array item</strong> = one rule where both conditions must match (AND). <strong>Two YAML array items</strong> = two independent rules where either can match (OR).</p><p>When both selectors are {} (empty), it’s a trick question — both produce the same result because “all pods AND all namespaces” equals “all pods OR all namespaces.” But add real labels, and the trap snaps shut:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*OOWmPttYlxfHkMp4.png" /></figure><p>Read that again. The AND version allows exactly <strong>one pod</strong> (model-monitor, in ml-ops). The OR version allows <strong>every pod in the ml-ops namespace</strong> plus <strong>every model-monitor pod in every namespace</strong>. One extra - in your YAML, and you’ve opened a door you didn’t know existed.</p><blockquote><strong>The rule to memorize:</strong></blockquote><blockquote>One - = AND. Both must match. Two - = OR. Either can match.</blockquote><blockquote>A single hyphen changes your entire security posture.</blockquote><h3>🔍 Spot the Difference #4: Namespace vs. Specific Pod</h3><p>The final two scenarios show the spectrum from “everyone in this department” to “only this one person.”</p><pre>SPECIFIC NAMESPACE                  SPECIFIC POD IN NAMESPACE<br>  ─────────────────────               ─────────────────────</pre><pre>  - namespaceSelector:                - namespaceSelector:<br>      matchLabels:                        matchLabels:<br>        name: ml-ops                        name: ml-ops<br>                                        podSelector:           ◄── added<br>                                          matchLabels:<br>                                            app: model-monitor</pre><pre>  Allowed:                            Allowed:<br>  ✅ model-monitor (ml-ops)           ✅ model-monitor (ml-ops)<br>  ✅ drift-detector (ml-ops)          ❌ drift-detector (ml-ops)<br>  ❌ pods from other ns              ❌ pods from other ns</pre><p>Scenario 7 is a namespace-level badge: “anyone from ml-ops can enter.” Scenario 8 adds a photo ID check: “only model-monitor from ml-ops.” Both use the same AND logic from the trap above — but here it’s intentional. The namespaceSelector and podSelector sit in the same from entry, so both must match.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*aj9gA123cHIOdnSV.png" /></figure><p>This is AND logic <em>used right</em> — a precision instrument, not a footgun.</p><h3>The Trap Nobody Warns You About: Egress and DNS</h3><p>You’ve locked down ingress. You’re feeling smart. So you think: <em>“Let me lock down egress too — deny all outbound traffic.”</em></p><pre>spec:<br>  podSelector: {}<br>  policyTypes:<br>  - Egress<br>  # no egress rules = pods can&#39;t call anything</pre><p>Congratulations. Your pods are now so secure they can’t resolve hostnames.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*NRqprBylwwui7wY3.png" /></figure><p>DNS runs on UDP/TCP port 53, served by kube-dns pods in kube-system. Deny all egress? You just cut off DNS. Every service name becomes unresolvable. Your pods aren’t just isolated — they’re blind.</p><p><strong>The fix — always pair egress deny with a DNS escape hatch:</strong></p><pre>spec:<br>  podSelector: {}<br>  policyTypes:<br>  - Egress<br>  egress:<br>  - to:<br>    - namespaceSelector:<br>        matchLabels:<br>          kubernetes.io/metadata.name: kube-system<br>      podSelector:<br>        matchLabels:<br>          k8s-app: kube-dns<br>    ports:<br>    - protocol: UDP<br>      port: 53<br>    - protocol: TCP<br>      port: 53</pre><blockquote><strong>Burn this into memory:</strong> Every egress deny needs a DNS allow. No exceptions. Ever. Put it in your template. Put it in your CI. Tattoo it on your forearm.</blockquote><h3>The Mental Model You Actually Need</h3><p>Forget everything else. If you internalize one diagram from this entire post, make it this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*2pLpHC0Uspffw5gF.png" /></figure><p>That last point is subtle and important: you can’t write a “deny” policy that overrides an “allow” from another policy. Policies are additive. If Policy A allows traffic from namespace X, and Policy B tries to be more restrictive, Policy A still wins. The union of all rules is what gets enforced.</p><h3>The Cheat Sheet</h3><p>Tear this out. Pin it next to your terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*iPaEfA7jCg4DGpaU.png" /></figure><h3>Break Things Yourself</h3><p>Here’s a complete lab you can run on your laptop in under five minutes using <a href="https://kind.sigs.k8s.io/">Kind</a>, <a href="https://kubernetes.io/docs/tasks/tools/">kubectl</a>, and <a href="https://docs.docker.com/get-docker/">Docker</a>:</p><p><a href="https://github.com/prabhu43/experiments/tree/main/k8s-network-policy">https://github.com/prabhu43/experiments/tree/main/k8s-network-policy</a></p><h3>One Last Thing</h3><p>Kubernetes networking is opt-in security. Nobody forces you to write NetworkPolicies. Your cluster will run perfectly fine without them — in the same way your AI platform works perfectly fine without access controls.</p><p>Until someone exfiltrates your embeddings, poisons your training pipeline, or routes prompts through a compromised pod.</p><p>The YAML is few lines only. The blast radius of not writing it is your entire model stack. That’s the trade-off, and it’s not even close.</p><p>Ship the policy before you ship the model.</p><p><strong>Tags:</strong> kubernetes network-policy ai-security zero-trust cloud-native mlops devsecops container-security llm-infrastructure</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d930c05eae0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[QuakePulse: Building a Real-Time Earthquake Dashboard with Aiven’s Free Tier]]></title>
            <link>https://prabhujayakumar.medium.com/quakepulse-building-a-real-time-earthquake-dashboard-with-aivens-free-tier-53df5f970184?source=rss-6a2512a612e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/53df5f970184</guid>
            <category><![CDATA[earthquake]]></category>
            <category><![CDATA[aiven]]></category>
            <dc:creator><![CDATA[Prabhu Jayakumar]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 17:01:52 GMT</pubDate>
            <atom:updated>2026-03-31T18:00:59.994Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>#AivenFreeTier</strong></p><p><em>Every minute, somewhere on Earth, the ground shakes. Most of these tremors go unnoticed — small ripples deep beneath the ocean floor, micro-quakes in remote mountain ranges, aftershocks that only seismographs detect. But every so often, the Earth reminds us that we live on a restless planet. When it does, seconds matter.</em></p><p><em>QuakePulse is my attempt to turn raw seismic data into something anyone can see, understand, and react to — in real time.</em></p><p><strong>Live Demo:</strong> <a href="https://quakepulse.onrender.com/">https://quakepulse.onrender.com</a></p><h3>Why I Built This</h3><p>I’ve always been fascinated by how fast seismic data travels — from a fault rupture deep underground to a USGS data feed in under a minute. But that data sits in a JSON endpoint. Nobody stares at JSON.</p><p>I wanted to build something that makes the invisible visible: a live map where you can <em>watch</em> the Earth shake. Not a static chart updated once a day, but a truly streaming system where a magnitude 5.0 event in Chile appears on your screen seconds after the USGS records it.</p><p>At the same time, I wanted to learn streaming architecture properly — not by reading about it, but by building a real pipeline with real data flowing through it. When I saw Aiven’s free tier offering Kafka, PostgreSQL, and Valkey together, it clicked. That’s not just a database or a cache — that’s a <em>complete data platform</em>. I could build the entire streaming pipeline end-to-end without any infrastructure headaches.</p><h3>The Architecture: Three Services, One Pipeline</h3><p>The beauty of QuakePulse is that all three Aiven services play distinct, essential roles. None of them are bolted on for show — remove any one, and the system breaks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K87zuav2PnHb8pJBVuwxew.png" /></figure><p>Here’s how data flows:</p><ol><li><strong>A Kafka Producer</strong> polls the <a href="https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson">USGS earthquake feed</a> every 60 seconds, deduplicates events by ID, and publishes them to three Kafka topics: raw-quakes (everything), significant-quakes (M4.5+), and quake-alerts (M6.0+ or tsunami warnings).</li><li><strong>A Kafka Consumer</strong> reads from all three topics in parallel. For each earthquake, it performs a PostgreSQL <strong>upsert</strong> (for durable storage and analytics), caches it in a Valkey <strong>sorted set</strong> (for sub-second API responses), and <strong>publishes</strong> to a Valkey pub/sub channel for live push.</li><li><strong>The WebSocket handler</strong> subscribes to Valkey’s live-quakes pub/sub channel and fans out new events to every connected browser — no polling, no delay.</li><li><strong>The frontend</strong> renders earthquakes as color-coded circles on a dark-themed Leaflet.js map, with pulse animations for new arrivals and a Chart.js analytics panel.</li></ol><h3>Why These Three Services? The Architecture Decisions</h3><h3>Kafka: The Backbone You Don’t See</h3><p>I could have skipped Kafka entirely — just poll USGS, write to PostgreSQL, done. But that would be a toy.</p><p>Kafka gives me <strong>decoupling</strong>. The producer doesn’t know or care what happens downstream. The consumer can crash, restart, and pick up exactly where it left off thanks to consumer group offsets. I can add new consumers later (email alerts, a Slack bot, a machine learning anomaly detector) without touching a single line of producer code.</p><p>I used three topics to implement <strong>priority routing</strong> at the infrastructure level:</p><ul><li>raw-quakes — every event, for completeness</li><li>significant-quakes — M4.5+ events, for dashboards that only care about notable activity</li><li>quake-alerts — M6.0+ or tsunami warnings, for critical notifications</li></ul><p>Aiven’s free tier gives you 5 topics. I used 3 — enough to demonstrate the pattern without forcing unnecessary topics.</p><p>The Kafka producer also implements a <strong>circuit breaker</strong>: after 5 consecutive failures, it stops attempting sends for 60 seconds, preventing a cascade of timeout errors if the broker is temporarily unreachable.</p><h3>PostgreSQL: The Source of Truth</h3><p>Every earthquake that flows through the pipeline gets upserted into PostgreSQL using ON CONFLICT DO UPDATE. This means:</p><ul><li>First time we see an earthquake ID → INSERT</li><li>USGS revises the magnitude or adds felt reports → UPDATE the existing row</li></ul><p>PostgreSQL is the durable analytical store. The REST API queries it for historical data — earthquakes by time range, magnitude filterts, bounding box queries (for what’s visible on the map viewport), and aggregated statistics like hourly counts and magnitude distributions.</p><p>I deliberately chose <strong>not</strong> to use PostGIS. Bounding box queries with simple latitude BETWEEN ? AND ? comparisons are fast enough for this use case, and it avoids any dependency on extensions that might not be available on a free tier.</p><h3>Valkey: The Speed Layer + Real-Time Glue</h3><p>Valkey is doing double duty, and it’s the piece that ties the whole system together:</p><p><strong>As a cache</strong>, it keeps the last 200 earthquakes in a sorted set (scored by timestamp). When the frontend loads or a user adjusts filters, the API hits Valkey first — sub-millisecond response times, no database round-trip. Individual earthquake details are cached with a 5-minute TTL. Daily stats are cached with a 60-second TTL.</p><p><strong>As a pub/sub broker</strong>, it’s the real-time delivery mechanism. When the Kafka consumer processes a new earthquake, it publishes to the live-quakes channel. The FastAPI WebSocket handler subscribes to this channel and fans out the event to all connected browsers instantly.</p><p>This dual role is what makes Valkey indispensable in this architecture. Without it, I’d need either constant database polling (slow, wasteful) or a separate pub/sub system (over-engineered for this scale).</p><h3>The Challenges I Faced (And How I Solved Them)</h3><h3>Challenge 1: SSL Everywhere</h3><p>All three Aiven services require TLS. This is a <em>good thing</em> in production, but it means dealing with certificates from day one. Kafka needs a CA cert, service cert, and service key. PostgreSQL needs ?ssl=require on the connection string. Valkey uses the rediss:// scheme.</p><p>I centralized all of this in a Pydantic Settings config class that reads from environment variables and constructs SSL contexts programmatically. The Kafka SSL context is built once using Python’s ssl module, and the certs live in a certs/ directory that&#39;s .gitignored.</p><p><strong>Lesson learned:</strong> Get the SSL plumbing right first. Everything else is easy after that.</p><h3>Challenge 2: Graceful Degradation</h3><p>What happens when Kafka is temporarily unreachable? Or Valkey restarts? In a demo, it’s tempting to pretend services never go down. But I wanted QuakePulse to degrade gracefully:</p><ul><li>If Kafka fails, the producer’s <strong>circuit breaker</strong> stops attempting sends and retries after a cooldown period.</li><li>If Valkey is down, the API falls back to PostgreSQL for data and the WebSocket handler skips pub/sub.</li><li>If the WebSocket connection drops on the client side, the frontend switches to <strong>REST polling</strong> every 15 seconds as a fallback, complete with a visual indicator showing “Polling” instead of “Live.”</li><li>On startup, each service (DB, Kafka, Valkey) is initialized with a <strong>best-effort</strong> pattern — if one fails, the others still start, and the system runs in a degraded mode rather than crashing.</li></ul><p>This makes the system resilient in a way that a typical demo project isn’t.</p><h3>Challenge 3: Cold Start — The Empty Map Problem</h3><p>On first launch, the USGS all_hour feed might only have 5-10 earthquakes. An almost-empty map isn&#39;t impressive.</p><p>The solution: on startup, QuakePulse seeds from the all_day.geojson feed — the last 24 hours of global seismicity. This typically gives 100-200 earthquakes immediately, so the map is populated with real data the moment you open it. After seeding, it switches to the regular 60-second polling loop for truly live updates.</p><h3>Challenge 4: Deduplication Across Feeds</h3><p>The USGS updates existing earthquakes (revised magnitudes, additional felt reports) which means the same earthquake ID can appear in multiple polls. The producer maintains an in-memory set of seen IDs (capped at 5,000 to prevent unbounded growth) to avoid re-publishing duplicates. On the database side, the ON CONFLICT DO UPDATE upsert ensures we always have the latest data without creating duplicate rows.</p><h3>How Aiven’s Free Tier Enabled This</h3><p>Let me be direct: <strong>I would not have built this project without Aiven’s free tier.</strong></p><p>Setting up Kafka locally is notoriously painful — JVM dependencies, Zookeeper (or KRaft), broker configuration, topic creation. Setting up PostgreSQL isn’t bad, but adding proper TLS and async connection pooling adds friction. Valkey/Redis is the easiest of the three, but managing three separate local services while trying to build an application is a productivity killer.</p><p>With Aiven, I went from zero to fully connected in under 15 minutes:</p><ol><li>Created three services in the Aiven console</li><li>Downloaded Kafka certificates</li><li>Copied connection URIs into my .env file</li><li>Ran uvicorn app.main:app — and data started flowing</li></ol><p>No Docker Compose for infrastructure. No debugging “why won’t Kafka start.” No SSL certificate generation with openssl. Just production-grade managed services with a few clicks.</p><p>The free tier is generous enough for a real project too — 5 Kafka topics (I used 3), a proper PostgreSQL instance (not a toy SQLite), and an in-memory Valkey store fast enough for real-time caching and pub/sub. These aren’t sandboxed trial services with artificial limits — they’re real Aiven instances with real TLS, real availability, and the same API you’d use in production.</p><p>This let me spend my time on what matters: <strong>building the application</strong>, not fighting infrastructure.</p><h3>The Frontend: Making Data Visceral</h3><p>A streaming backend means nothing if the frontend doesn’t <em>feel</em> real-time. Here’s what makes QuakePulse’s map compelling:</p><ul><li><strong>Dark-themed CartoDB tiles</strong> create a dramatic backdrop where earthquake markers pop visually.</li><li><strong>Color-coded circles</strong> scale by magnitude — green for micro-quakes, yellow for light, orange for moderate, red for strong, dark red for great (6.0+). You can see seismic patterns at a glance.</li><li><strong>Pulse animations</strong> — when a new earthquake arrives via WebSocket, its marker animates with a CSS pulse effect. Your eye is naturally drawn to the new event.</li><li><strong>Marker clustering</strong> — at low zoom levels, markers group into clusters labeled with counts, so the map stays readable even with hundreds of events.</li><li><strong>Click-to-fly</strong> — the side panel lists recent earthquakes in a scrollable list. Click any event and the map smoothly flies to that location.</li><li><strong>Connection indicator</strong> — a green dot means live WebSocket, yellow means fallback polling, red means disconnected. Transparency builds trust.</li></ul><p>The entire frontend is vanilla JavaScript — no React, no build step, no node_modules. It loads fast, works everywhere, and the code is immediately readable.</p><h3>What I’d Build Next</h3><p>QuakePulse is a complete application, but the decoupled architecture means every extension is <em>additive</em> — new consumers, new features, zero changes to existing code.</p><ul><li><strong>Location-based mobile notifications </strong>— users subscribe with their GPS coordinates and a radius (e.g., “alert me for anything M3.0+ within 200 km”). A new Kafka consumer on the `quake-alerts` topic computes haversine distances against subscriber locations and fires push notifications via Firebase Cloud Messaging or APNs. The subscriber list lives in PostgreSQL; the hot set of active subscriptions stays in Valkey for fast lookups. Because the alerting topic already exists, this entire feature is a new consumer — the producer and pipeline don’t change at all.</li><li><strong>Alert zones</strong> — draw a circle on the map and get browser notifications when a quake occurs in that area (client-side distance calculation, minimal server changes)</li><li><strong>More Kafka consumers</strong> — a Slack webhook consumer that posts to a channel when a significant quake hits, using the quake-alerts topic that&#39;s already producing messages</li><li><strong>Historical replay</strong> — use Kafka’s offset management to replay past events, effectively turning the dashboard into a seismic activity timelapse. Imagine scrubbing through a week of Pacific Ring of Fire activity in 30 seconds.</li></ul><h3>Try It Yourself</h3><p>The entire project is open source. Clone it, provision three free Aiven services, add your connection URIs, and you’ll have a live earthquake dashboard in minutes.</p><p><strong>GitHub:</strong> <a href="https://github.com/prabhuj/quakepulse">github.com/</a>prabhu43<a href="https://github.com/prabhuj/quakepulse">/quakepulse</a></p><pre>git clone https://github.com/prabhu43/quakepulse.git<br>cd quakepulse/backend<br>python -m venv venv &amp;&amp; source venv/bin/activate<br>pip install -r requirements.txt<br>cp .env.example .env   # add your Aiven URIs<br>uvicorn app.main:app --host 0.0.0.0 --port 8000</pre><p>Open http://localhost:8000 and watch the Earth shake.</p><p><em>Built for the </em><a href="https://aiven.io/blog/the-aiven-free-tier-competition"><em>Aiven Free Tier Competition</em></a><em>. The Earth never stops shaking — now you can watch.</em></p><p><strong>#AivenFreeTier</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53df5f970184" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Inter-AZ Data Transfer Costs in K8s: Strategies for Savings]]></title>
            <link>https://itnext.io/demystifying-inter-az-data-transfer-costs-in-k8s-strategies-for-savings-c579821a3764?source=rss-6a2512a612e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c579821a3764</guid>
            <category><![CDATA[cost-savings]]></category>
            <category><![CDATA[high-availability]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Prabhu Jayakumar]]></dc:creator>
            <pubDate>Sun, 21 Apr 2024 17:15:09 GMT</pubDate>
            <atom:updated>2024-04-22T09:48:03.562Z</atom:updated>
            <content:encoded><![CDATA[<p>Throughout my six years of experience working with various K8s clusters across different environments, I’ve noticed a tendency to overlook Inter-AZ data transfer, resulting in significant expenses.</p><p>InterAZ (Inter-Availability Zone) data transfer costs within AWS EKS pertain to charges associated with transferring data between availability zones within the same AWS region. These costs fluctuate depending on the volume of data transferred and the region in which the EKS cluster is deployed.</p><p>Understanding and managing InterAZ data transfer costs in EKS is crucial for optimizing the overall cost efficiency of running Kubernetes workloads in AWS while ensuring high availability and reliability across availability zones</p><blockquote>Inter AZ Data Transfer cost in AWS, GCP and Azure: $0.01 per GB</blockquote><h3>Hidden Cost of High Availability</h3><p>Striving for High Availability often involves deploying applications in EKS clusters across multiple availability zones within a region, inadvertently leading to increased data transfer between these zones and subsequent charges.</p><p>To illustrate, consider two applications, X and Y, operating in different zones. When X connects to Y across zones, it contributes to InterAZ data transfer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/0*nXu6MTlfGyRKkIAe.jpg" /></figure><p>In AWS, data transferred between Availability Zones within the same region falls under the UsageType of Region-DataTransfer-Regional-Bytes. For instance, the USE2-DataTransfer-Regional-Bytes UsageType specifies charges for data transfer between Availability Zones in the US East (Ohio) Region.</p><p>Regarding billing, both inbound and outbound traffic for a specific resource incur charges for data transfers within an AWS Region, resulting in two separate line items of DataTransfer-Regional-Bytes for each data transfer corresponding to each metered resource.</p><h3>Cost-Effective Strategy</h3><p>Minimising inter-Availability Zone (interAZ) data transfer is crucial while maintaining high availability.</p><p>In the provided scenario, it’s advisable to limit App X’s connectivity to App Y which operates in a different zone. This measure not only decreases interAZ data transfer costs but also enhances network performance by connecting to pods situated within the same zone. Kubernetes’ Topology Aware Routing provides a solution to address this concern.</p><blockquote><em>Topology Aware Routing adjusts routing behavior to prefer keeping traffic in the zone it originated from. In some cases this can help reduce costs or improve network performance</em></blockquote><p>Enable Topology Aware Routing for Service Y by setting the service.kubernetes.io/topology-mode annotation to Auto. Endpoint slice controller will add hints to endpoints as follows and then kube-proxy will filter the endpoints based on these hints to route the traffic to a service.</p><pre>apiVersion: discovery.k8s.io/v1<br>kind: EndpointSlice<br>metadata:<br> name: example-hints<br> labels:<br>   kubernetes.io/service-name: example-svc<br>addressType: IPv4<br>ports:<br> - name: http<br>   protocol: TCP<br>   port: 80<br>endpoints:<br> - addresses:<br>     - &quot;10.1.2.3&quot;<br>   conditions:<br>     ready: true<br>   hostname: pod-1<br>   zone: zone-a<br>   hints:<br>     forZones:<br>       - name: &quot;zone-a&quot;</pre><p>But Topology Aware Routing works well when there are a minimum of 3 endpoints in each zone. We can use pod topology spread to distribute pods in all 3 zones</p><pre>topologySpreadConstraints:<br>   - labelSelector:<br>       matchLabels:<br>         app.kubernetes.io/app: Y<br>     matchLabelKeys:<br>       - pod-template-hash<br>     maxSkew: 1<br>     topologyKey: topology.kubernetes.io/zone<br>     whenUnsatisfiable: DoNotSchedule</pre><p>Pod topology constraints are considered only during scheduling of pods. If it is not strict(whenUnsatisfiable: ScheduleAnyway), there are a lot of chances for ignoring this constraint due to node availability. And during rolling update, while scheduling a new pod, it also considers old version pods which will be terminated in next steps. Finally It results in skewed distribution of new version pods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/0*BEBqV796zW8jbcL-.jpg" /></figure><p>Hence, whenUnsatisfiable: DoNotSchedule and matchLabelKeys: pod-template-hash are mandatory to achieve even distribution of pods consistently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/0*nQJvWJOg1XuCaape.jpg" /></figure><h3>Limitation of Topology Aware Routing</h3><p>Even after running 3 pods in each zone always, topology aware routing might get disabled when load in a zone is high compared to other zones. This is indicated by the Kubernetes event thrown by the endpoint slice controller. It fails to allocate 9 endpoints to 3 zones without exceeding the overload threshold. It happens when there are a lot of CPU in a zone. And it gets enabled automatically once the CPUs in thezone is back to the state which does not cross the overload threshold.</p><blockquote>TopologyAwareHintsDisabled: Unable to allocate minimum required endpoints to each zone without exceeding overload threshold (9 endpoints, 3 zones), addressType: IPv4</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/0*fFsqIixtCK8MuC4L.jpg" /></figure><p>For now, the only way to solve this permanently is to ensure CPUs in all zones are also balanced. But it is challenging as we have some apps that run only in fewer zones.</p><h3>Better solution</h3><p>We need more control over the traffic routing behavior irrespective of CPUs in each zone.</p><p>Kubernetes’ team proposed <a href="https://github.com/kubernetes/enhancements/tree/master/keps/sig-network/4444-service-routing-preference">an enhancement</a> to satisfy this requirement. And it introduced a new field “trafficDistribution” to offer greater control over traffic distribution to Service endpoints. This new alpha feature is available in K8s version 1.30 which was released recently on April 17, 2024</p><p>Now, We can set .spec.trafficDistribution: PreferClose in the K8s Service to ensure endpoints within the same zone are used by kube-proxy while routing requests.<a href="https://kubernetes.io/docs/reference/networking/virtual-ips/#traffic-distribution">(Reference)</a></p><h3>Bonus</h3><p>Aside from saving costs, limiting Inter-AZ data transfer offers two additional advantages as a bonus:</p><ul><li>Improving latency of requests between 2 services by keeping the traffic within a zone</li><li>Increasing the system’s resilience in the event of an Availability Zone failure</li></ul><h3>References</h3><ul><li><a href="https://kubernetes.io/docs/concepts/services-networking/service/#trafic-distribution">New traffic distribution feature</a></li><li><a href="https://github.com/kubernetes/endpointslice/blob/master/topologycache/topologycache.go#L328">EndpointSlice Controller throwing error</a></li><li><a href="https://github.com/kubernetes/kubernetes/pull/123487">PR for the Traffic Routing Preference</a></li><li><a href="https://github.com/kubernetes/enhancements/blob/master/keps/sig-network/2433-topology-aware-hints/README.md#overload">Overload concept in TopologyAwareRouting</a></li></ul><p><em>Originally published at </em><a href="https://prabhujayakumar.dev/blog/inter-az-data-transfer-k8s"><em>https://prabhujayakumar.dev</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c579821a3764" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/demystifying-inter-az-data-transfer-costs-in-k8s-strategies-for-savings-c579821a3764">Demystifying Inter-AZ Data Transfer Costs in K8s: Strategies for Savings</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Firewall for Applications in Kubernetes]]></title>
            <link>https://itnext.io/firewall-for-applications-in-kubernetes-af0acbe337da?source=rss-6a2512a612e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/af0acbe337da</guid>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[network-policies]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[kubernetes-security]]></category>
            <dc:creator><![CDATA[Prabhu Jayakumar]]></dc:creator>
            <pubDate>Fri, 19 Feb 2021 04:08:00 GMT</pubDate>
            <atom:updated>2021-02-19T04:10:58.118Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we will look at a kubernetes feature which is intended to improve security for applications running in a cluster</p><p>In a kubernetes cluster, we can run many applications with multiple replicas for each application. By default, any pods can talk to any other pods running in the same cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*2dcI61BNhb5Ctyz8ZUCZrA.jpeg" /><figcaption>Communication between different pods in cluster</figcaption></figure><p>But it is not recommended to allow such feature to be in place. In case an intruder get access to a pod, then he/she can access all pods from inside that compromised pod. So we need a firewall for applications using which it can decide if the traffic(both ingress and egress) should be allowed or denied inside the cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*RxZ9_Mp7o0iu1enmes8Clw.jpeg" /><figcaption>Restricted pod communication in k8s cluster</figcaption></figure><p>There comes the saviour, <strong><em>Network Policy</em></strong> that helps to create a firewall for applications running in kubernetes cluster.</p><p>Let’s understand the need for such firewall and how Network Policy helps for the same with some examples.</p><h3><strong>Guestbook</strong></h3><p>Consider an application <strong><em>Guestbook</em></strong> having 3 different components as follows:</p><ul><li>guestbook-ui (frontend)</li><li>guestbook-api (backend)</li><li>guestbook-db (db)</li></ul><p>Expected communication between these components are like ui communicates to api and api communicates to db.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*cIZzqGd4dqYBcQe2DJsiBA.jpeg" /><figcaption>Expected communication between guestbook pods</figcaption></figure><p>But when all these components of guestbook application are running in a kubernetes cluster, technically ui component can communicate to db by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*0gXVU5ssiIx6FkYMJQE8Dw.jpeg" /><figcaption>guestbook-ui pod can access db pod, which is not expected</figcaption></figure><h3><strong>Use Network Policy to setup firewall for applications in cluster</strong></h3><blockquote>As network policy is a feature that should be implemented by the network plugin, ensure that your network plugin supports NetworkPolicy resource. Creating NetworkPolicy resource without such plugin will have no effect. Calico, Cilium, Kube-router, Romana and Weave Net are some of the network plugins that support network policy</blockquote><p>As a first step, disable the default behaviour of allowing all communications between all pods running in a kubernetes cluster by creating a network policy as follows in all namespaces.</p><pre>apiVersion: networking.k8s.io/v1</pre><pre>kind: NetworkPolicy</pre><pre>metadata:</pre><pre>  name: deny-all</pre><pre>spec:</pre><pre>  podSelector: {}</pre><pre>  ingress: {}</pre><p>Now, none of the pods can communicate to any other pods running in the kubernetes cluster. Now based on requirements, allow the ingress/egress traffic for pods in the cluster.</p><p>For the guestbook application, to allow ingress traffic to <strong><em>guestbook-api</em></strong> pods but only from <strong><em>guestbook-ui</em></strong> pods, create a network policy as follows.</p><pre>apiVersion: networking.k8s.io/v1</pre><pre>kind: NetworkPolicy</pre><pre>metadata:</pre><pre>  name: allow-ui-to-api</pre><pre>spec:</pre><pre>  podSelector:</pre><pre>    matchLabels:</pre><pre>      app: guestbook-api</pre><pre>      tier: backend</pre><pre>  ingress:</pre><pre>  - from:</pre><pre>      podSelector:</pre><pre>        matchLabels:</pre><pre>          app: guestbook-ui</pre><pre>          tier: frontend</pre><p>And to allow ingress traffic to <strong><em>guestbook-db</em></strong> pods but only from <strong><em>guestbook-api</em></strong> pods, create a network policy as follows.</p><pre>apiVersion: networking.k8s.io/v1</pre><pre>kind: NetworkPolicy</pre><pre>metadata:</pre><pre>  name: allow-api-to-db</pre><pre>spec:</pre><pre>  podSelector:</pre><pre>    matchLabels:</pre><pre>      app: guestbook-db</pre><pre>      tier: db</pre><pre>  ingress:</pre><pre>  - from:</pre><pre>      podSelector:</pre><pre>        matchLabels:</pre><pre>          app: guestbook-api</pre><pre>          tier: backend</pre><p>Final setup with these network policies allows only the valid communications between the pods</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*Me7UP1ZQqQsIScE6S3m8gQ.jpeg" /><figcaption>guestbook-ui pod cannot access db pod as expected</figcaption></figure><h3><strong>More about network policy</strong></h3><h4><strong>NamespaceSelector</strong></h4><p>In some scenarios, we have to allow ingress from any pods in a namespace. For example, all applications pods should allow ingress from all pods in <strong><em>monitoring</em></strong> namespace. Namespace selector can be used to achieve this setup easily as follows.</p><pre>apiVersion: networking.k8s.io/v1</pre><pre>kind: NetworkPolicy</pre><pre>metadata:</pre><pre>  name: allow-monitoring-namespace</pre><pre>spec:</pre><pre>  podSelector: {} ## applies to all pods in the namespace</pre><pre>    ingress:</pre><pre>    - from:</pre><pre>        namespaceSelector:</pre><pre>          matchLabels:</pre><pre>            team: monitoring ## labels of the monitoring namespace</pre><h4><strong>IP Block</strong></h4><p>Not just labels, network policy also allows configuration using IP blocks. Following network policy allows ingress from 10.72.X.X but blocks traffic from 10.72.10.X</p><pre>apiVersion: networking.k8s.io/v1</pre><pre>kind: NetworkPolicy</pre><pre>metadata:</pre><pre>  name: allow-using-ip</pre><pre>spec:</pre><pre>  podSelector: {}</pre><pre>    ingress:</pre><pre>    - from:</pre><pre>        ipBlock:</pre><pre>          cidr: 10.72.0.0/16</pre><pre>          except: 10.72.10.0/8</pre><h3><strong>Conclusion</strong></h3><p>It is good to have security at all levels in k8s cluster. Adding a firewall for the application pods in the kubernetes cluster increases level of security by reducing the attack surface and hence is highly recommended.</p><p><em>Originally published at </em><a href="https://www.prabhujayakumar.dev/blog/save-your-k8s-cluster-from-dos/"><em>https://www.prabhujayakumar.dev</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af0acbe337da" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/firewall-for-applications-in-kubernetes-af0acbe337da">Firewall for Applications in Kubernetes</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Save Your Kubernetes Cluster From DoS]]></title>
            <link>https://itnext.io/save-your-kubernetes-cluster-from-dos-4b8855126ca1?source=rss-6a2512a612e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b8855126ca1</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[denial-of-service]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Prabhu Jayakumar]]></dc:creator>
            <pubDate>Mon, 06 Jul 2020 17:17:35 GMT</pubDate>
            <atom:updated>2020-07-12T11:15:33.574Z</atom:updated>
            <content:encoded><![CDATA[<p>Kubernetes has become a market leader in container orchestration tools. According to the <a href="https://www.cncf.io/wp-content/uploads/2020/03/CNCF_Survey_Report.pdf">2019 CNCF survey</a>, <strong>78% of respondents are using Kubernetes in production, a huge jump from 58% last year</strong></p><p>While containers have become the norm for deploying applications, kubernetes has become the norm for container management.</p><h3>DoS in Kubernetes cluster</h3><p>Consider a Kubernetes cluster with 3 worker nodes having a memory of 10GB each. Suppose the developers end up deploying some pods by mistake which consumes almost all the cpu and memory available in the node. Hence causing resource contention in the others application pods which serves traffic from consumers. This could also be caused when hackers inject high resource consuming pods intentionally into the system.</p><p>To understand this situation better, assume a node having 10GB of allocatable memory for containers and there are 5 application pods sharing the available memory. Each application pod on an average consumes 1GB of memory which makes the node to run at 50% to 60% memory utilization. Now deploying a pod that consumes 10GB of memory in the same node will cause noisy neighbor problem. This results in resource contention in other application pods which in turn either increase the latency of those services or in the worse case make the services go unavailable.</p><p>This might also happen when the developer commits a mistake in the code which leaks the memory and increase the memory usage steadily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*60EHfdnbAhJqixl8E-0i3Q.jpeg" /></figure><h3>Effective Resource Management in Kubernetes</h3><p>This is the reason why developers should be more conscious of the resources required for the services that they develop and configure the minimum required memory and cpu while deploying it in the Kubernetes cluster. Resource requests can be configured accordingly to schedule the pods in the node which guarantees the minimum resource.</p><p>For example, if a service requires 2 cpu and 3GB of memory at minimum, then in the pod specification configure the resource request as follows:</p><pre>apiVersion: v1</pre><pre>kind: Pod</pre><pre>metadata:</pre><pre>  name: demo-service</pre><pre>  namespace: demo</pre><pre>spec:</pre><pre>  containers:</pre><pre>  - name: demo-container</pre><pre>    image: demo-service-image</pre><pre>    resources:</pre><pre>      requests:</pre><pre>        cpu: &quot;2&quot;</pre><pre>        memory: &quot;3G&quot;</pre><p>It is also important that the developers should also configure the maximum resources that their service could consume. This helps in avoiding noisy neighbor problem in other service pods.</p><p>Let’s say the same demo-service should not consume more than 4 cpu and 5 GB of memory. In that case add the resource limit to the above pod specification.</p><pre>apiVersion: v1</pre><pre>kind: Pod</pre><pre>metadata:</pre><pre>  name: demo-service</pre><pre>  namespace: demo</pre><pre>spec:</pre><pre>  containers:</pre><pre>  - name: demo-container</pre><pre>    image: demo-service-image</pre><pre>    resources:</pre><pre>      requests:</pre><pre>        cpu: &quot;2&quot;</pre><pre>        memory: &quot;3G&quot;</pre><pre>      limits:</pre><pre>        cpu: &quot;4&quot;</pre><pre>        memory: &quot;5G&quot;</pre><p>It is strongly recommended to configure the resource requests and limits in the pods deployed in the Kubernetes cluster as per the service needs.</p><p>Having said that, just to be on the safer side, we need some policy to be added in the Kubernetes cluster to ensure the pods do not over utilize the resource causing noisy neighbor problem and hence save the apps deployed in cluster from Denial of Service.</p><h3>Save your Kubernetes cluster from DoS</h3><p>One solution to the above problem is setting up some kind of a quota on the resources that will be configured as requests and limits in pods. This is to ensure that no one over configures the resource requests and limits and hence avoid the over utilization of resources in the node (beyond some threshold).</p><p>Kubernetes provides ResourceQuota to achieve this as it injects an admission controller in validating phase. Most of the kubernetes distribution supports ResourceQuota by default. Even otherwise, it can be enabled by adding ResourceQuota in --enable-admission-plugins flag to kube-apiserver.</p><p>After enabling the ResourceQuota admission plugin, add the quota for each namespace as per need. For example, to allocate only 10GB of memory that deploy their services in a namespace, create a resource quota as:</p><pre>apiVersion: v1</pre><pre>kind: ResourceQuota</pre><pre>metadata:</pre><pre>  name: demo-resourcequota</pre><pre>spec:</pre><pre>  hard:</pre><pre>    limits.memory: 10G</pre><p>This resource quota ensures that the sum of memory in resource limits of all pods does not exceed 10GB of memory. Any create or modify request will be validated by the ResourceQuota admission controller in the validating phase. In case of non compliance of the existing ResourceQuota, the request will be rejected.</p><p>Now deploy the pod with memory limit of 2GB as follows:</p><pre>apiVersion: v1</pre><pre>kind: Pod</pre><pre>metadata:</pre><pre>  name: myapp-pod</pre><pre>  labels:</pre><pre>    app: myapp</pre><pre>spec:</pre><pre>  containers:</pre><pre>  - name: myapp-container</pre><pre>    image: busybox:1.28</pre><pre>    command: [&#39;sh&#39;, &#39;-c&#39;, &#39;echo The app is running! &amp;&amp; sleep 3600&#39;]</pre><pre>    resources:</pre><pre>      limits:</pre><pre>        memory: 2G</pre><p>And by running kubectl describe resourcequota demo-resourcequota, see that 2GB memory limit is used out of configured quota.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uWZpgULtbWzcoUyp.png" /></figure><p>When another pod having memory limit of 9GB is deployed, it will fail as it will exceed the quota of 10GB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hfJ3X0Hbbjy4XjWe.png" /></figure><p>Cluster administrators should configure the values in ResourceQuota so that it does not overutilize the nodes.</p><p>In kubernetes cluster, mentioning resource requests and limits in the pod spec is not mandatory and if its not mentioned, it means no limit for resources to be consumed by pod. It can consume resources as much as available in the node. Hence it is not recommended to skip the resource requests and limits in pod spec.</p><p>Having ResourceQuota, any pod creation or updation will be rejected if the request or limit of resources that is required by resource quota is missing. For example, the above resource quota will not allow creation or updation of pods that does not have resource limit for memory configured.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fjBhNQPS-nu_tkJp.png" /></figure><p>Simply to ensure that all the pods have some default resource request or limit, we can create LimitRanger in the namespace.</p><p>LimitRanger is also an admission controller which will be involved in the mutating phase. If any of the pod spec does not have resource requests or limits, it will add the resource request and limit as mentioned in the LimitRanger of same namespace.</p><p>Create a LimitRanger in a namespace as follows:</p><pre>apiVersion: v1</pre><pre>kind: LimitRange</pre><pre>metadata:</pre><pre>  name: default-requests-limits</pre><pre>  namespace: demo</pre><pre>spec:</pre><pre>  limits:</pre><pre>  - default:</pre><pre>      memory: 1Gi</pre><pre>    defaultRequest:</pre><pre>      memory: 500Mi</pre><pre>    type: Container</pre><p>And then apply the pod without resource requests and limits in the same namespace as follows:</p><pre>apiVersion: v1</pre><pre>kind: Pod</pre><pre>metadata:</pre><pre>name: myapp-no-resources-pod</pre><pre>labels:</pre><pre>app: myapp</pre><pre>spec:</pre><pre>containers:</pre><pre>- name: myapp-container</pre><pre>image: busybox:1.28</pre><pre>command: [&#39;sh&#39;, &#39;-c&#39;, &#39;echo The app is running! &amp;&amp; sleep 3600&#39;]</pre><p>Now, get the yaml of the above pod that is running in the K8s cluster. Resource request and limits that is mentioned in the LimitRanger default-requests-limits got added to .spec.resources.</p><pre>...</pre><pre>spec:</pre><pre>  containers:</pre><pre>  - command:</pre><pre>    - sh</pre><pre>    - -c</pre><pre>    - echo The app is running! &amp;&amp; sleep 3600</pre><pre>    image: busybox:1.28</pre><pre>    imagePullPolicy: IfNotPresent</pre><pre>    name: myapp-container</pre><pre>    resources:</pre><pre>      limits:</pre><pre>        memory: 1G</pre><pre>      requests:</pre><pre>        memory: 500Mi</pre><pre>...</pre><p>Once again run kubectl describe resourcequota demo-resourcequota and see that 3GB memory limit is used out of configured quota.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-rOsZwpPQfQomsBO.png" /></figure><h3>Conclusion</h3><p>Thus, configuring ResourceQuota and LimitRanger based on requirements, all the applications in the Kubernetes cluster can be saved from noisy neighbor problem and Denial of Service</p><p><em>Originally published at </em><a href="https://www.prabhujayakumar.dev/blog/save-your-k8s-cluster-from-dos/"><em>https://www.prabhujayakumar.dev</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b8855126ca1" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/save-your-kubernetes-cluster-from-dos-4b8855126ca1">Save Your Kubernetes Cluster From DoS</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Container from Scratch]]></title>
            <link>https://itnext.io/container-from-scratch-348838574160?source=rss-6a2512a612e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/348838574160</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Prabhu Jayakumar]]></dc:creator>
            <pubDate>Sat, 27 Jun 2020 17:28:57 GMT</pubDate>
            <atom:updated>2020-07-04T15:25:16.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vTiSw8CmL-iXjEBMBs8GHQ.jpeg" /></figure><p>This article was originally published at: <a href="https://www.prabhujayakumar.dev/blog/container-from-scratch">https://www.prabhujayakumar.dev/blog/container-from-scratch</a></p><p>This is my first blog and I want to share my learnings about containers</p><p>Container adoption to run enterprise applications softwares in production has been increasing drastically nowadays. And most of the container deployments are using docker. Docker became the de-facto technology for running containerised applications. But what is docker built on? How it is containerising the applications? I will try to answer these questions in this article.</p><h3><strong>Need for the Container</strong></h3><p>Before getting into containers, let’s clearly understand what a process is?</p><p>A process is created when a program is put into execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*tFYSnKuvNIoELkisT0sujQ.jpeg" /><figcaption>Process</figcaption></figure><p>How can we execute a program? What are the requirements to execute a program?</p><p>A program needs libs, envs and resources to be able to put into execution and thereby create a process. For example, to execute a python script, we need python binary and some python modules, python environments and resources like cpu, memory, disk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*DpCUm9tkbmFkPhtZCxuLdQ.jpeg" /><figcaption>Process Execution Requirements</figcaption></figure><p>Let us consider a Web Application which consists of many microservices running on various languages and various versions. These microservices are nothing but a process at the backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*MnMfsjYXWS_sA04S3bLIxA.jpeg" /><figcaption>Microservices of a Web Application</figcaption></figure><p>Now that being said, imagine running these services in a physical machine…</p><p>Thats not an easy task, ITS MERELY POSSIBLE</p><p>But Why? What is the challenge in running all these services of the same web application in a physical machine?</p><p>The problem is, suppose if the application has 2 Java services using different Java versions what will be the value for JAVA_HOME? There can’t be 2 JAVA_HOME set in a single physical machine.</p><p>If we have N services to be run in a machine, we have to assign the port to each service such that no port collision occurs. Think about running 2 versions of postgres, pg10 on 5432 port and pg9.6 on 5433 port. So all the services should be aware of the port it is running on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*I6TZ2xRVmVuWJqDu_9KRgg.jpeg" /><figcaption>Running all microservices of a web application in a host</figcaption></figure><p>To sum up the above mentioned challenge in a single word, there is NO ISOLATION.</p><p>Since there are different versions of libs and hence different envs are required, each and every service needs to be isolated from one another.</p><p>In order to isolate the processes, people started using Virtual Machines. Let’s see how Virtual Machines solve this problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*H-An2efdRGkT5_g1ub0Xxg.jpeg" /><figcaption>Virtual Machine</figcaption></figure><p>Virtual machine is a separate guest OS created by an hypervisor running on a host machine.</p><p>This separate guest OS, helps to achieve isolated libs, envs and resources.</p><p>But there are some challenges in using Virtual Machines in this case.</p><p>Think about running all the above services(processes) in a physical machine by creating required virtual machines(1 VM for 1 service).</p><p>You can evidently see the performance overhead in that physical machine which is running 10+ virtual machines. The reason being, the guest OS in each VM has its own memory management, network management and so on.</p><p>Not just that, proper resource utilization becomes a tough task while using Virtual Machines.</p><p>The main reason behind this overhead in Virtual machines approach is that the hypervisor virtualizes an hardware by creating guest OS for each VM.</p><p>All that we want is something which can isolate the libs, envs and resources without having to create separate OS. Why can’t we use the resource management of the Host OS itself instead of virtualizing the hardwares which results in overhead?</p><p>Yes, we have something called “CONTAINER” which is capable of doing the same for us.</p><p>A Container is nothing but an isolated process implemented by using some linux technologies like namespace and cgroup.</p><p>Now let us dive deep into containers, how they provide isolation to a process, what are namespaces and cgroup and how are they used.</p><p>Container is a group of process running on a host machine isolated by namespaces.</p><p>It provides OS level virtualization. Hence we can call it as “Lightweight VM”</p><p>We now have a basic understanding of what containers are. Next step would be how do we create it? I know many of us use docker to create containers using docker run command. But, is that the only option? No, there are few other tools like lxc, podman, etc. How the containers are created using these tools? What is the backend process?</p><p>To understand that, let us see how to create a container from scratch using linux technologies like namespace and cgroup.</p><h3><strong>Simple Container in Golang</strong></h3><p>Let’s create a simple go program which takes command as an argument and executes that command by creating a new process. Assume this go program as a docker. To execute a command in docker, we will use “docker run” command, similarly, here we use “go run container.go run”</p><pre>package main</pre><pre>import (</pre><pre>  &quot;fmt&quot;</pre><pre>  &quot;os&quot;</pre><pre>  &quot;os/exec&quot;</pre><pre>)</pre><pre>// go run container.go run &lt;cmd&gt; &lt;args&gt;</pre><pre>// docker run &lt;cmd&gt; &lt;args&gt;</pre><pre>func main() {</pre><pre>  switch os.Args[1] {</pre><pre>    case &quot;run&quot;:</pre><pre>      run()</pre><pre>    default:</pre><pre>      panic(&quot;invalid command!!&quot;)</pre><pre>  }</pre><pre>}</pre><pre>func run() {</pre><pre>  fmt.Printf(&quot;Running %v as PID %d \n&quot;, os.Args[2:], os.Getpid())</pre><pre>  cmd := exec.Command(os.Args[2], os.Args[3:]...)\</pre><pre>  cmd.Stdin = os.Stdin</pre><pre>  cmd.Stdout = os.Stdout</pre><pre>  cmd.Stderr = os.Stderr</pre><pre>  cmd.Run()</pre><pre>}</pre><p>The above program executes the given arguments as a command. As you see below, “go run container run echo hello container” executes the command “echo hello container”. It executes the command by creating a new process which can be considered as a container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lfxNTarOwADc2Yp7Fwp-0A.gif" /></figure><p>Similarly let’s create a process using `/bin/bash` and assign a dedicated hostname for that container. But changing the hostname inside the container, changed the hostname of the host machine as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wxP33BLWBDwYsxTCF8kE-Q.gif" /></figure><p>This happens because there is no isolation of hostname for this container. So, to create isolation of hostname, we can assign new UTS namespace for the container. In golang, we can do this by using the `syscall` package.</p><pre>func run() {</pre><pre>  fmt.Printf(“Running %v as PID %d \n”, os.Args[2:], os.Getpid())</pre><pre>  cmd := exec.Command(os.Args[2], os.Args[3:]…)</pre><pre>  cmd.Stdin = os.Stdin</pre><pre>  cmd.Stdout = os.Stdout</pre><pre>  cmd.Stderr = os.Stderr</pre><pre>  cmd.SysProcAttr = &amp;syscall.SysProcAttr{</pre><pre>    Cloneflags: syscall.CLONE_NEWUTS,</pre><pre>  }</pre><pre>  cmd.Run()</pre><pre>}</pre><p>Now, if you change the hostname of the container, it will not affect the hostname of the host machine because the container has its own UTS namespace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XNWE6SrfSUvpR6Hcs30uyA.gif" /></figure><p>But I want to assign the hostname automatically to the container from golang program using syscall `syscall.Sethostname([]byte(“container-demo”))`. But where can I place this line in the above program, the process is created on `cmd.Run()` and exited on the same line. Hence, let’s fork a child process and set hostname inside that.</p><pre>package main</pre><pre>import (</pre><pre>  “fmt”</pre><pre>  “os”</pre><pre>  “os/exec”</pre><pre>  “syscall”</pre><pre>)</pre><pre>// go run container.go run &lt;cmd&gt; &lt;args&gt;</pre><pre>// docker run &lt;cmd&gt; &lt;args&gt;</pre><pre>func main() {</pre><pre>  switch os.Args[1] {</pre><pre>    case “run”:</pre><pre>      run()</pre><pre>    case “child”:</pre><pre>      child()</pre><pre>    default:</pre><pre>      panic(“invalid command!!”)</pre><pre>  }</pre><pre>}</pre><pre>func run() {</pre><pre>  fmt.Printf(“Running %v as PID %d \n”, os.Args[2:], os.Getpid())</pre><pre>  args := append([]string{“child”}, os.Args[2:]…)</pre><pre>  cmd := exec.Command(“/proc/self/exe”, args…)</pre><pre>  cmd.Stdin = os.Stdin</pre><pre>  cmd.Stdout = os.Stdout</pre><pre>  cmd.Stderr = os.Stderr</pre><pre>  cmd.SysProcAttr = &amp;syscall.SysProcAttr{</pre><pre>    Cloneflags: syscall.CLONE_NEWUTS,</pre><pre>  }</pre><pre>  cmd.Run()</pre><pre>}</pre><pre>func child() {</pre><pre>  fmt.Printf(“Running %v as PID %d \n”, os.Args[2:], os.Getpid())</pre><pre>  syscall.Sethostname([]byte(“container-demo”))</pre><pre>  cmd := exec.Command(os.Args[2], os.Args[3:]…)</pre><pre>  cmd.Stdin = os.Stdin</pre><pre>  cmd.Stdout = os.Stdout</pre><pre>  cmd.Stderr = os.Stderr</pre><pre>  cmd.Run()</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*kYIkVGi2c05zfvxfrkZeXg.gif" /></figure><p>Another catch here is, the container is able to see all the processes running in the host machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bPFX5h5bF8NI_QHKz59feQ.gif" /></figure><p>A container should be able to see only the processes running in that container, which can be achieved by using PID namespace.</p><pre>cmd.SysProcAttr = &amp;syscall.SysProcAttr{</pre><pre>  Cloneflags: syscall.CLONE_NEWUTS | syscall.CLONE_NEWPID,</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xHxnl38JbQzr6CTbIj-i-w.gif" /></figure><p>Even then, the container is able to see the processes of the host machine. The reason is `/proc`; the container is using the same root filesystem as that of the host machine. Hence a different root file system is to be used for container and mount `/proc` into it.</p><p>`/containerfs` directory contains files of an operating system which has few binaries like python and core linux utilities. So mounting this directory as a root file system for container makes it self sufficient for linux utilities and not depend on host machine for binaries. It also provides separate environment for this container.</p><pre>func child() {</pre><pre>  fmt.Printf(“Running %v as PID %d \n”, os.Args[2:], os.Getpid())</pre><pre>  syscall.Sethostname([]byte(“container-demo”))</pre><pre>  cmd := exec.Command(os.Args[2], os.Args[3:]…)</pre><pre>  cmd.Stdin = os.Stdin</pre><pre>  cmd.Stdout = os.Stdout</pre><pre>  cmd.Stderr = os.Stderr</pre><pre>  syscall.Chroot(“/containerfs”)</pre><pre>  os.Chdir(“/”)</pre><pre>  syscall.Mount(“proc”, “proc”, “proc”, 0, “”)</pre><pre>  cmd.Run()</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*knUwXYv5SbLhRdwpCt795g.gif" /></figure><p>Now we have achieved process id isolation using PID namespace. Similarly, we can provide isolation of network and users using network and user namespace.</p><p>Basically, the namespace is about what you can see in the container. It allows us to create restricted views of systems like the process tree, network interfaces, and mounts and users. These are the various namespaces that are available to provide isolation:</p><ul><li>UTS(Unix Time Sharing) namespace: hostname and domain name</li><li>PID namespace: process number</li><li>Mounts namespace: mount points</li><li>IPC namespace: Inter Process Communication resources</li><li>Network namespace: network resources</li><li>User namespace: User and Group ID numbers</li></ul><p>Now, let us see how resource management works in container. I have a python script `<em>hungry.py`</em> which consumes 10mb of memory for each 0.5 seconds. Running this python script using the container.go program, allows the container process to consume all of the memory available in the host machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9u5KYtZFSU_y1kgxsm7NQ.gif" /></figure><p>To manage the resources like memory, cpu, disk blocks, we can use cgroups.</p><p>Every system has control groups in `/sys/fs/cgroup/` and memory uses the default values from `/sys/fs/cgroup/memory`. You can see that the value in `/sys/fs/cgroup/memory/memory.limit_in_bytes` is very huge, allowing a process to consume memory as much as available in the host machine.</p><p>Here, in this go program, I am creating a control group `prabhu` and giving 100mb as maximum limit of memory and disabling the swap memory. And also assigning the process id of the container to the tasks of cgroup `prabhu`.</p><pre>func child() {</pre><pre>  fmt.Printf(“Running %v as PID %d \n”, os.Args[2:], os.Getpid())</pre><pre>  syscall.Sethostname([]byte(“container-demo”))</pre><pre>  controlgroup()</pre><pre>  cmd := exec.Command(os.Args[2], os.Args[3:]…)</pre><pre>  cmd.Stdin = os.Stdin</pre><pre>  cmd.Stdout = os.Stdout</pre><pre>  cmd.Stderr = os.Stderr</pre><pre>  syscall.Chroot(“/containerfs”)</pre><pre>  os.Chdir(“/”)</pre><pre>  syscall.Mount(“proc”, “proc”, “proc”, 0, “”)</pre><pre>  cmd.Run()</pre><pre>}</pre><pre>func controlgroup() {</pre><pre>  cgPath := filepath.Join(“/sys/fs/cgroup/memory”, “prabhu”)</pre><pre>  os.Mkdir(cgPath, 0755)</pre><pre>  ioutil.WriteFile(filepath.Join(cgPath, “memory.limit_in_bytes”), []byte(“100000000”), 0700)</pre><pre>  ioutil.WriteFile(filepath.Join(cgPath, “memory.swappiness”), []byte(“0”), 0700)</pre><pre>  ioutil.WriteFile(filepath.Join(cgPath, “tasks”), []byte(strconv.Itoa(os.Getpid())), 0700)</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lADI5Zgm4XTYXQhZqSOH3Q.gif" /></figure><p>Since, cgroup `prabhu` assigned to the container process allows only 100mb of memory, the python process gets killed once it tries to exceed that memory limit.</p><p>By using cgroups, system administrators gain fine-grained control over allocating, prioritizing, denying, managing, and monitoring system resources. The hardware resources can be appropriately divided up among tasks and users, increasing overall efficiency. And hence we can use the cgroups for resource management in container ecosystem.</p><p>Here, I have created a simple container with isolation of hostname, mount(`/proc`) and process tree using corresponding namespaces and also did memory management for the container using cgroups.</p><h3><strong>Conclusion</strong></h3><p>Containers are just isolated groups of processes running on a single host and that isolation leverages several underlying technologies built into the Linux kernel like namespaces, cgroups and chroots.</p><p>This is how Docker is containerising the applications with many other features like storing and transferring the files in terms of docker images.</p><p>And Docker is not the only technology that helps to run containers. There are other options like Podman from RedHat, LXC Linux Containers and rkt from CoreOS(project closed now).</p><p>Inspired from <a href="https://www.youtube.com/watch?v=Utf-A4rODH8">Building a container from scratch in Go — Liz Rice</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=348838574160" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/container-from-scratch-348838574160">Container from Scratch</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>