<?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 Yasin Hastürk on Medium]]></title>
        <description><![CDATA[Stories by Yasin Hastürk on Medium]]></description>
        <link>https://medium.com/@ysnhasturk?source=rss-50050967942b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Kyc4Jjyt3NyRVF1e</url>
            <title>Stories by Yasin Hastürk on Medium</title>
            <link>https://medium.com/@ysnhasturk?source=rss-50050967942b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:50:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ysnhasturk/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[The Linux Kernel Revolution: Why eBPF Is Redefining Cloud-Native Observability, Networking and…]]></title>
            <link>https://medium.com/@ysnhasturk/the-linux-kernel-revolution-why-ebpf-is-redefining-cloud-native-observability-networking-and-dee1cd5fd5c2?source=rss-50050967942b------2</link>
            <guid isPermaLink="false">https://medium.com/p/dee1cd5fd5c2</guid>
            <dc:creator><![CDATA[Yasin Hastürk]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 13:12:52 GMT</pubDate>
            <atom:updated>2026-10-02T13:12:52.028Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Linux Kernel Revolution: Why eBPF Is Redefining Cloud-Native Observability, Networking and Security</h3><h3>1. Introduction</h3><h4>Why the Linux Kernel Is Suddenly Exciting Again</h4><p>For years the Linux kernel was seen as a steady but big foundation — a part that was only for the people who kept the operating system running. Changes here needed a lot of agreement and testing over years. In systems adding new ways to handle networking or security meant changing code in the kernel or building extra kernel modules. Both of these things could cause problems like crashing the system.</p><p>Now the kernel has become an easy to use engine. It allows developers to safely add programs into the system while it is running. This has made the Linux kernel the exciting part of software engineering today.</p><p><strong>The Problem: Observability, Networking and Security at Cloud-Native Scale</strong></p><p>As organizations migrate to Kubernetes and microservice architectures, infrastructure complexity increases exponentially. Microservices create massive east-west network traffic, pods spin up and terminate in seconds, and IP addresses change constantly. Traditional monitoring relying on polling agents or userspace collectors struggles to catch micro-bursts and short-lived container events while incurring heavy CPU and memory overhead.</p><p>At the same time, traditional sidecar container proxies introduce significant network hop latency, memory bloat, and operational maintenance burdens across large clusters. Furthermore, specialized cloud workloads — such as AI/ML inference on GPUs — introduce complex hardware and driver interactions where standard hardware exporters (like NVIDIA DCGM) report utilization drops or memory plateaus without explaining the underlying root cause, such as CUDA kernel launch waiting times or host-to-device memory transfer latencies.</p><p><strong>What This Article Covers</strong></p><p>This article looks closely at eBPF, the technology that is making this change in the kernel. We will look at how eBPF works, including the parts that check the code the way it turns code into instructions, the places where it can run and the points where it connects. We will explain why eBPF and Kubernetes work together. We will look at examples of how it is used in networking checking how things work, security and without extra containers. We will look at the challenges that come with using eBPF and explain why knowing about eBPF is important for people who manage software today.</p><h3>2. What Is eBPF?</h3><p><strong>From BPF to eBPF</strong></p><p>eBPF originated from the classic Berkeley Packet Filter (BPF), a lightweight packet filtering engine created in the 1990s to power utilities like tcpdump by filtering raw socket packets. Over the last decade, Linux kernel maintainers extended this architecture into eBPF, transforming it from a simple socket filter into a general-purpose, high-performance in-kernel virtual machine.</p><p><strong>The Core Idea: Sandboxed In-Kernel Execution</strong></p><p>The main idea of eBPF is that it can run custom code inside the kernel without changing the kernel code or using modules.</p><p><strong>The JavaScript Analogy: </strong>Just like JavaScript changed web pages into interactive ones without needing changes, to the browser eBPF changes the static Linux kernel into a fully adjustable system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZzsdNHpP4CRD01RNAUd0Pg.jpeg" /></figure><h4>How It Works Under the Hood: Hook Points</h4><p>eBPF programs are event-driven: they remain idle until a specific event triggers execution at a designated hook point in the kernel. Key hook points include:</p><ul><li><strong>kprobes &amp; kretprobes:</strong> Attach dynamically to the entry and return of kernel functions.</li><li><strong>uprobes &amp; uretprobes:</strong> Attach dynamically to userspace functions, enabling tracing of application libraries (such as OpenSSL or CUDA runtime calls like cudaLaunchKernel and cudaMemcpy).</li><li><strong>Tracepoints:</strong> Static, predefined event markers placed by kernel developers.</li><li><strong>XDP (eXpress Data Path):</strong> Ultra-low-level network hooks located directly in the network card driver before sk_buff memory allocation, enabling packet processing at bare-metal speeds.</li><li><strong>TC (Traffic Control):</strong> Network hooks attached to container virtual ethernet devices for ingress and egress traffic management.</li></ul><h4>The Verifier: Why eBPF Is Safe</h4><p>Executing user-written code inside the kernel presents obvious security and stability risks. Before an eBPF program is loaded via the bpf() system call, it must pass the eBPF Verifier. The verifier performs strict static code analysis to guarantee that:</p><ul><li>The loading process possesses appropriate kernel privileges (CAP_BPF or root).</li><li>The program cannot dereference null pointers or access out-of-bounds memory.</li><li>The program contains no unbounded infinite loops; all loops must have bounded exit conditions guaranteed to evaluate to true.</li><li>Execution paths fit within complexity and stack size limits.</li></ul><h4>JIT Compilation: Why eBPF Is Fast</h4><p>Once verified, generic eBPF bytecode is processed by a Just-In-Time (JIT) Compiler, which compiles the bytecode directly into native machine instructions (x86_64, ARM64). This allows eBPF programs to execute as fast as natively compiled kernel code or built-in kernel modules.</p><h4>eBPF Maps: Kernel-Userspace State Sharing</h4><p>Because eBPF programs operate in isolated contexts, they utilize eBPF Maps — efficient key-value data structures — to persist state and share metrics between the kernel and userspace applications. Map types include Hash Tables, Arrays, LRU Caches, Longest Prefix Match (LPM) Tries, and Ring Buffers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*0MgkYMx9xZBaCAj1ZQI6Zg.png" /></figure><h3>3. Why eBPF and Kubernetes Are a Perfect Match</h3><h4>Kubernetes Scale Challenges</h4><p>Kubernetes abstracts physical hardware into dynamic abstractions: pods, services, and namespaces. However, beneath this abstraction, pods are transient, IP addresses shift dynamically during reschedules, and inter-service communication creates complex network topologies. Userspace monitoring tools polling /sys directories struggle to keep pace with rapid container lifecycles.</p><h4>Limits of iptables and kube-proxy at Scale</h4><p>Traditionally, Kubernetes routing relies on kube-proxy generating iptables rules. In clusters with thousands of services and endpoints, iptables rules grow sequentially into tens of thousands of lines. Every incoming packet must evaluate these rules sequentially ($O(N)$ lookup complexity), leading to high CPU usage, packet processing bottlenecks, and slow service update propagation.</p><h4>The Sidecar Overhead Problem</h4><p>Service meshes historically relied on sidecar container proxies (e.g., Envoy) injected alongside every application pod. In large clusters, running thousands of sidecars consumes huge amounts of CPU and RAM, increases tail latency through extra TCP socket hops, and increases operational complexity.</p><h4>The Kernel Sees Everything</h4><p>Because every container and pod on a worker node shares the host’s underlying Linux kernel, an eBPF program deployed once at the node level sees all pod activity. It observes every network packet, system call, process execution, and socket connection transparently across all containers without requiring sidecar injection or SDK integration.</p><h3>4. Key Use Cases of eBPF in Kubernetes</h3><h4>High-Performance Networking</h4><ul><li><strong>eBPF-Based CNI Plugins:</strong> Modern Container Network Interfaces like Cilium and the Calico eBPF data plane replace iptables by translating Kubernetes policies into eBPF programs attached to container virtual interfaces.</li><li><strong>Replacing kube-proxy:</strong> eBPF map-based hash lookups enable $O(1)$ routing efficiency, routing service traffic directly without sequential rule evaluation.</li><li><strong>XDP Load Balancing:</strong> By attaching load balancing programs at the network driver layer via XDP, incoming packets are steered or filtered immediately at the NIC, processing millions of packets per second with minimal CPU usage (a technique pioneered at Meta with Katran).</li></ul><h4>Zero-Instrumentation Observability</h4><ul><li><strong>Auto-Instrumentation:</strong> eBPF captures L7 protocol details (HTTP, gRPC, database calls) and request latencies by attaching probes to kernel socket routines and userspace application functions without touching application code.</li><li><strong>Ecosystem Tools:</strong></li><li><strong>Hubble:</strong> Visualizes network flow topologies and L4–L7 traffic security policies in real time.</li><li><strong>Pixie:</strong> Uses eBPF uprobes/kprobes to collect distributed traces, HTTP metrics, and CPU profiles locally on nodes.</li><li><strong>Grafana Beyla:</strong> Provides zero-code OpenTelemetry-compliant metrics and traces for cloud-native apps.</li><li><strong>GPU &amp; Deep AI Observability:</strong> Traditional hardware tools (like NVIDIA DCGM) suffer from a “visibility illusion” — showing GPU utilization or temperature drops without revealing why performance stalled. eBPF hooks into CUDA runtime functions (cudaLaunchKernel and cudaMemcpy) to measure exact kernel launch latencies, CPU-to-GPU data movement bottlenecks, and detect unauthorized GPU crypto-mining activities.</li></ul><h4>Runtime Security &amp; Threat Detection</h4><ul><li><strong>Kernel-Level Intrusion Detection:</strong> Tools like Falco and Tetragon attach eBPF probes to syscalls and process execution paths. They detect runtime threats — such as unauthorized shell execution inside containers, privilege escalation attempts, or unauthorized access to sensitive files like /etc/shadow—in real time.</li><li><strong>L3–L7 Policy Enforcement:</strong> Enforces granular, identity-aware network policies using pod labels rather than volatile IP addresses.</li><li><strong>Augmenting seccomp &amp; LSM:</strong> Works alongside seccomp-bpf and Linux Security Modules (LSM) to enforce granular syscall and file access restrictions.</li></ul><h4>Sidecar-Less Service Mesh</h4><p>Platforms like Cilium Service Mesh and Istio Ambient Mesh leverage eBPF to handle mTLS encryption, L7 load balancing, and traffic routing directly at the node kernel layer. This eliminates the need for per-pod proxy sidecars, drastically cutting resource usage and network latency.</p><h3>5. Why eBPF Matters for DevOps Engineers</h3><h4>Faster Troubleshooting Without Code Changes</h4><p>DevOps and SRE teams no longer need to wait for application teams to add logging statements, import APM SDKs, or redeploy containers. eBPF provides instant, zero-instrumentation visibility into network drops, DNS latency, and system call errors out of the box.</p><h4>Superior Performance and Reduced Cloud Spend</h4><p>By replacing heavy polling agents and sidecar proxies with node-level eBPF DaemonSets, organizations reclaim substantial CPU and memory capacity across their Kubernetes clusters, directly lowering cloud infrastructure bills.</p><h4>Unified Engine for Infrastructure</h4><p>Instead of deploying separate, disjointed tools for CNI networking, APM tracing, and runtime security, eBPF serves as a singular, unified platform covering networking, security, and observability from a single kernel telemetry stream.</p><h4>Career Value</h4><p>As cloud-native environments shift toward Platform Engineering, eBPF proficiency is rapidly becoming one of the most valuable skill sets in cloud infrastructure, container security, and performance engineering.</p><h3>6. Challenges and Limitations</h3><p>While eBPF offers unprecedented power, platform teams must account for key technical constraints:</p><ul><li><strong>Kernel Version Dependencies:</strong> eBPF features evolve rapidly. Advanced features require modern Linux kernels (typically Linux 4.18+ or 5.x+) equipped with BPF Type Format (BTF) support, limiting backward compatibility on legacy OS distributions.</li><li><strong>Verifier Constraints:</strong> The kernel verifier can be unforgiving. Complex eBPF programs with intricate branching or state logic may be rejected during loading if the verifier cannot mathematically prove loop termination or memory safety.</li><li><strong>High Privilege Requirements:</strong> Deploying eBPF managers or loading eBPF programs requires elevated node privileges (CAP_BPF or CAP_SYS_ADMIN), making proper RBAC and bpfman daemon architectures vital to prevent misconfiguration risks.</li><li><strong>Debugging Complexity:</strong> Debugging kernel-level eBPF programs requires deep familiarity with C programming, LLVM toolchains, system calls, and Linux kernel internals.</li></ul><h3>7. The Future of eBPF</h3><ul><li><strong>The eBPF Foundation &amp; Industry Standardization:</strong> Backed by major technology leaders — including Meta, Google, Microsoft, Netflix, Isovalent, and Red Hat — the eBPF Foundation drives open-source community standards and cross-industry alignment.</li><li><strong>eBPF on Windows:</strong> Microsoft is actively extending eBPF capabilities to the Windows operating system, enabling unified cross-platform networking, security, and observability across hybrid OS clusters.</li><li><strong>The Direction of Cloud-Native Infrastructure:</strong> Kubernetes networking and security are shifting toward universal, kernel-native dataplanes, autonomous AI/GPU workload tracing, and fully sidecar-less service mesh architectures.</li></ul><h3>8. Conclusion</h3><h4>Key Takeaways</h4><p>eBPF represents a fundamental paradigm shift in operating system architecture. By bringing programmability directly into the Linux kernel, eBPF eliminates the historical trade-off between deep system visibility and runtime performance. In Kubernetes environments, eBPF delivers high-speed networking, zero-instrumentation observability, robust security enforcement, and sidecar-less service meshes.</p><h4>Recommended Resources</h4><ul><li><strong>Official Community Hub:</strong> <a href="https://ebpf.io/">ebpf.io</a></li><li><strong>eBPF Documentation:</strong> <a href="https://docs.ebpf.io/">docs.ebpf.io</a></li><li><strong>Project Documentation:</strong> <a href="https://docs.cilium.io/en/stable/">Cilium Docs</a></li></ul><h4><strong>Hands-On Learning</strong></h4><ul><li><strong>Learning eBPF (book code examples):</strong> <a href="https://github.com/lizrice/learning-ebpf">github.com/lizrice/learning-ebpf</a></li><li><strong>Isovalent Free Labs:</strong> <a href="https://isovalent.com/labs/">isovalent.com/labs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dee1cd5fd5c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Move Large Data Between Linux Servers with rsync]]></title>
            <link>https://medium.com/@ysnhasturk/how-to-move-large-data-between-linux-servers-with-rsync-3fb5d150c5f4?source=rss-50050967942b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fb5d150c5f4</guid>
            <dc:creator><![CDATA[Yasin Hastürk]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 14:40:44 GMT</pubDate>
            <atom:updated>2026-08-24T14:40:44.499Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical guide to rsync at scale — every flag explained, every flag you skipped explained, and how to prove the copy is actually correct</h4><p>Copying a directory between two Linux servers is a solved problem. Then the directory grows to a few hundred gigabytes and a million-odd files, and every assumption behind “it’s a solved problem” quietly stops holding.</p><p>The copy no longer finishes inside your SSH session. An interruption halfway through is not an inconvenience but a design consideration. cp -r no longer tells you anything useful about whether it worked. And in some storage layouts — content-addressable stores in particular — a file that only half arrived does not look like an error. It looks like a file.</p><p>This guide is about that transition: what changes when data gets large, how to build a transfer command by reasoning rather than by copy-paste, and how to verify the result in a way that would actually catch a problem.</p><p>It is written to be read before you run anything.</p><h3><strong>Part 1 — What actually changes at scale</strong></h3><p>Four things break as volume grows. Every decision later in this guide traces back to one of them.</p><p><strong>Duration turns into a failure mode.</strong> A transfer measured in hours will outlive your SSH session, your VPN, your laptop lid. The question stops being “will it finish” and becomes “what happens when it doesn’t, and can I resume without starting over”.</p><p><strong>File count costs more than file size.</strong> Moving 500 GB as ten large files and moving it as two million small ones are different problems on the same hardware. Every small file carries fixed overhead — a stat, an open, metadata, a close — and past a certain count you are no longer bandwidth-bound but syscall-bound. Your average file size is a real input to the design, not trivia.</p><p><strong>“It looked fine” stops being evidence.</strong> With twenty files you eyeball the destination. With two million you need a procedure — and one that compares more than just how many files landed.</p><p><strong>Partial writes become invisible.</strong> This is the one people underestimate, and Part 3 is devoted to it.</p><h3><strong>Part 2 — Why rsync, and not the obvious alternatives</strong></h3><p>Worth settling first, because the alternatives are genuinely better in specific cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*Rv5RNPjQaMLPqRW6FTHbIQ.png" /></figure><p>That last point is why rsync wins for most migrations. <strong>The same tool that performs the copy can tell you afterwards what still differs between source and destination.</strong> Nothing else in the list can do that.</p><p>The tar | ssh case deserves an honest caveat: if you are moving a huge number of tiny files <em>once</em>, with a maintenance window you control, and you have an independent way to verify, it can be considerably faster. Reach for rsync when you want resumability and a verification story — which, for a production migration, you do.</p><h3><strong>Part 3 — Understand the <em>shape</em> of your data firs</strong>t</h3><p>Not just how big. What kind.</p><p><strong>The easy case: large files, ordinary layout</strong></p><p>VM images, database dumps, media archives. Interruptions are the main risk, and a truncated file is obvious — wrong size, fails to open, checksum mismatch on first use. You will notice.</p><p><strong>The dangerous case: content-addressable storage</strong></p><p>Many document management systems (Nuxeo and Alfresco among them), backup tools, container registries and object stores use <strong>content addressing</strong>: the system hashes the bytes of a file, and that digest becomes the filename and the path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*3qRAQCWDLaZBSMhl4UBqAQ.png" /></figure><p>The database stores digests. The filesystem stores bytes. Nothing else links the two.</p><p>This creates a failure mode with no equivalent in ordinary file trees. <strong>A truncated file does not look broken — it looks like a file.</strong> It sits at the correct hash path. find | wc -l counts it. ls lists it. The database resolves a document to it. The user downloads a corrupt PDF. No error, no log line, no alert.</p><p>Content addressing is supposed to guarantee integrity — but only if something verifies the hash, and the normal read path never does. It trusts the path.</p><p>So: <strong>if your storage is content-addressable, design the transfer so a partial file can never appear under its final name.</strong> One specific flag does that, and Part 5 covers it. If you take one thing from this guide, take that.</p><h4>The other shape question: how the data is exposed</h4><p>The same bytes behave differently depending on what sits on top:</p><ul><li><strong>Plain directory, no service</strong> — simplest case, copy freely</li><li><strong>Live service writing to it</strong> — stop it for the transfer, or accept a copy that is not point-in-time consistent</li><li><strong>Container with a bind mount</strong> — numeric UIDs must line up on both hosts</li><li><strong>Database data directory</strong> — do not rsync it hot; use the database’s own dump/replication tools</li></ul><h3>Part 4 — Profile before you choose flags</h3><p>This is the step that separates a command you understand from a command you copied. Six checks. Two minutes. Each answer removes a flag from your command or makes one safe.</p><ol><li><strong>Are there hard links?</strong></li></ol><pre>find /data/myapp -type f -links +1 | head</pre><p>Output means you need -H. Without it, every hard link is copied as a separate full file and the destination can balloon well past the source size. People discover this when the target disk fills at 140% of what they expected.</p><p><strong>2. Are there ACLs or extended attributes?</strong></p><pre>getfacl -R /data/myapp 2&gt;/dev/null | grep -c &#39;^user:&#39;<br>getfattr -R -d /data/myapp 2&gt;/dev/null | head</pre><p>Output means you need -A and -X respectively. SELinux labels live in xattrs, so on RHEL-family systems the answer is often yes.</p><p><strong>3. How many distinct ownership combinations exist?</strong></p><pre>find /data/myapp -printf &#39;%u:%g\n&#39; | sort -u</pre><p>One line is the happy case — verification becomes a single stat comparison. Many lines means you must preserve ownership carefully and check it per-subtree.</p><p><strong>4. What is the average file size?</strong></p><pre>echo &quot;$(du -sb /data/myapp | cut -f1) bytes / $(find /data/myapp -type f | wc -l) files&quot;</pre><p>This single number drives more decisions than any other:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*3IxIh3D2jzBCu37WkqgIkg.png" /></figure><p><strong>5. Does the CPU support AES-NI?</strong></p><pre>grep -m1 -o aes /proc/cpuinfo<br>openssl speed -evp aes-128-gcm 2&gt;/dev/null | tail -3</pre><p>This decides your SSH cipher, and getting it wrong makes things <em>slower</em>. Check both machines — the transfer encrypts on one and decrypts on the other, so the slower CPU sets the ceiling.</p><p><strong>6. Is there room on the target, and is it empty?</strong></p><pre>ssh user@target &#39;df -h /data; ls -la /data/myapp&#39;</pre><p>An empty destination means the delta algorithm has nothing to compare against — which unlocks -W. A non-empty destination is a different transfer with different flags.</p><blockquote>Rule of thumb: never copy an rsync command — this guide’s included — without running these six checks first. They are what makes a given command correct for a given dataset, and they are the only part of this article that is not optional.</blockquote><h3><strong>Part 5 — Building the command</strong></h3><p>Rather than presenting a finished incantation, here is how it assembles. Start with the minimum that is correct:</p><pre>rsync -a /data/myapp/ user@target:/data/myapp/</pre><p>-a alone is a valid transfer. Everything after this point is a deliberate addition with a stated reason.</p><blockquote><strong>The trailing slashes are not decorative.</strong> /data/myapp/ means <em>the contents of</em> this directory. /data/myapp without the slash means <em>the directory itself</em>, producing /data/myapp/myapp on the target. This is the single most common rsync mistake. Both sides carry it in the examples here.</blockquote><p>The assembled command, for the profile described so far — small files, empty destination, numeric UID match, gigabit LAN, AES-NI present:</p><pre>rsync -aW --numeric-ids \<br>      --partial-dir=.rsync-partial \<br>      --info=progress2 \<br>      --exclude &#39;/logs/&#39; \<br>      -e &quot;ssh -c aes128-gcm@openssh.com&quot; \<br>      /data/myapp/ user@target:/data/myapp/</pre><p>Now, each flag: what it does, and how it can hurt you. <strong>The second half is the part tutorials skip, and it is the part that decides whether the flag belongs in <em>your</em> command.</strong></p><h4>-a — archive</h4><p><strong>What it does.</strong> Shorthand for -rlptgoD: recurse, preserve symlinks as symlinks, permissions, timestamps, group, owner, and device/special files. It is what makes the result a copy rather than an approximation.</p><p><strong>How it can hurt you.</strong> Not directly — but through what it omits. -a does <strong>not</strong> include:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*MfMp2gBwSHomUoyyMkBBbA.png" /></figure><p>The lesson is not “always add -HAX&quot;. It is that <strong>-a is not &quot;preserve everything&quot;</strong>, and adding all three blindly costs real memory and CPU across a million files — -H in particular has to build and hold a hard-link table. Add what your profiling found, and nothing more.</p><h4>-W — whole file</h4><p><strong>What it does.</strong> Disables the delta-transfer algorithm. Normally rsync splits the destination file into blocks, checksums them, and sends only the differing blocks. That is brilliant over a slow WAN. It is pointless when the destination is empty — there is nothing to compare against, and you are spending CPU to discover that every block is missing. On a fast LAN, skipping the computation is free speed.</p><p><strong>How it can hurt you.</strong> If a transfer is interrupted, a partially transferred file cannot be resumed mid-file — it is resent from byte zero. With small files that cost rounds to nothing. <strong>With multi-gigabyte files it is severe:</strong> an interruption at 90% of a 50 GB file throws away 45 GB of work.</p><blockquote><strong>Use </strong><strong>-W when:</strong> the destination is empty <em>and</em> files are small <em>and</em> the link is fast. <strong>Skip </strong><strong>-W when:</strong> files are large, the destination has existing data, or the link is slow or unreliable.</blockquote><p>-W also cancels the <em>speed</em> benefit of --partial-dir below. The <em>safety</em> benefit remains — and that is the one that matters.</p><h4>--numeric-ids</h4><p><strong>What it does.</strong> Transfers UIDs and GIDs as numbers without resolving them to names. Two reasons: name lookup across a million files is a measurable cost, and containers only ever look at the number, never the name.</p><p><strong>How it can hurt you.</strong> If the same UID belongs to a <em>different</em> user on the target, files end up owned by that user and your service cannot read them. Check 3, plus comparing id output on both hosts, is what makes this safe.</p><p>Worth stating plainly, because instinct runs the other way: <strong>name-based mapping — the default, without this flag — is the more dangerous option.</strong> When a username maps to different UIDs on the two machines, rsync silently writes a different number than the source had. Numeric mode fails predictably; name mode fails quietly.</p><h4>--partial-dir=.rsync-partial</h4><p><strong>The flag from Part 3.</strong> When a transfer is interrupted, incomplete data is held in a hidden .rsync-partial subdirectory inside the destination directory. The file is moved to its real name <strong>only once it is complete.</strong> An incomplete file never appears in the main tree, under any name anything else would look for.</p><p>For content-addressable storage this is the most important flag in the command. For ordinary file trees it is still good hygiene: nothing downstream ever reads a half-written file.</p><p><strong>Why not plain </strong><strong>--partial.</strong> --partial keeps incomplete data <strong>under the final filename.</strong> That is precisely the silent-corruption scenario from Part 3, implemented on purpose. --partial exists for resuming a large download you control end to end; it becomes actively dangerous the moment anything else reads that directory. The two flags look like variants of the same idea. They are opposites.</p><p><strong>How it can hurt you.</strong> Combined with -W there is no speed benefit — a half file is resent from scratch either way — only safety. And an interrupted transfer can leave orphaned .rsync-partial directories behind, which is why verification explicitly hunts for them.</p><h4>--info=progress2</h4><p><strong>What it does.</strong> Reports aggregate progress — total bytes, current rate, ETA — instead of per-file output. Past a few thousand files, per-file output is not a progress display; it is a denial-of-service attack on your terminal.</p><p><strong>How it can hurt you.</strong> Practically, nothing. One caveat worth internalizing: rsync builds its file list incrementally, so it does not know the true total when it starts. <strong>Ignore the percentage and ETA for the first stretch of a large transfer</strong> — they are computed against a file list that is still growing, and they will be wrong, usually optimistically.</p><h4>--exclude — and how its patterns actually work</h4><p>Some things should not travel. Logs are the standard example, and the reason is not disk space.</p><p>If you copy the old instance’s logs to the new server, the new instance opens the same file and appends to it. You now have one log file interleaving output from two machines with no way to tell which line came from where. You discover this during your first incident on the new server — the worst possible moment.</p><p>Similar candidates: caches, temp directories, .Trash, search index directories that the application rebuilds anyway, and anything under a *_transient naming convention.</p><p><strong>The pattern syntax is where people get hurt.</strong> In rsync, a leading / does not mean the filesystem root — it means <strong>the root of the transfer</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*XFwIJW3LSNT0nYbJQzP0Lw.png" /></figure><p>That third row is the trap. An over-qualified pattern does not error out. It quietly excludes nothing, and you find out when the files show up on the target.</p><p><strong>How it can hurt you.</strong> The pattern must be <strong>repeated identically in every command that touches this tree</strong> — the transfer <em>and</em> the verification dry-run. Miss it during verification and rsync reports “logs missing on target”, leaving you to work out whether that is a real inconsistency or your own pattern drift. Put it in a variable used by both:</p><pre>EXCL=&quot;--exclude=/logs/ --exclude=/tmp/&quot;<br>rsync -aW --numeric-ids $EXCL /data/myapp/ user@target:/data/myapp/</pre><h4>-e &quot;ssh -c aes128-gcm@openssh.com&quot; — choosing the cipher</h4><p><strong>What it does.</strong> Selects the SSH transport cipher. AES-128-GCM uses the CPU’s <strong>AES-NI</strong> hardware instructions. The modern default, ChaCha20-Poly1305, is a software cipher specifically designed for CPUs <em>without</em> AES acceleration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*1NhZgoELBziapome6Sse0w.png" /></figure><p>Orders of magnitude, not specifications — measure yours with openssl speed -evp aes-128-gcm.</p><p><strong>How it can hurt you.</strong> On a CPU without AES-NI it is dramatically <em>worse</em> — that bottom row is slower than the gigabit line you are trying to saturate. This is a flag to verify before using, never to copy.</p><p><strong>The honest version.</strong> On a 1 Gbps link the practical difference is small, because ChaCha20 can already saturate ~125 MB/s of wire. <strong>The real gain is CPU headroom</strong>, which leaves more cores for rsync’s own work — directory walking, syscalls, file list management. On 10 Gbps, or when running parallel streams that compete for CPU, the difference becomes obvious. On a saturated gigabit link with one stream, this flag is close to a no-op — include it knowing that.</p><p><strong>On security.</strong> AES-128-GCM is not a downgrade. It is an AEAD cipher (encryption plus integrity) and among OpenSSH’s recommended defaults. You are choosing between two strong ciphers based on hardware support, not trading security for speed.</p><h3>Part 6 — Flags you should not use</h3><p>Just as instructive, because most of these appear in tutorials as unconditional advice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*O4j__rgVABaYAxwYt9Q-3A.png" /></figure><h3>Part 7 — Running it so an interruption is survivable</h3><p><strong>Never run a multi-hour transfer in a bare SSH session.</strong> One dropped VPN and the process dies with it.</p><pre>screen -S sync        # or: tmux new -s sync</pre><p>Run the transfer inside. Detach with Ctrl+A then D (tmux: Ctrl+B then D). Reattach with screen -r sync (tmux: tmux attach -t sync).</p><p><strong>If it dies, run the exact same command again.</strong> This is rsync’s defining property: completed files are skipped, so a re-run resumes rather than restarts. Do not modify the command between attempts — changed flags mean a changed comparison, and you lose the guarantee.</p><p>Monitor from a second terminal:</p><pre>watch -n 60 &#39;ssh user@target &quot;du -sh /data/myapp; df -h /data | tail -1&quot;&#39;</pre><p><strong>Watch the destination disk.</strong> If the data lands on a filesystem shared with anything else, a full disk mid-transfer is a slow and irritating recovery. Intervene past 90%.</p><h4>Estimating how long it will take</h4><p>Two ceilings; the lower one wins:</p><ul><li><strong>Bandwidth ceiling</strong> — total size ÷ realistic throughput. A 1 Gbps link gives ~125 MB/s theoretical, ~100–110 MB/s realistic after overhead.</li><li><strong>File-count ceiling</strong> — with small files, per-file overhead dominates and you may see far less than the link allows.</li></ul><p>If measured throughput is well below the bandwidth ceiling, you are file-count-bound, and Part 8 is your remedy. Measure the link first so you know which problem you have:</p><pre>dd if=/dev/zero bs=1M count=4000 | ssh user@target &#39;cat &gt; /dev/null&#39;</pre><h3>Part 8 — Going parallel</h3><p>A single rsync is one process doing one thing: stat, read, encrypt, write, repeat. When the CPU has idle cores and the link is not saturated, splitting the work wins — typically 30–50%.</p><p><strong>Parallelism needs a natural partition.</strong> You cannot split one rsync; you run several over disjoint subtrees. What makes a good partition:</p><ul><li>Roughly equal in size — otherwise you wait for the one heavy stream</li><li>Disjoint — two rsyncs writing the same directory tree will fight</li><li>Enumerable up front</li></ul><p>Hash-prefix directories are ideal, because content addressing distributes files across them uniformly by construction. Date-partitioned trees (2024/01/, 2024/02/) work too. A tree with one enormous directory and forty tiny ones does not partition well — stay single-stream.</p><p>Move the light directories first, then fan out over the heavy partition:</p><pre># 1. everything except the big partition<br>rsync -aW --numeric-ids --info=progress2 --exclude &#39;binaries/&#39; \<br>      -e &quot;ssh -c aes128-gcm@openssh.com&quot; \<br>      /data/myapp/data/ user@target:/data/myapp/data/<br><br># 2. the big partition, N streams at a time<br>ssh user@target &quot;mkdir -p /data/myapp/data/binaries/data&quot;<br><br>ls /data/myapp/data/binaries/data | xargs -P 8 -I{} \<br>  rsync -aW --numeric-ids --partial-dir=.rsync-partial \<br>        -e &quot;ssh -c aes128-gcm@openssh.com&quot; \<br>        /data/myapp/data/binaries/data/{}/ \<br>        user@target:/data/myapp/data/binaries/data/{}/</pre><p><strong>Choosing </strong><strong>-P.</strong> Start at 4–8. More is not better: past the point where the link, the disks or the CPU saturate, extra streams add seek contention and context switching and make things <em>slower</em>. On spinning disks the tipping point comes early — concurrent random reads are the worst case for a mechanical drive. On NVMe you can push higher. Watch throughput as you raise it and stop when it stops improving.</p><p><strong>Two things to know about this path.</strong> --info=progress2 is dropped, because eight progress meters writing to one terminal is unreadable — use the watch loop instead. And exclusions that were relative to the old transfer root no longer apply: each stream has its own root now. Re-check that anything you meant to exclude is still outside the scope.</p><p>Verification is identical either way, and it is the same command in both cases.</p><h3>Part 9 — Verifying, in layers</h3><p>The step people skip because the transfer “looked fine”. Each layer catches something the previous one cannot.</p><h4>Layer 1 — the dry run</h4><p>The single most valuable check. Ask rsync what it would still need to change:</p><pre>rsync -an --delete --numeric-ids --itemize-changes \<br>      --exclude &#39;/logs/&#39; \<br>      /data/myapp/ user@target:/data/myapp/</pre><p>-n means dry run: nothing is modified. --delete here <em>reports</em> files on the target that are not on the source, rather than removing them. <strong>No file lines in the output means the copy is complete.</strong></p><p>Note --exclude &#39;/logs/&#39; appearing again, character for character. This is the drift trap from Part 5.</p><h4>Reading --itemize-changes output</h4><p>Cryptic on first contact, but there are only a few codes you meet in practice. Each line starts with an eleven-character field (YXcstpoguax):,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*ivFTo93x4sSFh05n_q0XRA.png" /></figure><p>.f....og... is the friendly one: no bytes need to move, you are one chown away from done. (Older rsync 2.x prints nine characters rather than eleven; same meaning, shorter string.)</p><h4>Layer 2 — counts and sizes</h4><pre>echo &quot;SOURCE: $(du -sb /data/myapp | cut -f1) bytes, $(find /data/myapp -type f | wc -l) files&quot;<br>ssh user@target &#39;echo &quot;TARGET: $(du -sb /data/myapp | cut -f1) bytes, $(find /data/myapp -type f | wc -l) files&quot;&#39;</pre><p>Use du -sb (bytes), not du -sh — human-readable output rounds, and rounding hides exactly the discrepancy you are looking for. If you excluded directories, exclude them from this comparison too or the numbers will differ by design.</p><p>Also check the distribution, not just the total, so a shortfall in one subtree cannot be masked by a surplus in another:</p><pre>du -sh /data/myapp/data/* | sort -rh<br>ssh user@target &quot;du -sh /data/myapp/data/* | sort -rh&quot;</pre><p><strong>Layer 3 — ownership</strong></p><pre>stat -c &#39;%u:%g (%U:%G)&#39; /data/myapp/data<br>ssh user@target &quot;stat -c &#39;%u:%g (%U:%G)&#39; /data/myapp/data&quot;</pre><p>The numeric pair must match, and it must match what the service runs as.</p><h4>Layer 4 — content, by sample</h4><p><strong>Everything above compares metadata.</strong> Counts, sizes, ownership, timestamps — not one byte of file content has been read. For content-addressable storage that is not sufficient, because the failure mode is a file of plausible size at a correct path.</p><pre>rsync -an --checksum --numeric-ids --itemize-changes \<br>      /data/myapp/data/binaries/data/00/ \<br>      user@target:/data/myapp/data/binaries/data/00/</pre><p>--checksum reads and hashes both sides. Empty output means the bytes genuinely match.</p><p>Why a sample: checksumming everything means reading the entire dataset twice, over the network — hours, against a risk --partial-dir has already largely eliminated. Pick a few partitions out of the whole. If the data is critical, pick more. If it is irreplaceable, run the lot and accept the time.</p><h4>Layer 5 — leftover partial directories</h4><pre>ssh user@target &quot;find /data/myapp -name &#39;.rsync-partial&#39; -type d&quot;</pre><p>Anything here means a stream died mid-file. Re-run the same rsync command.</p><h4>Layer 6 — the functional test</h4><p>Start the service on the target and <strong>exercise the real path end to end</strong> — for a document system, open a document in the UI and download its attachment.</p><p>Every layer so far compared two filesystems to each other. This is the first that proves the <em>application</em> can reach the data. A wrong bind-mount path, a missing environment variable, a permission mismatch inside the container — none of those show up in a byte comparison, and all of them surface here.</p><pre>docker compose up -d<br>docker exec myapp curl -fsS &quot;http://localhost:8080/healthcheck&quot;</pre><h3>Part 10 — What rsync does not move</h3><p><strong>Databases.</strong> If your application has one, the filesystem copy is half the migration. Use pg_dump, mysqldump or the engine&#39;s replication — never rsync a live data directory.</p><p><strong>Timing matters more than method.</strong> Take the dump <strong>inside the same window in which the service is stopped</strong>, so the database and the file store describe the same moment. Dump them at different times and you get records whose metadata exists but whose file does not — broken entries that no filesystem check will ever find, because from rsync’s perspective the copy was perfect.</p><p><strong>Configuration and secrets.</strong> Environment files, TLS certificates, cron jobs, systemd units, firewall rules. These live outside the data directory and are the usual reason a “successful” migration will not start.</p><p><strong>Do not delete the source.</strong> Not until verification passes <em>and</em> the new system has run cleanly under real use for several days. Storage is cheaper than a restore you cannot perform.</p><h3>Part 11 — Troubleshooting</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*45wwIC9ZWoOUepQO-hWobg.png" /></figure><h3>The short version</h3><p>If you skim one section, this one:</p><ol><li><strong>Profile first</strong> — hard links, ACLs/xattrs, ownership spread, average file size, AES-NI, free space. Six commands, two minutes, and they determine everything downstream. Never copy a command you have not profiled for.</li><li><strong>Average file size is a design input.</strong> It decides -W, it decides whether resume-from-scratch is acceptable, it decides whether parallelism will help.</li><li><strong>Know what a partial write looks like in your storage model.</strong> In content-addressable storage it looks like a healthy file. That single fact makes --partial-dir mandatory and plain --partial dangerous.</li><li><strong>Run it in </strong><strong>screen or </strong><strong>tmux,</strong> and know that re-running the identical command resumes.</li><li><strong>Stop the service, and dump the database inside the same window.</strong> Consistency between the two is not automatic.</li><li><strong>Verify in layers.</strong> Metadata checks are cheap and worth running, but they read no content. Sample-checksum something, then open the application and use it for real.</li><li><strong>LAN and WAN invert the defaults.</strong> -z becomes a bottleneck on a fast local link; a hardware-accelerated cipher beats the safe software default. Know which network you are on.</li></ol><p>The command is the easy part. The reasoning is what makes it correct for your data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fb5d150c5f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Highly Available Kubernetes Cluster with Kubeadm, HAProxy and Keepalived]]></title>
            <link>https://medium.com/@ysnhasturk/building-a-highly-available-kubernetes-cluster-with-kubeadm-haproxy-and-keepalived-31bce8462dc2?source=rss-50050967942b------2</link>
            <guid isPermaLink="false">https://medium.com/p/31bce8462dc2</guid>
            <dc:creator><![CDATA[Yasin Hastürk]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 11:49:48 GMT</pubDate>
            <atom:updated>2026-07-22T11:57:02.181Z</atom:updated>
            <content:encoded><![CDATA[<p>Setting up a production-ready, highly available (HA) Kubernetes cluster can feel like piecing together a massive puzzle. While managed Kubernetes services (like EKS, GKE, or AKS) handle the control plane for you, building it from scratch using <strong>Kubeadm</strong> gives you full control, deep architectural visibility, and zero cloud-vendor lock-in.</p><p>However, a control plane with multiple master nodes is only as good as its load balancer. If a single control plane node dies, how do your workers and kubectl clients know where to send API requests?</p><p>This is where <strong>HAProxy</strong> and <strong>Keepalived</strong> come into play:</p><ul><li><strong>Keepalived</strong> manages a floating <strong>Virtual IP (VIP)</strong> that instantly fails over if the primary node goes down.</li><li><strong>HAProxy</strong> sits behind that VIP, evenly distributing incoming API traffic across all active master nodes.</li></ul><p>In this step-by-step guide, we will build a resilient, highly available Kubernetes cluster with <strong>three master nodes</strong> and <strong>one worker node</strong> using standard Linux instances. <em>(You can scale and add as many worker nodes as needed following the exact same procedure)</em>.</p><h3>Architecture Overview</h3><p>Before opening the terminal, let’s look at the blueprint of what we are building:</p><ul><li><strong>Master Nodes:</strong> master1, master2, master3 <em>(Running both the K8s control plane and the HAProxy/Keepalived stack)</em></li><li><strong>Worker Node:</strong> worker1 <em>(Used for this guide, but you can scale and add as many worker nodes as your workload requires)</em></li><li><strong>Virtual IP (VIP):</strong> 10.152.82.100 (<em>A floating IP managed by Keepalived)</em></li><li><strong>Load Balancer Port:</strong> 6443 (<em>HAProxy routes traffic from this port to the API servers listening internally on port </em><em>6444)</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a3piU7ud6ZnfhW9R7YjLqg.png" /></figure><h3>Step 1: System-Level Prerequisites (All Nodes)</h3><p>Log into <strong>every single node</strong> (master1, master2, master3, worker1) and run the following system updates and baseline configurations.</p><h4>1. Disable Swap</h4><p>Kubernetes requires swap to be completely disabled to ensure reliable memory scheduling by the kubelet.</p><pre>sudo swapoff -a<br>sudo sed -i &#39;/ swap / s/^\(.*\)$/#\1/g&#39; /etc/fstab</pre><h4>2. Configure Kernel Modules and Sysctl Parameters</h4><p>Load the overlay and br_netfilter modules required for container networking, and allow bridged IPv4/IPv6 traffic to pass to iptables chains.</p><pre>cat &lt;&lt;EOF | sudo tee /etc/modules-load.d/k8s.conf<br>overlay<br>br_netfilter<br>EOF<br><br>sudo modprobe overlay<br>sudo modprobe br_netfilter<br><br># Configure sysctl params<br>cat &lt;&lt;EOF | sudo tee /etc/sysctl.d/k8s.conf<br>net.bridge.bridge-nf-call-iptables  = 1<br>net.bridge.bridge-nf-call-ip6tables = 1<br>net.ipv4.ip_forward                 = 1<br>EOF<br><br>sudo sysctl --system</pre><h4>3. Install Containerd Runtime</h4><p>We will use containerd as our Container Runtime Interface (CRI).</p><pre>sudo apt-get update &amp;&amp; sudo apt-get install -y containerd<br><br># Generate default configuration<br>sudo mkdir -p /etc/containerd<br>containerd config default | sudo tee /etc/containerd/config.toml<br><br># Crucial: Configure containerd to use SystemdCgroup<br>sudo sed -i &#39;s/SystemdCgroup = false/SystemdCgroup = true/g&#39; /etc/containerd/config.toml<br><br>sudo systemctl restart containerd<br>sudo systemctl enable containerd</pre><h3>Step 2: Installing Kubernetes CLI Tools (All Nodes)</h3><p>Next, install kubeadm, kubelet, and kubectl on all nodes.</p><pre>sudo apt-get update &amp;&amp; sudo apt-get install -y apt-transport-https ca-certificates curl gpg<br><br># Download the public signing key for the Kubernetes package repositories<br>curl -fsSL https://pkgs.k8s.io/core:/stable:/v1.30/deb/Release.key | sudo gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg<br><br># Add the appropriate Kubernetes apt repository<br>echo &#39;deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.io/core:/stable:/v1.30/deb/ /&#39; | sudo tee /etc/apt/sources.list.d/kubernetes.list<br><br>sudo apt-get update<br>sudo apt-get install -y kubelet kubeadm kubectl<br>sudo apt-mark hold kubelet kubeadm kubectl</pre><h3>Step 3: Setting Up HAProxy and Keepalived (Master Nodes Only)</h3><p>To eliminate single points of failure, we will configure an active-passive routing setup using Keepalived and HAProxy directly on master1, master2, and master3.</p><p>Run the installation command on <strong>all three masters</strong>:</p><pre>sudo apt-get update &amp;&amp; sudo apt-get install -y haproxy keepalived</pre><h4>1. Configure Keepalived</h4><p>Create /etc/keepalived/keepalived.conf on each master.</p><p><strong><em>Important:</em></strong><em> Adjust </em><em>state and </em><em>priority based on the node:</em></p><ul><li><strong>master1:</strong> state MASTER, priority 101</li><li><strong>master2:</strong> state BACKUP, priority 100</li><li><strong>master3:</strong> state BACKUP, priority 99</li></ul><pre>vrrp_script check_haproxy {<br>    script &quot;killall -0 haproxy&quot;<br>    interval 2<br>    weight 2<br>}<br><br>vrrp_instance VI_1 {<br>    state MASTER          # Set to BACKUP on master2 and master3<br>    interface eth0<br>    virtual_router_id 51<br>    priority 101          # 100 on master2, 99 on master3<br>    advert_int 1<br>    authentication {<br>        auth_type PASS<br>        auth_pass K8sHAClusterPass<br>    }<br>    virtual_ipaddress {<br>        10.152.82.100/24  # Your Virtual IP (VIP)<br>    }<br>    track_script {<br>        check_haproxy<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*WANfkqe6SHKqFWUcWBsQdg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*ElVbHmuWsKwjKezugvGFbw.jpeg" /></figure><h4>2. Configure HAProxy</h4><p>Modify /etc/haproxy/haproxy.cfg on <strong>all three master nodes</strong> so it receives API requests on port 6443 and distributes them across the underlying API servers listening on port 6444.</p><pre>frontend k8s-api<br>    bind 10.152.82.100:6443<br>    mode tcp<br>    option tcplog<br>    default_backend k8s-api-backend<br><br>backend k8s-api-backend<br>    mode tcp<br>    option tcp-check<br>    balance roundrobin<br>    server master1 10.152.82.193:6444 check<br>    server master2 10.152.82.181:6444 check<br>    server master3 10.152.82.194:6444 check</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3X0oA-xGefkKx5Z5HqeKFw.jpeg" /></figure><p>Start and enable both services on all master nodes:</p><pre>sudo systemctl enable keepalived haproxy<br>sudo systemctl restart keepalived haproxy</pre><h3>Step 4: Initializing the Cluster Control Plane</h3><p>Now that our load balancing layer points to the Virtual IP (10.152.82.100), we can safely initialize the cluster using kubeadm.</p><p>On <strong>master1</strong>:</p><pre>sudo kubeadm init --control-plane-endpoint &quot;10.152.82.100:6443&quot; --upload-certs --pod-network-cidr=10.244.0.0/16 --apiserver-bind-port=6444</pre><blockquote><strong><em>Note:</em></strong><em> We set </em><em>--apiserver-bind-port=6444 so the local Kubernetes API server doesn&#39;t conflict with HAProxy binding to port </em><em>6443.</em></blockquote><p>Upon successful initialization, copy the generated kubeadm join tokens for both control-plane nodes and worker nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*b11O0jBEZEml-3Jx_3x15A.jpeg" /></figure><p>To start managing your cluster from <strong>master1</strong>:</p><pre>mkdir -p $HOME/.kube<br>sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config<br>sudo chown $(id -u):$(id -g) $HOME/.kube/config</pre><h4>Deploy a CNI (Pod Network)</h4><p>Deploy a CNI plugin like <strong>Flannel</strong> or <strong>Cilium</strong> to enable pod communication:</p><pre>kubectl apply -f https://github.com/flannel-io/flannel/releases/latest/download/kube-flannel.yml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*PEsKhRMwIl9Ag0fSBRFTkQ.jpeg" /></figure><h3>Step 5: Joining Secondary Masters and Worker Nodes</h3><h4>Joining Master Nodes (master2 and master3)</h4><p>Run the control-plane join command saved from Step 4 on <strong>master2</strong> and <strong>master3</strong>. Make sure to append --apiserver-bind-port=6444:</p><pre>sudo kubeadm join 10.152.82.100:6443 --token &lt;your-token&gt; \<br>    --discovery-token-ca-cert-hash sha256:&lt;your-hash&gt; \<br>    --control-plane --certificate-key &lt;your-key&gt; \<br>    --apiserver-bind-port=6444</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*eLhPsW0q8LPQCjMG6_8rfw.jpeg" /></figure><h4>Joining Worker Nodes (worker1)</h4><p>Run the standard worker join command on <strong>worker1</strong>:</p><pre>sudo kubeadm join 10.152.82.100:6443 --token &lt;your-token&gt; \<br>    --discovery-token-ca-cert-hash sha256:&lt;your-hash&gt;</pre><p><strong>Note on Worker Scaling:</strong> For demonstration purposes, we are using <strong>one worker node</strong> due to resource constraints. However, this setup is fully scalable. You can add as many worker nodes as needed (worker2, worker3, etc.) simply by preparing them using <strong>Steps 1 &amp; 2</strong> and running this exact kubeadm join command on each.</p><h3>Step 6: Verifying Cluster Health &amp; Failover Testing</h3><h4>1. Check Node Status</h4><p>On <strong>master1</strong>, verify that all nodes have successfully joined and reached Ready status:</p><pre>kubectl get nodes -o wide</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FIOCwZFgJRUICTJgkuDorQ.jpeg" /></figure><h4>2. Verify Keepalived (VIP Ownership)</h4><p>Run the following command on all masters to confirm which node currently holds the Virtual IP:</p><pre>ip addr show eth0</pre><p>Only one master (the active MASTER, e.g., master1) should display the secondary IP: inet 10.152.82.100/24.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*vACstQSB34dJT5TXNpfKCg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*c2v0AngmRUqE6ZS43Ojj3A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*fbAnnkhaiPGMEYGzRZsACQ.jpeg" /></figure><p>Check Keepalived logs:</p><pre>sudo journalctl -u keepalived --no-pager -n 20</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pj1DBmy6iB16ALQUBh7r5w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*88Iw-NqBjMBfgEs_Yie0Dg.jpeg" /></figure><h4>3. Verify HAProxy Routing</h4><p>Test if HAProxy properly proxies traffic to your API servers:</p><pre>kubectl --kubeconfig=/etc/kubernetes/admin.conf get componentstatuses</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*iUZ6t84vEIOtAjbOflu_Jg.jpeg" /></figure><p>Check service status:</p><pre>sudo systemctl status haproxy</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*K9rX6YcgkjtpJCDypNLqNg.jpeg" /></figure><h4>4. Simulating Failover (Resiliency Test)</h4><p>To verify high availability, let me crash master1 on purpose:</p><ol><li>Stop Keepalived on master1:</li></ol><pre>sudo systemctl stop keepalived</pre><p>2. Check VIP on master2/master3:</p><pre>ip addr show eth0</pre><p>You will see 10.152.82.100 immediately drift to one of the backup nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*39fiZuVLv7tjqvT66XToUA.jpeg" /></figure><p>3. Execute cluster commands:</p><p>Run kubectl get nodes from your local machine or worker. Operations continue without interruption.</p><p>4. Restore master1:</p><pre>sudo systemctl start keepalived</pre><p>Because master1 has a higher priority (101), it reclaims the VIP smoothly.</p><h3>Conclusion</h3><p>You now have a fully operational, high-availability Kubernetes cluster running on standard infrastructure! By combining <strong>Kubeadm</strong> with <strong>HAProxy</strong> and <strong>Keepalived</strong>, your control plane can survive the loss of any single master node without causing downtime for cluster management or worker workloads.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31bce8462dc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End Hardcoded IPs: Building a Zero-Touch K3s Cluster with Terraform’s templatefile]]></title>
            <link>https://medium.com/@ysnhasturk/stop-hardcoding-ips-dynamic-k3s-cluster-setup-with-terraform-multipass-6f511995df3e?source=rss-50050967942b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f511995df3e</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[Yasin Hastürk]]></dc:creator>
            <pubDate>Tue, 20 Jan 2026 09:40:47 GMT</pubDate>
            <atom:updated>2026-09-02T06:50:00.091Z</atom:updated>
            <content:encoded><![CDATA[<p>As DevOps engineers, we love automation. But we often hit a “Chicken and Egg” problem when building infrastructure: <strong>How do I configure Server B with Server A’s IP address, if Server A hasn’t even been created yet?</strong></p><p>In this guide, we won’t just build a lightweight Kubernetes (K3s) cluster using Multipass and WSL. We are going to solve this dynamic configuration problem using one of Terraform’s most powerful features: the <strong>templatefile</strong> function.</p><p>By the end of this tutorial, you will have a running local lab and a solid understanding of how to inject dynamic data into your startup scripts.</p><h3>1. The Setup &amp; Prerequisites</h3><p>Before we dive into the code, let’s quickly understand the tool that powers our infrastructure.</p><blockquote><strong><em>What is Multipass?</em></strong><em> Developed by </em><strong><em>Canonical</em></strong><em> (the creators of Ubuntu), Multipass is a lightweight VM manager designed specifically for developers. Unlike heavy GUI-based tools, it spins up cloud-style Ubuntu instances in seconds. It achieves this speed and efficiency by utilizing your operating system’s native hypervisor (Hyper-V on Windows, KVM on Linux, and QEMU/HyperKit on macOS).</em></blockquote><p>I’m going to assume you already have your development environment ready to go. To follow along, you should have:</p><ul><li><strong>Multipass</strong> installed on Windows (handling the VMs).</li><li><strong>Terraform</strong> installed inside WSL (Ubuntu).</li><li><strong>WSL 2</strong> active and running.</li></ul><p><strong>⚠️ A Quick Sanity Check for WSL Users:</strong> Even if both tools are installed, Terraform inside WSL might not “see” Multipass running on Windows because they live in different environments. Before we start, make sure you’ve bridged the gap.</p><p>If multipass version fails inside your WSL terminal, run this quick fix to link the Windows executable to your Linux path:</p><pre>sudo ln -s &quot;/mnt/c/Program Files/Multipass/bin/multipass.exe&quot; /usr/local/bin/multipass</pre><p>Now that our tools are talking to each other, let’s focus on the code.</p><h3>2. The Challenge: Dynamic IPs in Infrastructure</h3><p>Imagine you are building a Kubernetes cluster.</p><ol><li>You launch a <strong>Master Node</strong>. It gets a random IP from the DHCP.</li><li>You launch a <strong>Worker Node</strong>.</li><li>The Worker needs to run a “join command” that includes the Master’s IP.</li></ol><p>If you were doing this manually, you would copy-paste the IP. But in Terraform (IaC), we want zero manual intervention. We need a way to tell Terraform: <em>“Wait for the Master to finish, grab its IP, write it into the Worker’s script, and THEN launch the Worker.”</em></p><p>This is exactly what templatefile does.</p><blockquote><strong>Terraform Tooltip: Understanding </strong><strong>templatefile</strong></blockquote><p>Before we implement it, let’s briefly define what this function actually does.</p><ul><li><strong>What is it?</strong> templatefile(path, vars) is a built-in Terraform function that reads a text file and renders it based on a set of variables you provide.</li><li><strong>What is it used for?</strong> It is primarily used to generate dynamic configuration files, shell scripts, or cloud-init data where the values (like IPs, Database URLs, or passwords) are not known until runtime.</li><li><strong>Why use it?</strong> It keeps your code clean. Instead of writing messy, long shell scripts inside your main.tf (using &quot;heredoc&quot; syntax), you can keep your scripts in separate files (like .sh or .yaml) and just inject the necessary data when Terraform runs.</li></ul><blockquote>Which Provider are we using?</blockquote><p>To make this orchestration work on our local machine, we leverage the <strong>Multipass Provider</strong> (specifically larstobi/multipass).</p><p>Multipass is a lightweight VM manager by Canonical that uses native hypervisors (like Hyper-V on Windows or QEMU on Linux). By using this provider, Terraform can treat local VMs just like cloud instances, allowing us to automate the creation, resource allocation, and cloud-init execution of our Ubuntu nodes with ease.</p><h3>3. The Solution: templatefile in Action</h3><p>Let’s look at how we implemented this logic in our Terraform files.</p><h3>Step A: The Template (worker_setup.tftpl)</h3><p>First, we create a shell script but save it with the .tftpl extension. This is our &quot;blueprint.&quot; Instead of hardcoding values, we use placeholders like ${master_ip}.</p><pre>#cloud-config<br>package_update: false<br>package_upgrade: false<br>runcmd:<br>  - |<br>    (<br>    # Wait until Master API Server (6443) is reachable<br>    until curl -k https://${master_ip}:6443; do sleep 5; done<br>    # Install K3s Agent and join the cluster<br>    curl -sfL https://get.k3s.io | K3S_URL=https://${master_ip}:6443 \<br>    K3S_TOKEN=&quot;${join_token}&quot; sh -<br>    ) &amp;<br>  - ufw disable</pre><p>Notice we aren’t writing 192.168.x.x. We are writing variables that don&#39;t exist yet!</p><h3>Step B: The Rendering (main.tf)</h3><p>Now, inside our Terraform code, we use the templatefile function to fill in the blanks dynamically.</p><pre># main.tf<br><br># 1. Create the Master Node first<br>resource &quot;multipass_instance&quot; &quot;master&quot; {<br>  name = &quot;k8s-master&quot;<br>  # ... specs ...<br>}<br><br># 2. Render the Template<br>resource &quot;local_file&quot; &quot;worker_cloudinit_rendered&quot; {<br>  content = templatefile(&quot;${path.module}/worker_setup.tftpl&quot;, {<br>    # Here is the magic: We map the Terraform resource output to the template variable<br>    master_ip  = multipass_instance.master.ipv4<br>    join_token = var.k3s_token<br>  })<br>  filename = &quot;${path.module}/worker_setup_rendered.yaml&quot;<br>}</pre><p><strong>What is happening here?</strong></p><ol><li>Terraform builds the master instance first.</li><li>It grabs the new dynamic IP (multipass_instance.master.ipv4).</li><li>It reads worker_setup.tftpl.</li><li>It replaces ${master_ip} with the actual IP address.</li><li>It saves the result as a <strong>new</strong> file called worker_setup_rendered.yaml.</li></ol><h3>Step C: The Deployment</h3><p>Finally, when the Worker node launches, it uses this <em>rendered</em> file which now contains the correct, real-time connection details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*rF_swFzN7cwu9EIikO1ycw.jpeg" /></figure><h3>4. Why Use master_setup.yaml?</h3><p>For the Master node, the setup is simpler since it doesn’t need to know anyone else’s IP. We use a standard cloud-init YAML file.</p><p>A key detail here is running the install command in the background (&amp;).</p><pre># master_setup.yaml<br>runcmd:<br>  - (curl -sfL https://get.k3s.io | K3S_TOKEN=&quot;k8s-otomatik-sifre-2026&quot; sh -) &amp;</pre><p><em>Why?</em> Because K3s installation might take a minute. If we don’t push it to the background, Terraform might think the provisioning script is “stuck” and time out.</p><h3>5. Launching the Lab</h3><p>Now, let’s fire it up. Open your terminal in the folder containing your .tf files.</p><pre># Initialize providers<br>terraform init<br><br># Apply the configuration0<br>terraform apply -auto-approve</pre><p>Watch the logs closely. You will see the local_file resource being created <em>after</em> the master but <em>before</em> the worker. This is the dependency graph at work.</p><h3>6. Verifying the Cluster</h3><p>Once Terraform finishes (usually in 2–3 minutes), let’s verify our lab environment.</p><p>Log into the master node:</p><pre>multipass shell k8s-master</pre><p>multipass shell k8s-master</p><pre>kubectl get nodes</pre><p>You should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*P3Gk9irFhkl0n3VNNvg_rg.jpeg" /></figure><p>Congratulations! You have successfully orchestrated a dynamic infrastructure where servers configure themselves based on real-time data.</p><h3>Conclusion</h3><p>While setting up a Kubernetes lab is useful, understanding <strong>Terraform </strong><strong>templatefile</strong> is the real takeaway here.</p><p>We moved away from static configurations to a dynamic setup where:</p><ol><li><strong>Infrastructure is flexible:</strong> IP addresses can change, and the code still works.</li><li><strong>Setup is automated:</strong> No manual copy-pasting of tokens or IPs.</li><li><strong>Code is clean:</strong> Logic is separated from configuration.</li></ol><p>You can use this same pattern for generating Ansible inventories, load balancer configs, or any scenario where Server B needs to know about Server A.</p><h3>📥 Get the Complete Code</h3><p>Don’t want to copy-paste snippets? You can clone the full repository with all the ready-to-use Terraform and Cloud-init files from my GitHub.</p><p>👉 <a href="https://github.com/yasindevops/k3s-multipass-terraform"><strong>k3s-multipass-terraform Repository</strong></a></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f511995df3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Docker Images the Right Way: Size, Layers, and Security]]></title>
            <link>https://medium.com/@ysnhasturk/building-docker-images-the-right-way-size-layers-and-security-c03f08250469?source=rss-50050967942b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c03f08250469</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[multi-stage-dockerfile]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[docker-image]]></category>
            <dc:creator><![CDATA[Yasin Hastürk]]></dc:creator>
            <pubDate>Mon, 15 Dec 2025 05:31:41 GMT</pubDate>
            <atom:updated>2025-12-15T05:31:41.176Z</atom:updated>
            <content:encoded><![CDATA[<p>Docker images are one of the most fundamental building blocks of modern application delivery.<br> Yet many production images are still unnecessarily large, hard to reproduce, and insecure by default.</p><p>In this article, we’ll walk through:</p><ul><li>The difference between virtual machines and containers (briefly, for context)</li><li>How Docker images are built using layers</li><li>Why simple images often become huge</li><li>How multi-stage builds dramatically reduce image size</li><li>Practical steps to build <strong>smaller and more secure Docker images</strong></li></ul><p>The focus is not theory, but <strong>practical image construction techniques</strong> you can apply immediately.</p><h3>Virtual Machines vs Containers (Quick Context)</h3><h3>Virtual Machines</h3><p>A virtual machine typically consists of:</p><ul><li>Host operating system</li><li>Host kernel</li><li>Hypervisor</li><li>Guest operating system (with its <strong>own kernel</strong>)</li><li>Application running inside the guest OS</li></ul><p>Each VM includes a full operating system. This provides strong isolation, but also comes with:</p><ul><li>Higher resource usage</li><li>Slower startup times</li><li>More maintenance overhead</li></ul><h3>Containers</h3><p>Containers take a different approach:</p><ul><li>Host operating system</li><li><strong>Single host kernel</strong></li><li>Container runtime (Docker, containerd)</li><li>Application process isolated using kernel features</li></ul><p>Instead of shipping an entire OS, containers rely on Linux kernel mechanisms:</p><ul><li><strong>Namespaces</strong> for isolation (processes, networking, filesystem views)</li><li><strong>cgroups</strong> for resource limits</li></ul><p>Containers are essentially regular processes placed into isolated environments. This makes them lightweight and fast — but also means that <strong>image quality and configuration matter a lot</strong>.</p><h3>How Docker Images Are Built: Layers</h3><p>Docker images are based on a <strong>layered filesystem</strong>.</p><p>Each instruction in a Dockerfile either:</p><ul><li>Creates a new filesystem layer</li><li>Or updates image metadata</li></ul><h3>Instructions That Create Layers</h3><p>These typically increase image size:</p><ul><li>RUN</li><li>COPY</li><li>ADD</li></ul><h3>Instructions That Do Not Create Layers</h3><p>These modify metadata only:</p><ul><li>CMD</li><li>ENTRYPOINT</li><li>ENV</li><li>EXPOSE</li><li>USER</li></ul><p>Every additional layer increases:</p><ul><li>Image size</li><li>Build time</li><li>Potential attack surface</li></ul><p>Understanding this is key to building efficient images.</p><h3>A Simple Image That Becomes Surprisingly Large</h3><p>Let’s imagine a very simple Go application that prints the current user every second.</p><p>A straightforward Dockerfile might:</p><ul><li>Start from Ubuntu</li><li>Install the Go compiler</li><li>Copy the source code</li><li>Build the binary</li><li>Run the application</li></ul><p>After building the image:</p><pre>docker image ls | grep app</pre><p>You may see something like:</p><pre>app   latest   ~700MB</pre><p>That’s huge — especially for a tiny application.</p><h3>Why does this happen?</h3><p>Because the final image still contains:</p><ul><li>The Ubuntu base image</li><li>The Go compiler</li><li>All build dependencies</li><li>All layers created during installation and compilation</li></ul><p>Even though the compiler is no longer needed at runtime, it’s still there.</p><h3>Multi-Stage Builds: The Correct Approach</h3><p>Multi-stage builds solve this problem cleanly.</p><h3>The Idea</h3><ul><li>Use one image to <strong>build</strong> the application</li><li>Use a second, minimal image to <strong>run</strong> it</li><li>Copy only the compiled artifact between stages</li><li>Discard everything else</li></ul><p>Only the <strong>last stage</strong> becomes the final image.</p><h3>Example: Multi-Stage Dockerfile</h3><pre>#########################<br># Stage 0: Build stage  #<br>#########################<br>FROM ubuntu:22.04 AS builder<br>ARG DEBIAN_FRONTEND=noninteractive<br>RUN apt-get update &amp;&amp; apt-get install -y golang-go<br>COPY app.go .<br>RUN CGO_ENABLED=0 go build -o /app app.go<br><br>#############################<br># Stage 1: Runtime stage    #<br>#############################<br>FROM alpine:3.12.1<br>COPY --from=builder /app /app<br>CMD [&quot;/app&quot;]</pre><p>After building:</p><pre>docker build -t app-multistage .</pre><p>Checking the image size:</p><pre>docker image ls | grep app</pre><p>Typical result:</p><pre>app-multistage   latest   ~7MB<br>app              latest   ~700MB</pre><p>Same application. Massively smaller image.</p><h3>Securing the Docker Image</h3><p>Once the image is small, the next step is making it <strong>secure by design</strong>.<br> A minimal image alone is not enough — how it is built and configured directly affects its security posture.</p><p>Below are four practical steps that significantly improve Docker image safety. Each step shows the <strong>full Dockerfile</strong> so the change can be clearly understood in context.</p><h3>1. Pin Base Image Versions</h3><p>Avoid using latest tags in production images.</p><pre>#########################<br># Stage 0: Build stage  #<br>#########################<br>FROM ubuntu:22.04 AS builder      # ← pinned version<br>ARG DEBIAN_FRONTEND=noninteractive<br>RUN apt-get update &amp;&amp; apt-get install -y golang-go<br>COPY app.go .<br>RUN CGO_ENABLED=0 go build -o /app app.go<br><br>#############################<br># Stage 1: Runtime stage    #<br>#############################<br>FROM alpine:3.12.1                # ← pinned version<br>COPY --from=builder /app /app<br>CMD [&quot;/app&quot;]</pre><p>Pinning base image versions provides:</p><ul><li>Reproducible builds</li><li>Predictable runtime behavior</li><li>Clear and traceable vulnerability reporting</li></ul><p>Upgrades then become <strong>explicit decisions</strong>, not surprises triggered by a rebuild.</p><h3>2. Do Not Run as Root</h3><p>By default, containers run as root — but in most cases, this is unnecessary.</p><p>A safer approach is to create a dedicated user in the runtime image and run the application under that user.</p><pre>#########################<br># Stage 0: Build stage  #<br>#########################<br>FROM ubuntu:22.04 AS builder<br>ARG DEBIAN_FRONTEND=noninteractive<br>RUN apt-get update &amp;&amp; apt-get install -y golang-go<br>COPY app.go .<br>RUN CGO_ENABLED=0 go build -o /app app.go<br><br>#############################<br># Stage 1: Runtime stage    #<br>#############################<br>FROM alpine:3.12.1<br>RUN addgroup -S appgroup \         # ← added<br> &amp;&amp; adduser -S appuser \           # ← added<br>    -G appgroup \<br>    -h /home/appuser<br>COPY --from=builder /app /home/appuser/app   # ← changed path<br>USER appuser                       # ← added<br>CMD [&quot;/home/appuser/app&quot;]</pre><p>Now, even if the application is compromised, the process does <strong>not</strong> have root privileges inside the container.</p><h3>3. Restrict Filesystem Write Access</h3><p>Many filesystem locations never need to be modified at runtime. Removing write access from system directories reduces the ability of an attacker to alter configuration files.</p><pre>#########################<br># Stage 0: Build stage  #<br>#########################<br>FROM ubuntu:22.04 AS builder<br>ARG DEBIAN_FRONTEND=noninteractive<br>RUN apt-get update &amp;&amp; apt-get install -y golang-go<br>COPY app.go .<br>RUN CGO_ENABLED=0 go build -o /app app.go<br><br>#############################<br># Stage 1: Runtime stage    #<br>#############################<br>FROM alpine:3.12.1<br>RUN chmod a-w /etc                 # ← added<br>RUN addgroup -S appgroup \<br> &amp;&amp; adduser -S appuser \<br>    -G appgroup \<br>    -h /home/appuser<br>COPY --from=builder /app /home/appuser/app<br>USER appuser<br>CMD [&quot;/home/appuser/app&quot;]</pre><p>This prevents runtime modification of system configuration and limits the impact of a successful compromise.</p><h3>4. Remove Shell Access</h3><p>Shells are extremely useful for attackers. If tools like sh, bash, or curl exist inside an image, they will almost certainly be used after a compromise. Once all setup steps are complete, shell binaries can be removed from the runtime image.</p><pre>#########################<br># Stage 0: Build stage  #<br>#########################<br>FROM ubuntu:22.04 AS builder<br>ARG DEBIAN_FRONTEND=noninteractive<br>RUN apt-get update &amp;&amp; apt-get install -y golang-go<br>COPY app.go .<br>RUN CGO_ENABLED=0 go build -o /app app.go<br><br>#############################<br># Stage 1: Runtime stage    #<br>#############################<br>FROM alpine:3.12.1<br>RUN chmod a-w /etc<br>RUN addgroup -S appgroup \<br> &amp;&amp; adduser -S appuser \<br>    -G appgroup \<br>    -h /home/appuser<br>RUN rm -rf /bin/*                  # ← added (remove shell access)<br>COPY --from=builder /app /home/appuser/app<br>USER appuser<br>CMD [&quot;/home/appuser/app&quot;]</pre><p>At this point, the image is fully finalized. It contains only the application binary and the minimal runtime environment required to execute it. As a result, even commands like:</p><pre>docker exec -it &lt;container-name&gt; sh</pre><p>will fail, because no shell exists inside the container. This significantly reduces post-compromise capabilities and enforces the idea that containers should run a <strong>single-purpose process</strong>, not behave like general-purpose systems.</p><h3>Final Thoughts</h3><p>A well-built Docker image should be:</p><ul><li>Small</li><li>Reproducible</li><li>Minimal</li><li>Explicitly configured</li><li>Deprived of unnecessary privileges and tools</li></ul><p>Docker makes it easy to build images — but <strong>building them correctly is a deliberate engineering choice</strong>.</p><p>Multi-stage builds, pinned versions, non-root execution, restricted filesystems, and minimal tooling are not advanced tricks.<br> They are simply <strong>good defaults</strong> for modern containerized applications.</p><p>If you treat your Docker image as production software — not just a packaging artifact — everything downstream becomes safer and easier to operate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c03f08250469" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Kubernetes RBAC and ServiceAccounts — A Practical Guide]]></title>
            <link>https://medium.com/@ysnhasturk/understanding-kubernetes-rbac-and-serviceaccounts-a-practical-guide-60aed603d956?source=rss-50050967942b------2</link>
            <guid isPermaLink="false">https://medium.com/p/60aed603d956</guid>
            <dc:creator><![CDATA[Yasin Hastürk]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 19:30:53 GMT</pubDate>
            <atom:updated>2025-11-05T19:30:53.317Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Kubernetes RBAC and ServiceAccounts — A Practical Guide</h3><p>Role-Based Access Control (RBAC) and ServiceAccounts (SAs) form the backbone of Kubernetes authorization. This guide will explain both concepts, how they work together, and how to apply them in real-world scenarios — including examples that connect permissions to specific ServiceAccounts.</p><h3>What is a ServiceAccount?</h3><p>A <strong>ServiceAccount</strong> in Kubernetes represents an identity used by applications, controllers, or CI/CD pipelines running inside the cluster. Unlike normal user accounts (managed via external identity providers), ServiceAccounts are <strong>namespace-scoped</strong> and managed by Kubernetes itself.</p><h3>Key Points:</h3><ul><li>Created per namespace: each ServiceAccount belongs to one namespace.</li><li>Pods can automatically use a ServiceAccount to authenticate with the API server.</li><li>Used in automation, controllers, and pipelines — e.g., a CI/CD pipeline deploying applications to a cluster.</li></ul><p>Create a ServiceAccount with:</p><pre>kubectl -n dev create serviceaccount app-bot</pre><p>You can view it using:</p><pre>kubectl -n dev get sa app-bot -o yaml</pre><p>The output will include an automatically generated secret (if using older Kubernetes versions) or a projected token for authentication.</p><h3>What is RBAC?</h3><p><strong>Role-Based Access Control (RBAC)</strong> defines <strong>who can do what</strong> within a Kubernetes cluster. It works by connecting subjects (users, groups, ServiceAccounts) to permission sets (Roles or ClusterRoles) using bindings (RoleBinding or ClusterRoleBinding).</p><p>RBAC is implemented via four main Kubernetes resources:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*9pBU-TjAK78oxnQTCVGZPA.jpeg" /></figure><h3>RBAC in Action — Example Scenarios</h3><p>Let’s walk through two common patterns that combine ServiceAccounts and RBAC.</p><h3>1️⃣ Read-Only Access Across the Cluster</h3><p>If you want certain ServiceAccounts to be able to <em>view</em> most Kubernetes resources without modifying them, use the built-in view ClusterRole.</p><pre>kubectl create clusterrolebinding app-view-access \<br>--clusterrole=view \<br>--serviceaccount=dev:app-bot</pre><p><strong>Explanation:</strong></p><ul><li>The view role is predefined by Kubernetes and allows listing, watching, and getting most resources.</li><li>The ClusterRoleBinding applies this permission cluster-wide.</li><li>The ServiceAccount app-bot in namespace dev can now view almost all resources.</li></ul><p>To verify:</p><pre>kubectl auth can-i list pods --as system:serviceaccount:dev:app-bot -A<br># yes</pre><h3>2️⃣ Granting Namespace-Limited Deployment Management</h3><p>You might want an application or pipeline to manage Deployments — but <strong>only in its own namespace</strong>.</p><p>Create a Role defining the allowed verbs:</p><pre>apiVersion: rbac.authorization.k8s.io/v1<br>kind: Role<br>metadata:<br>name: deployment-manager<br>namespace: dev<br>rules:<br>- apiGroups: [&quot;apps&quot;]<br>resources: [&quot;deployments&quot;]<br>verbs: [&quot;create&quot;, &quot;delete&quot;]</pre><p>Then bind it to your ServiceAccount:</p><pre>kubectl -n dev create rolebinding deployment-manager-binding \<br>--role=deployment-manager \<br>--serviceaccount=dev:app-bot</pre><p>Now test the permissions:</p><pre>kubectl auth can-i create deployments --as system:serviceaccount:dev:app-bot -n dev<br># yes<br>kubectl auth can-i delete deployments --as system:serviceaccount:dev:app-bot -n dev<br># yes<br>kubectl auth can-i update deployments --as system:serviceaccount:dev:app-bot -n dev<br># no</pre><h3>RBAC Combinations Explained</h3><p>Here’s a visual summary of how RBAC roles and bindings interact:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*s3kY1-PZAF244xmEQkLN0A.jpeg" /></figure><p><strong>Common Use Cases</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*7jw9W7K68WguUHFdtbizxQ.jpeg" /></figure><h3>Best Practices</h3><ul><li><strong>Principle of Least Privilege</strong>: Always start with minimal access and expand as needed.</li><li>Prefer <strong>Role + RoleBinding</strong> for namespace-specific permissions.</li><li>Regularly test with kubectl auth can-i.</li><li>Avoid giving ServiceAccounts cluster-admin unless absolutely necessary.</li><li>Store all RBAC definitions as version-controlled YAML manifests.</li></ul><h3>Final Thoughts</h3><p>RBAC and ServiceAccounts together provide a fine-grained, flexible way to secure Kubernetes clusters. By assigning ServiceAccounts with only the roles they need — and binding them properly — you can build secure automation, CI/CD pipelines, and application access patterns without overexposing your cluster.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60aed603d956" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Encrypt Secret Data at Rest in Kubernetes: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@ysnhasturk/how-to-encrypt-secret-data-at-rest-in-kubernetes-a-step-by-step-guide-337302fad821?source=rss-50050967942b------2</link>
            <guid isPermaLink="false">https://medium.com/p/337302fad821</guid>
            <dc:creator><![CDATA[Yasin Hastürk]]></dc:creator>
            <pubDate>Sat, 04 Oct 2025 07:00:21 GMT</pubDate>
            <atom:updated>2025-10-04T07:00:21.649Z</atom:updated>
            <content:encoded><![CDATA[<p>Securing sensitive data is one of the most critical aspects of running applications in Kubernetes. While Kubernetes provides the Secret resource to manage credentials, tokens, and keys, by default these secrets are only <strong>base64-encoded</strong> — which is <strong>not encryption</strong>.</p><p>This article walks you through <strong>how to enable encryption at rest for Kubernetes secrets stored in etcd</strong>, following the official Kubernetes documentation but with practical explanations and examples.</p><h3>Why Encrypt Secrets at Rest?</h3><p>By default, Kubernetes secrets are stored in <strong>etcd</strong> as plain base64-encoded data. Anyone with access to the etcd datastore can decode them easily:</p><pre>kubectl get secret my-secret -o yaml</pre><p>You’ll see something like this:</p><pre>data:<br>  key1: c3VwZXJzZWNyZXQ=</pre><p>Base64 decoding this value:</p><pre>echo &#39;c3VwZXJzZWNyZXQ=&#39; | base64 -d</pre><p>reveals the secret:</p><pre>supersecret</pre><p>That means if your etcd datastore is compromised, your sensitive data is exposed. To protect against this, Kubernetes supports <strong>encryption at rest</strong>: secrets are encrypted before being persisted to etcd.</p><h3>Step 1: Inspect How Secrets Are Stored in etcd</h3><p>Kubernetes stores data in etcd under paths like registry/secrets/default/my-secret. To explore etcd directly, install the client:</p><pre>sudo apt-get install etcd-client -y</pre><p>Then, query etcd:</p><pre>ETCDCTL_API=3 etcdctl \<br>   --cacert=/etc/kubernetes/pki/etcd/ca.crt   \<br>   --cert=/etc/kubernetes/pki/etcd/server.crt \<br>   --key=/etc/kubernetes/pki/etcd/server.key  \<br>   get /registry/secrets/default/{secret-name} | hexdump -C</pre><p>👉 Here, you’ll notice the secret is visible in plaintext. This is exactly what we want to fix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*acZwhpE-1-_t_UaEK0_cTA.jpeg" /></figure><h3>Step 2: Verify Encryption Is Not Enabled</h3><p>Check the kube-apiserver manifest:</p><pre>grep encryption-provider-config /etc/kubernetes/manifests/kube-apiserver.yaml</pre><p>If nothing is returned, encryption is <strong>not enabled</strong>. This is typical in kubeadm-based clusters unless explicitly configured.</p><h3>Step 3: Create an Encryption Configuration File</h3><p>Encryption providers supported by Kubernetes include:</p><ul><li>identity (no encryption)</li><li>aescbc</li><li>aesgcm</li><li>secretbox</li></ul><p>For strong encryption, we’ll use aescbc.</p><p>First, generate a 32-byte key:</p><pre>head -c 32 /dev/urandom | base64</pre><p>Create an encryption config file (/etc/kubernetes/enc/enc.yaml):</p><pre>apiVersion: apiserver.config.k8s.io/v1<br>kind: EncryptionConfiguration<br>resources:<br>  - resources:<br>      - secrets<br>    providers:<br>      - aescbc:<br>          keys:<br>            - name: key1<br>              secret: &lt;your-32-byte-key&gt;<br>      - identity: {}</pre><h3>Step 4: Update kube-apiserver Manifest</h3><p>Edit /etc/kubernetes/manifests/kube-apiserver.yaml and add:</p><pre>- --encryption-provider-config=/etc/kubernetes/enc/enc.yaml</pre><p>Also mount the config:</p><pre>volumeMounts:<br>  - mountPath: /etc/kubernetes/enc<br>    name: encryption-config<br>    readOnly: true<br><br>volumes:<br>  - name: encryption-config<br>    hostPath:<br>      path: /etc/kubernetes/enc<br>      type: DirectoryOrCreate</pre><p>Save the file — the kube-apiserver will restart automatically. Verify the option is active:</p><pre>ps aux | grep kube-apiserver | grep encryption-provider-config</pre><h3>Step 5: Test Encrypted Secrets</h3><p>Create a new secret:</p><pre>kubectl create secret generic my-secret-2 \<br>  --from-literal=key2=topsecret</pre><p>Now inspect etcd again:</p><pre>ETCDCTL_API=3 etcdctl \<br>   --cacert=/etc/kubernetes/pki/etcd/ca.crt   \<br>   --cert=/etc/kubernetes/pki/etcd/server.crt \<br>   --key=/etc/kubernetes/pki/etcd/server.key  \<br>   get /registry/secrets/default/{secret-name} | hexdump -C</pre><p>This time, you won’t see topsecret in plaintext. It’s encrypted! The output is similar to this (abbreviated):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*RA2NJxtkPF7PRYy-t26X4A.jpeg" /></figure><p>⚠️ Note: Old secrets remain unencrypted until updated. To re-encrypt existing secrets:</p><pre>kubectl get secrets --all-namespaces -o json | kubectl replace -f -</pre><h3>Conclusion</h3><p>With encryption at rest enabled, secrets in Kubernetes are now <strong>protected in etcd</strong>. This prevents attackers who gain access to etcd from reading sensitive data directly.</p><p>✅ Always:</p><ul><li>Enable encryption at rest in production.</li><li>Control access to etcd strictly.</li><li>Avoid committing secrets (even encoded ones) to Git.</li></ul><p>By following these steps, you’ve taken a major step toward <strong>hardening Kubernetes security</strong>.</p><h3>References &amp; Attribution</h3><ul><li>The official Kubernetes documentation “Encrypting Confidential Data at Rest” — how Kubernetes implements and configures at-rest encryption for secrets and API data. <a href="https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/">Kubernetes</a></li><li>Kubernetes docs sections on encryption providers, configuration ordering, and migration. <a href="https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/">Kubernetes</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=337302fad821" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Docker with Jenkins: A Simple Example]]></title>
            <link>https://medium.com/@ysnhasturk/using-docker-with-jenkins-a-simple-example-d95652b620f3?source=rss-50050967942b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d95652b620f3</guid>
            <dc:creator><![CDATA[Yasin Hastürk]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 13:51:07 GMT</pubDate>
            <atom:updated>2024-03-03T13:51:07.011Z</atom:updated>
            <content:encoded><![CDATA[<p>Docker has become a popular tool for software development and deployment. It allows developers to package their applications into lightweight, portable containers that can be easily run on any machine.</p><p><strong>Benefits of using Docker with Jenkins:</strong></p><p>Increased efficiency: Docker can help to streamline the software development process by automating the build, test, and deployment of applications. This can free up developers to focus on writing code and improving the quality of their applications.</p><p>Improved reliability: Docker containers are isolated from each other and the underlying host system. This helps to ensure that applications will run consistently regardless of the environment they are deployed in.</p><p>Greater portability: Docker containers can be easily moved between different environments, such as development, staging, and production. This makes it easy to test and deploy applications in a variety of environments.</p><p>Enhanced security: Docker containers can be used to isolate applications from each other and the underlying host system. This can help to improve the security of applications.</p><p>Overall, Docker can be a valuable tool for teams that are looking to improve the efficiency, reliability, portability, and security of their software development process.</p><p>To implement the usage of Jenkins with Docker through a simple example, follow the steps below:</p><p><strong>Step 1: Install Docker Pipeline Plugin</strong></p><p>Use Jenkins with Docker by downloading the required plugin. Navigate to Dashboard -&gt; Manage Jenkins -&gt; Plugins -&gt; Search for “docker pipeline” -&gt; click INSTALL.</p><p>This will enable the Docker Pipeline plugin in Jenkins, allowing you to integrate Docker functionality into your Jenkins pipelines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6f00jb9GrMVIll8XAyNxUg.jpeg" /></figure><p><strong>Step 2: Configure Docker on Jenkins Agent Node</strong></p><p>Install Docker on the server that will be used as the agent node with the following commands:</p><pre>sudo dnf install docker -y #installs Docker on your system and automatically downloads all dependencies.)<br>sudo systemctl start docker  (starts the Docker service and allows it to run in the background.)<br>sudo systemctl enable docker (enables the Docker service to start automatically at system boot. )<br>sudo usermod -a -G docker ec2-user (adds the ec2-user user to the Docker group and allows this user to run Docker commands. )<br>sudo usermod -a -G docker Jenkins (adds the jenkins user to the Docker group and allows this user to run Docker commands. )</pre><p>These steps ensure that Docker is installed, configured to listen on the specified port, and ready to be used as an agent node for Jenkins.</p><p><strong>Step 3: Create Jenkins Pipeline Job with Docker Integration</strong></p><p>In this step, we’ll create a new Jenkins pipeline job with Docker integration:</p><ol><li><em>Go to the Jenkins Dashboard.</em></li><li><em>Click on New Item in the left-hand menu.</em></li><li><em>Enter the name for the new item: </em><em>jenkins-docker-pipeline.</em></li><li><em>Choose the project type as Pipeline and click OK.</em></li><li><em>Pipeline Configuration:</em></li></ol><ul><li><em>Description: My pipeline.</em></li><li><em>Pipeline &gt; Definition: pipeline script from SCM.</em></li><li><em>SCM: Git.</em></li><li><em>Repository URL: </em><a href="https://github.com/yasindevops/medium-jenkins-docker.git"><em>https://github.com/yasindevops/medium-jenkins-docker.git</em></a><em>.</em></li><li><em>Branch Specifier: main.</em></li><li><em>Script Path: Jenkinsfile.</em></li></ul><p><em>5. Click Save &amp; Apply to create the Jenkins pipeline job.</em></p><p>Now, you have set up a Jenkins pipeline that fetches the pipeline script from the specified Git repository <a href="https://github.com/yasindevops/medium-jenkins-docker.git">https://github.com/yasindevops/medium-jenkins-docker.git</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*t5Ac56qEfbYEyCnB91RZ2w.jpeg" /></figure><p><strong>Step 4: Inspect the jenkinsfile.</strong></p><ol><li><strong><em>Agent Section:</em></strong></li></ol><pre>agent {<br>    docker { image &#39;maven:3.8.6-openjdk-11-slim&#39; }<br>}</pre><p>This section specifies the environment in which the pipeline will run. In this case, it uses a Docker image based on Maven version 3.8.6 and OpenJDK version 11 with a slim Linux distribution. The pipeline will run inside a Docker container with this specified image.</p><p><strong><em>2. Stages Section:</em></strong></p><pre>stages {<br>    stage(&#39;Build Application&#39;) {<br>        steps {<br>            sh &#39;mvn clean package&#39;<br>        }<br>        post {<br>            success {<br>                echo &quot;Now Archiving the Artifacts.....&quot;<br>                archiveArtifacts artifacts: &#39;**/*.war&#39;<br>            }<br>        }<br>    }<br>}</pre><p>The stages section defines the different stages of the pipeline. In this case, there is one stage named ‘Build Application.’</p><p>Inside the ‘Build Application’ stage, there is a single step that executes the Maven build command: mvn clean package.</p><p>The post section contains a success block that will be executed after the stage completes successfully. In this block, it echoes a message and archives artifacts (WAR files in this case) using the archiveArtifacts step.</p><p><strong><em>3. Conclusion:</em></strong></p><p>This Jenkinsfile describes a simple pipeline that builds a Maven-based Java application using a specified Docker image and archives the resulting WAR files upon a successful build. This is a basic structure, and depending on the project requirements, additional stages for testing, deployment, and other tasks can be added to the pipeline.</p><p><strong>Step 5: Build and Inspect Jenkins Pipeline Output</strong></p><ol><li>Go back to the Jenkins Dashboard.</li><li>Locate the newly created Jenkins pipeline job: jenkins-docker-pipeline.</li><li>Click on the job to open its details page.</li><li>On the left-hand menu, click on Build Now to initiate the pipeline build. This action will trigger the Jenkins pipeline, and you can follow these steps to inspect the output.</li><li>Once the build is initiated, click on the build number under the “Build History” section to view the console output. The console output provides detailed information about each stage of the pipeline, including the Docker-related steps, Maven build process, and any post-build actions.</li><li>Monitor the console output for any errors or warnings. Ensure that each stage completes successfully.</li><li>Look for the “Now Archiving the Artifacts…..” message in the console output, indicating the successful archiving of artifacts.</li><li>If the build is successful, check the “Artifacts” section on the job details page to verify that the WAR files are archived.</li></ol><p><strong>Conclusion:</strong></p><p>Integrating Docker with Jenkins offers significant advantages in streamlining software development and deployment. Docker’s lightweight, portable containers automate the build, test, and deployment processes, allowing developers to focus on coding and improving application quality.</p><p>The isolation of Docker containers ensures consistent application performance across various environments, enhancing reliability. Their portability facilitates easy movement between development, staging, and production environments, supporting efficient testing and deployment.</p><p>Additionally, Docker’s security features, such as container isolation, contribute to improved application security.</p><p>In this tutorial, we covered the essential steps for Docker and Jenkins integration through a simple example. By installing the Docker Pipeline Plugin, configuring Docker on the agent node, and creating a Jenkins pipeline, teams can lay the foundation for more complex CI/CD workflows.</p><p>As you embark on your DevOps journey, leveraging Jenkins and Docker will unlock the full potential to enhance the efficiency, reliability, portability, and security of your software development process. Best of luck in your DevOps endeavors!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d95652b620f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>