<?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 Pramodh Kumar M on Medium]]></title>
        <description><![CDATA[Stories by Pramodh Kumar M on Medium]]></description>
        <link>https://medium.com/@pramodhm112?source=rss-e1df5bff44a7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9rYJ8N_Y5yJzu-kctmYSRw.jpeg</url>
            <title>Stories by Pramodh Kumar M on Medium</title>
            <link>https://medium.com/@pramodhm112?source=rss-e1df5bff44a7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:55:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pramodhm112/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[Mastering Linux Kernel Internals]]></title>
            <link>https://pramodhm112.medium.com/mastering-linux-kernel-internals-6517b7655df4?source=rss-e1df5bff44a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6517b7655df4</guid>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[cgroup]]></category>
            <category><![CDATA[namespaces]]></category>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Pramodh Kumar M]]></dc:creator>
            <pubDate>Tue, 06 Jan 2026 14:20:38 GMT</pubDate>
            <atom:updated>2026-01-06T14:20:38.733Z</atom:updated>
            <content:encoded><![CDATA[<h3>Linux Kernel Internals: A Comprehensive Guide for DevOps Beginners</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9z1F-R23tTUELLcODZ8kHg.png" /><figcaption>Linux Kernel Internals</figcaption></figure><h3>Introduction</h3><p>Welcome to this comprehensive guide on <strong>Linux kernel internals</strong>. This manual is designed for DevOps engineers who are comfortable with Linux basics and cloud/container concepts, but who may not have much exposure to how the Linux kernel works under the hood.</p><p>We will take a tutorial-like approach, breaking down complex systems into digestible explanations with real-world analogies, hands-on examples, and callout tips. By the end, you should have a solid understanding of the major subsystems of the Linux kernel and why they matter in modern DevOps and cloud-native environments.</p><p><strong>Why learn kernel internals as a DevOps engineer?</strong> In containerized and cloud systems, the Linux kernel is the foundational layer that provides isolation, resource management, networking, and security. Technologies like Docker, Kubernetes, and many cloud services <em>leverage kernel features, </em>often invisibly to work their magic. By understanding kernel internals, you can better troubleshoot performance issues, tune systems, harden security, and generally <strong>become a power user of Linux</strong> rather than treating it as a black box.</p><blockquote><strong><em>Did You Know?</em></strong><em> The Linux kernel was originally created by Linus Torvalds in 1991 </em>as a hobby project<em>, but it has since grown to run on everything from embedded devices to </em><strong><em>all of the world’s top 500 supercomputers</em></strong><em>. Linux now powers a huge percentage of servers, cloud infrastructure, smartphones (Android), and more. It’s essentially the backbone of the modern internet!</em></blockquote><p>We will start with the basics, what the kernel is and how it differs from user space, then gradually dive into processes and threads, memory management, containers (cgroups &amp; namespaces), filesystems, networking, device drivers, security mechanisms, cutting-edge features like eBPF, the boot process, and tools for observing and debugging the system. Each section builds on the previous ones, but you can also treat this as a reference and jump to topics of interest.</p><p>Throughout the guide, look out for <strong>“Pro Tips”</strong>, <strong>“Did You Know?”</strong> trivia, and <strong>“Common Pitfalls”, </strong>these callout boxes provide additional insight, practical advice, or warn about gotchas that engineers often encounter. We’ve also included <strong>Checkpoint Quizzes</strong> at the end of major sections so you can test your understanding. Answers are provided to help you verify your knowledge.</p><p>Let’s begin our journey at the most fundamental level: understanding the separation between <em>user space</em> and <em>kernel space</em> in Linux.</p><h3>Kernel Space vs User Space</h3><p>One of the most important concepts in any operating system is the distinction between <strong>user space</strong> and <strong>kernel space</strong>. In Linux (and other modern OSes), the CPU enforces different privilege levels. The <strong>kernel</strong> runs in a privileged mode (often called <em>ring 0</em> on x86 CPUs), whereas normal applications run in a restricted mode (<em>ring 3</em> for user programs). This separation provides <strong>memory protection and stability, </strong>a buggy application can’t directly crash the whole system because it can’t arbitrarily poke at kernel memory or hardware.</p><ul><li><strong>Kernel Space:</strong> This is the memory region and execution context for the kernel and its extensions. The kernel has full access to all hardware and memory. It can execute privileged CPU instructions and manage system resources. Think of the kernel as the “master” that <em>bridges software and hardware, </em>it manages processes, memory, device drivers, filesystems, networking, etc., with <em>complete authority</em>. If something runs in kernel space, it effectively <em>is</em> part of the operating system core.</li><li><strong>User Space (User Land):</strong> This refers to the memory and execution context for normal programs (like your shell, web server, database, etc.). Code running in user space <strong>cannot directly access hardware or memory outside its own address space</strong>. If it wants to do so (read a file, send network data, etc.), it must ask the kernel via a <strong>system call</strong> (we’ll cover those next). User space is like a sandboxed playground: each process gets its <em>own virtual address space</em> and is isolated from other processes by default. Crashing a user program may lose that program’s work, but it won’t crash the whole OS.</li></ul><p>The boundary between user space and kernel space is critical for security and stability. User programs can’t (directly) harm each other or the system because the kernel is policing access to resources. The kernel, running in ring 0, can do anything, so keeping user code out of ring 0 unless necessary is the whole point.</p><p><strong>How do user programs interact with the kernel?</strong> They must <strong>transition to kernel mode</strong> by making a <strong>system call</strong>. A system call is like <em>calling a service</em> that the kernel provides (e.g., “open this file for me” or “send this data over the network”). When a user program makes a syscall, the CPU switches from user mode to kernel mode, the kernel performs the requested work, then switches back to user mode and returns the result.</p><blockquote><strong><em>Analogy:</em></strong><em> Imagine the kernel as a library’s librarian (with keys to every room), and user programs as visitors. Visitors can’t enter staff-only areas or locked rooms (hardware, other processes’ memory, etc.). If they need a book from a locked room, they ask the librarian at the front desk (make a system call). The librarian (kernel) checks permissions and then either fulfills the request or denies it. The visitors themselves are never given the keys, they rely on the librarian.</em></blockquote><p>This design drastically increases security. For example, if a malware program runs as a normal user, it cannot <em>directly</em> tamper with kernel memory or other processes, it’s confined to user space. Only through vulnerabilities (e.g., a buggy system call implementation) could it potentially escalate privileges, which is why careful kernel development and minimal exposure are important.</p><p><strong>Performance consideration:</strong> The separation does incur overhead when switching between user and kernel mode. A system call involves a context switch (though a very fast one, on the order of microseconds or less). We’ll see later how tools like strace can show these transitions. Modern CPUs and OSes also provide optimizations (like <strong>vDSO</strong> and fast syscall instructions) to minimize this overhead.</p><blockquote><strong><em>Common Pitfall:</em></strong><em> Don’t confuse </em>root (admin) user<em> with </em>kernel mode<em>. Even if you run a process as root, it’s still running in </em><strong><em>user space</em></strong><em> (ring 3). Root has </em>privileges<em> that let it request more dangerous actions from the kernel, but it cannot bypass the kernel. A root-run program can ask the kernel to do privileged things (mount filesystems, load modules, etc.), but it’s still subject to kernel enforcement. Only the kernel (and things running in kernel context) execute in ring 0.</em></blockquote><p>To summarize, <strong>user space is where your applications run, kernel space is where the OS core runs</strong>. They interact via controlled mechanisms (syscalls, interrupts, etc.). This division is fundamental to everything that follows.</p><h3>Checkpoint Quiz: User vs Kernel Space</h3><ol><li><strong>True or False:</strong> A normal application running as a regular user can directly access hardware devices if it needs to.</li><li>What happens when a user-space program wants to perform an operation like reading a file or sending data over the network?</li><li>Why is it beneficial for stability that user programs run in a separate space from the kernel?</li></ol><p><strong>Answers:</strong></p><ol><li>False: user-space apps cannot directly access hardware or arbitrary memory; they must go through the kernel for such access.</li><li>2. It makes a <strong>system call</strong>, which switches the CPU to kernel mode so the kernel can perform the operation on the program’s behalf.</li><li>3. Because if a user program crashes or misbehaves, it won’t crash the whole system, the kernel isolates and protects processes from each other, and itself, improving overall stability and security.</li></ol><h3>System Calls: The Interface Between User and Kernel</h3><p>When a process in user space needs the kernel to do something privileged, it uses a <strong>system call (syscall)</strong>. System calls are the <em>gateways</em> into the kernel. You can think of them as a predefined set of <em>functions provided by the kernel</em> (actually, they’re not normal function calls, but the analogy works) that user programs can invoke.</p><p>In Linux, common system calls include things like open() (open a file), read(), write(), fork() (create a new process), execve() (execute a new program), socket() (create a network socket), and so on. In fact, pretty much any interaction with hardware or OS resources goes through a syscall. For example, when you call C library functions like printf or fopen, those will eventually invoke syscalls (write for output, or open for opening a file) under the hood.</p><p><strong>How system calls work (under the hood):</strong> System calls are <em>not</em> normal function calls, a user program can’t just jump into kernel code due to the privilege separation. Instead, CPUs provide a special instruction to transition to kernel mode. On x86_64 Linux, for example, the syscall instruction is used (older 32-bit used an int 0x80 software interrupt). When this instruction executes, the CPU switches to kernel mode (ring 0), jumps to a predefined entry point in the kernel, and the kernel then dispatches to the appropriate syscall handler.</p><p>Each system call is identified by a <strong>number</strong>. For instance, read() might be syscall number 0, write() number 1, etc., on a given architecture. Parameters to the syscall (file descriptors, buffer pointers, sizes, etc.) are passed in CPU registers as part of the syscall interface. The kernel has a syscall table – essentially an array of function pointers indexed by syscall number. When a syscall is invoked, the kernel uses the number to find the corresponding kernel function, executes it, and then returns the result to user space.</p><p>Here’s a simplified flow of a system call (e.g., read):</p><ol><li>User program calls the C library read(fd, buf, count).</li><li>The C library (glibc) prepares the syscall number for read (e.g., maybe 0) and places the arguments (fd, buf pointer, count) in the appropriate registers, then executes the CPU syscall instruction.</li><li>CPU switches to kernel mode and jumps to the kernel’s syscall entry point.</li><li>Kernel saves the current register state (since it’s going to clobber registers) and identifies which syscall was requested (by the number).</li><li>The kernel syscall dispatcher calls the actual kernel function that implements sys_read. This function in the kernel will ultimately copy data from a file (or device) into the buffer in user memory. The kernel has access to user memory, but it uses special functions to safely copy to/from user space (ensuring the user addresses are valid).</li><li>When the kernel function is done (say it read 100 bytes from disk into the buffer), it returns. The kernel restores registers, switches the CPU back to user mode, and the read call in the user program finally returns with the number of bytes read.</li></ol><p>From the user’s perspective, read() behaved like a normal function call that took some time to execute. Under the hood, it was a trap into the kernel and back. This mechanism is quite fast but not free – a syscall has more overhead than a regular function call because of the mode switch and safety checks. Thus, very performance-sensitive software tries to avoid unnecessary syscalls (for example, doing buffered reads/writes rather than tiny one-byte reads in a loop, because each read is a syscall).</p><blockquote><strong><em>Did You Know?</em></strong><em> Linux provides around </em><strong><em>380+ system calls</em></strong><em> on modern 64-bit systems (the exact number can vary by kernel version). You can see the list on your system by reading the manual page </em><em>man 2 syscalls or looking at </em><em>/usr/include/asm/unistd_64.h for syscall numbers. These cover everything from process control to filesystem operations, networking, device management, and more.</em></blockquote><p>A great way to observe system calls is to use the strace tool. <strong>strace</strong> intercepts and logs all system calls made by a process. This is incredibly useful for debugging. For example, if a program is hanging, strace can show if it’s stuck on a particular syscall (like waiting for input, or a filesystem lock). As an illustration, let’s trace a simple command like ls /tmp:</p><pre>$ strace -f ls /tmp</pre><p>This will print a log of each syscall ls makes. You might see something like:</p><pre>execve(&quot;/bin/ls&quot;, [&quot;ls&quot;, &quot;/tmp&quot;], ...)    = 0<br>brk(NULL)                               = 0x55b2c2234000<br>openat(AT_FDCWD, &quot;/tmp&quot;, O_RDONLY|O_DIRECTORY|O_CLOEXEC) = 3<br>getdents64(3, 0x7ffe1a5c8c80, 32768)     = 104<br>close(3)                                = 0<br>...<br>write(1, &quot;file1.txt\n&quot;, 10)              = 10<br>...<br>exit(0)                                 = ?</pre><p><em>(Shortened for brevity.)</em> This shows ls executed (execve), opened the /tmp directory (using the openat syscall), read directory entries (getdents64 is the syscall to read directory contents), then wrote output to file descriptor 1 (stdout), etc. We can see every interaction with the system.</p><p><strong>Key takeaways about syscalls:</strong></p><ul><li>System calls are the only official entry into kernel code (aside from things like hardware interrupts). If you want the kernel to do something, you <em>must</em> invoke a syscall (or be a kernel module, which is essentially running in kernel space already, more on that later).</li><li>The kernel carefully validates all syscall arguments because it’s being asked to do work on behalf of user space. For example, if a pointer to memory is passed, the kernel must verify that it is a valid user address and not pointing to kernel memory or swapped out, etc., before reading/writing to it.</li><li>After finishing the work, the kernel returns a result or error code. In Linux, most syscalls return -1 and set an errno variable on error, or some non-negative result on success (like number of bytes read, process ID, etc.).</li><li>From a DevOps perspective, knowing about syscalls can help in troubleshooting (using strace to see what a hung process is doing, for instance) and performance tuning (minimizing costly syscalls in performance-critical paths).</li></ul><blockquote><strong><em>Pro Tip:</em></strong><em> If you suspect a program is failing due to missing permissions or files, run it under </em><em>strace. For example, </em><em>strace -e openat,access -f your_program will show file access attempts. It’s often quicker than adding tons of debug logs. You might catch an error like “ENOENT” (file not found) or “EACCES” (permission denied) on a certain config file, immediately revealing the issue.</em></blockquote><p>Now that we understand syscalls as the mechanism to cross from user land to kernel land, let’s move on to how the kernel handles processes and threads, the <em>entities</em> that make those syscalls.</p><h3>Process and Thread Management</h3><p><strong>Processes</strong> are fundamental units of execution in Linux. A process is essentially an instance of a running program with its own isolated memory space. <strong>Threads</strong> are like lightweight processes that share the same memory space within a process. Linux kernel management of processes and threads is often collectively referred to as <strong>task management</strong>, since internally Linux doesn’t make a big distinction, each thread is just a “task” with its own scheduling context.</p><p>Let’s break it down:</p><ul><li><strong>Process:</strong> A process in Linux has its own virtual memory (distinct address space), one or more threads of execution, and various kernel-managed resources (open file descriptors, network sockets, etc.). When you run a program (say /usr/bin/python), the kernel creates a new process for it. Each process gets a unique PID (process identifier).</li><li><strong>Thread:</strong> A thread is a path of execution within a process. Multiple threads in the same process share the <em>same</em> memory and resources, which makes inter-thread communication easier (they can read/write to the same memory) but also introduces the need for synchronization (to avoid race conditions). In Linux, threads are often created via the pthread library or languages’ threading support, and under the hood they are created using the clone() system call with specific flags (to indicate sharing memory, file descriptors, etc.). Each thread also gets a unique thread ID (which for most intents and purposes is like a PID, indeed Linux threads are often called “lightweight processes” and identified by a PID in the kernel task list).</li></ul><p><strong>Process Creation (fork/exec):</strong> In Linux (and UNIX), creating a new process is traditionally done with the <strong>fork()</strong> system call. fork() creates a <em>duplicate</em> of the current process (the child is an almost exact copy of the parent, including memory contents). Afterwards, typically the child will call execve() to replace its memory space with a new program. This two-step fork+exec mechanism might seem odd, but it’s powerful (the parent can set up the child’s environment before the new program runs, etc.). Many high-level environments abstract this (for example, the system() library call or shell &amp; just do fork+exec behind the scenes).</p><p>Linux also provides more advanced calls like clone() (which is what the C library uses to implement threads or container-like isolation by choosing which resources to share) and vfork() (an optimization where the parent is paused until the child execs).</p><blockquote><strong><em>Did You Know?</em></strong><em> On modern systems, </em><em>fork() uses a technique called </em><strong><em>copy-on-write</em></strong><em> for efficiency. This means the child initially shares the parent’s memory pages, and only if either process modifies a page does the kernel actually copy that page. This makes </em><em>fork() very fast and memory-efficient when followed by </em><em>exec(), because in that case the child won’t touch most of the parent’s memory (it will exec a new program). So don’t be scared by the idea of copying “all of a process’s memory”, Linux is smart about it.</em></blockquote><p><strong>Threads vs Processes in Kernel:</strong> Linux does not have a separate “thread” entity at the kernel level, it uses the same task struct for a thread or a process. The difference is simply that threads are tasks that share certain resources with their “parent” (like memory). When you create a thread via pthread_create(), it ends up calling clone() with flags to share the parent process’s memory space (and thus we consider it a thread). Each thread still has its own stack, CPU registers, program counter, etc., so the scheduler can run threads independently on different CPUs if available.</p><p><strong>Context Switching:</strong> Whether dealing with processes or threads, the kernel’s scheduler switches between tasks to give the illusion of parallelism (or to achieve actual parallelism on multi-core systems). A <strong>context switch</strong> is when the kernel stops running one task and starts running another. During a context switch, the kernel must save the state of the current task (CPU registers, program counter, etc.) and load the state of the next task. This happens very frequently (hundreds or thousands of times per second on each CPU, depending on load and scheduling policy). We will discuss scheduling in the next section, but from a process perspective, just know that context switches are normal, each process gets its time slice eventually.</p><p><strong>Process States:</strong> In Linux, a process (or thread) can be in various states: running on CPU, ready to run (runnable but waiting for a CPU timeslice), sleeping (waiting for I/O or some event), etc. You might have seen these states in commands like ps (R for running, S for sleeping, D for uninterruptible sleep, Z for zombie, etc.). The kernel transitions tasks through these states. For example, when a process calls read() on a socket and there is no data, the kernel will put the process to sleep (state S) until data is available, at which point it will wake it up (make it runnable R).</p><p>A <strong>zombie</strong> process (Z state) is one that has exited but not yet been waited on by its parent, it’s a tiny stub just holding an exit status. Zombies aren’t actively running; they should be collected by the parent via wait(). If you see many zombies, it usually means the parent process isn’t reaping its children properly.</p><blockquote><strong><em>Common Pitfall:</em></strong><em> Forgetting to handle child processes can lead to zombies. In a long-running service (like a web server) that spawns child processes, if you don’t </em><em>wait() on children (or set them to be reaped automatically), you can accumulate zombie processes. They don’t consume CPU, but they do tie up an entry in the process table. Use proper process reaping (or tools like </em><em>prctl(PR_SET_CHILD_SUBREAPER) or double-fork) to avoid this.</em></blockquote><p><strong>Inter-process Communication (IPC):</strong> Since processes are isolated, they often need to communicate. Linux provides many IPC mechanisms: pipes, signals, shared memory (which involves special syscalls to set up shared regions), message queues, semaphores, etc. For DevOps, a common IPC you’ll see is signals (e.g., sending a SIGTERM to gracefully stop a process) or pipes (connecting outputs of one process to inputs of another in shell). These are largely built on kernel capabilities (for example, a pipe is implemented by the kernel as an in-memory buffer with two file descriptors).</p><p>In containerized environments, you might deal less with manual process spawning and more with orchestrators (like Kubernetes) managing processes, but understanding this helps when you debug things like why a container process might not be terminating (perhaps not handling signals properly from PID 1, etc.).</p><p>To sum up, Linux process management provides a flexible framework: <strong>fork</strong> to create new processes, <strong>clone</strong> to create threads or container-like processes, and a variety of mechanisms for synchronization and communication. The kernel keeps each process’s resources separate unless explicitly shared.</p><h3>Checkpoint Quiz: Processes and Threads</h3><ol><li>What is the key difference between two separate processes and two threads of the same process in terms of memory?</li><li>Which system call is commonly used to create a new process by duplicating the calling process? What call is typically used immediately after to load a new program into that new process?</li><li>True or False: In Linux, threads are completely different objects in the kernel compared to processes.</li></ol><p><strong>Answers:</strong></p><ol><li>Separate processes have <strong>separate memory spaces</strong> (each has its own virtual address space), while threads of the same process <strong>share the same memory space</strong> (they can access the same variables, heap, etc.) along with other resources like open files.</li><li>The classic combo is fork() followed by execve() (or a variant like execvp). fork() clones the process, and execve() replaces the child’s memory with a new program. (Linux also provides clone() for finer control and vfork() as an optimization.)</li><li>False. Internally, Linux handles threads and processes in a unified way – a thread is just a special process that shares resources with another. The kernel’s scheduler treats them similarly (each thread has its own schedulable entity).</li></ol><h3>CPU Scheduling and Context Switching</h3><p>Now that we have multiple processes and threads (tasks) in our system, the <strong>scheduler</strong> in the Linux kernel decides which task runs on each CPU core at any given time. <strong>Scheduling</strong> is the policy and mechanism by which the kernel allocates CPU time to tasks. <strong>Context switching</strong> is the act of the kernel switching the CPU from running one task to another.</p><p>Linux uses a scheduling algorithm to be fair (or meet other criteria like real-time constraints). For regular processes (not real-time), the default scheduler in Linux for many years was the <strong>Completely Fair Scheduler (CFS)</strong>, which as of 2023 has been replaced by a new algorithm called EEVDF in the latest kernels. The concepts, however, are similar.</p><p><strong>Completely Fair Scheduler (CFS) basics:</strong> CFS tries to allocate CPU time such that each runnable task gets an equal share of the processor over the long term (adjusted for weights/priorities). Internally, CFS maintains a <strong>red-black tree</strong> (self-balancing binary search tree) of all runnable tasks, ordered by a value called <strong>vruntime</strong> (virtual runtime). The task at the <em>leftmost node</em> of the tree is the one that has had the least CPU time so far (normalized by priority). CFS will pick that task to run next, because it is “most owed” CPU time. As that task runs, its vruntime increases. Eventually it may no longer be the leftmost (if it used more time than others), and the scheduler will preempt it and switch to whichever task is now leftmost (the next most starving task).</p><p>This approach ensures a “fair” distribution of CPU: each task makes progress, and if one task uses a lot of CPU, it will accumulate vruntime and others will get priority to run for a while. The name “completely fair” comes from this goal of proportional fairness. (Real-time tasks are handled by a different scheduler class with fixed priorities and possibly different algorithms, but we won’t delve into RT scheduling here, since typical DevOps workloads use normal scheduling.)</p><p><strong>Context switching details:</strong> When the scheduler decides to switch tasks (either the running task used up its time slice or a higher priority task became runnable, etc.), the kernel performs a context switch. This involves: saving the current task’s CPU registers, program counter, and other state into its <strong>task_struct</strong>; updating memory management registers (so the new task’s memory mappings become active); loading the new task’s saved state into the CPU; and jumping to the new task’s saved program counter. From the new task’s perspective, it just resumed from whatever it was doing (it might not even know it was suspended). All this happens in a few microseconds or less, modern CPUs even have features to help with context switching performance (like hardware multi-threading and optimized cache usage, etc.), but context switches still have a cost (mostly in terms of CPU cache disturbance and the overhead of the kernel code to do the switch).</p><blockquote><strong><em>Pro Tip:</em></strong><em> To see the scheduling in action, you can use the </em><em>perf tool or ftrace. For example, </em><em>perf sched record and </em><em>perf sched latency can show you scheduling latencies, i.e., how long tasks wait before running. Another neat trick: on a Linux system, you can look at </em><em>/proc/&lt;PID&gt;/sched to see scheduling info for a process, including how much runtime it has had and its scheduling statistics.</em></blockquote><p>Linux scheduling is preemptive and priority-based. Normal tasks have a <strong>dynamic priority</strong> handled by CFS using niceness (the nice value from -20 to 19, where lower nice means higher priority scheduling). You can adjust a process’s niceness to influence how much CPU it gets relative to others. For example, a CPU-intensive background job could be given a nice value of 19 (very low priority) so that it yields more often to other tasks.</p><p><strong>Multicore considerations:</strong> On a system with multiple CPU cores, Linux uses symmetric multiprocessing (SMP) scheduling. There is a run queue per CPU (actually per scheduling domain), and the scheduler tries to keep tasks on the same CPU (for cache warmth) but will rebalance if some CPUs are idle while others are overloaded. This is known as load balancing. CFS handles this by periodically moving tasks between run queues so all CPUs are utilized.</p><p><strong>Voluntary vs involuntary context switches:</strong> A task can lose the CPU in two main ways, <strong>voluntarily</strong> or <strong>involuntarily</strong>. Voluntary context switches happen when a task blocks or yields (for example, it’s waiting on I/O, or it explicitly calls something like sched_yield). Involuntary context switches happen when the scheduler preempts a task because its timeslice expired or a higher-priority task woke up. Both cases are normal. You can see counts of these by looking at cat /proc/&lt;PID&gt;/status which shows voluntary and non-voluntary context switch counts for a process.</p><p><strong>Process states during scheduling:</strong> When a task is not running, it’s either ready (runnable) or sleeping. The scheduler only deals with runnable tasks. Tasks that are waiting for I/O or other events are marked sleeping and are not on the run queue until the event happens (then they get woken up and placed on the run queue).</p><blockquote><strong><em>Did You Know?</em></strong><em> The Linux scheduler (CFS) has historically used a red-black tree to sort tasks by their virtual runtime. In late 2023, the kernel introduced a new scheduler called </em><strong><em>EEVDF</em></strong><em> (Earliest Eligible Virtual Deadline First) which aims to provide even better fairness and latency. This is a reminder that the kernel is always evolving. However, the high-level behavior remains “make sure every task gets its fair share of CPU”. Unless you work on kernel development or real-time tuning, you won’t typically notice the scheduler change, your programs just run.</em></blockquote><p>From a DevOps perspective, you might interact with the scheduler when you: adjust nice levels of processes, set CPU affinity (pin processes to specific cores using taskset or cgroups CPU sets), or tune kernel scheduling parameters for special workloads. For example, on a database server you might isolate heavy background maintenance tasks to certain CPUs and leave others for latency-sensitive tasks.</p><p>In summary, the Linux kernel scheduler ensures all processes/threads get time on the CPU according to a fair (or priority-respecting) policy, and it handles the low-level saving and loading of task contexts during switches. This crucial component maximizes CPU utilization while balancing competing workloads.</p><h3>Checkpoint Quiz: Scheduling</h3><ol><li>What data structure does the Completely Fair Scheduler (CFS) use to keep track of runnable tasks and pick the next task to run, and what key metric does it sort by?</li><li>True or False: In a context switch, the kernel must save the state of the currently running task before switching to the next task.</li><li>If you have a CPU-bound process that you want to have less impact on system responsiveness, what nice value could you give it (high number or low number)?</li></ol><p><strong>Answers:</strong></p><ol><li>CFS uses a <strong>time-ordered red-black tree</strong> of runnable tasks, sorted by each task’s <em>virtual runtime</em> (vruntime). The task with the smallest vruntime (least CPU time used so far) is picked to run next.</li><li>True. The kernel saves the current task’s CPU registers (and other CPU state) and then loads the saved state of the next task, this is the essence of a context switch.</li><li>You would give it a <strong>high nice value</strong> (like nice +10 or +19 which is the lowest scheduling priority) to make it yield more CPU time to other processes. High “niceness” means the process is courteous and lets others run first.</li></ol><h3>Memory Management in Linux</h3><p>Memory management is one of the most complex and important components of the kernel. It covers how the kernel virtualizes memory, manages physical RAM, handles swapping, and provides memory to processes in a safe and efficient manner. As a DevOps engineer, understanding memory management helps you interpret things like RAM usage, buffering/caching, and out-of-memory (OOM) situations on your systems.</p><h3>Virtual Memory and Paging</h3><p>Linux, like virtually all modern OSes, uses <strong>virtual memory</strong>. This means each process <em>thinks</em> it has a large, contiguous chunk of memory (its address space), starting from address 0 up to a very high address. In reality, the actual <em>physical</em> RAM is shared between processes, and each process’s address space is mapped to physical memory (or to disk, or not even backed by anything until needed) under the hood by the kernel. The unit of memory management is typically a <strong>page, </strong>on most architectures a page is 4 KB in size (though larger pages exist).</p><p>Each process has a <strong>page table</strong> that maps its virtual addresses to physical addresses (or to special markers for things like not-yet-allocated memory or swapped-out memory). The CPU’s memory management unit (MMU) uses this page table to translate addresses automatically on each memory access. If a process tries to access an address that isn’t mapped, it triggers a <em>page fault</em> and the kernel then decides how to handle it (e.g., by allocating a new page, or by killing the process if it was an invalid access).</p><p><strong>Paging</strong>: The kernel can move infrequently used pages of memory to <strong>swap</strong> (disk or other storage) to free up physical RAM for active use. This is called paging or swapping out. When those pages are needed again, they are read back into RAM (swapped in). This allows the illusion that you have more memory than physically installed (virtual memory can be larger than physical memory). However, swapping is slow (since disk is much slower than RAM), so heavy swapping usually indicates memory pressure and can degrade performance.</p><p>Linux memory is managed in zones (for different memory ranges) and uses allocators (like the buddy allocator) to allocate and free physical pages. But at a high level, as a user, you mostly care about how much memory is used, free, cached, etc. The command free -h gives a summary of memory usage, including how much is used by the OS for caching.</p><p><strong>Process memory layout:</strong> Each process’s virtual memory is divided into segments, typically text (the code), data (static variables), heap (dynamically allocated memory via malloc), stack (for function call frames), and memory-mapped areas (which are used for shared libraries, files mapped in memory, etc.). Tools like pmap or /proc/&lt;PID&gt;/maps can show the memory map of a process.</p><blockquote><strong><em>Did You Know?</em></strong><em> On 64-bit Linux, the virtual address space is enormous (like 128 TB or more), so running out of </em>virtual<em> address space is not a concern. However, running out of </em>physical<em> memory (RAM) is. The kernel by default allows processes to allocate more virtual memory than physical memory (assuming not all of it will be used at once), this is called </em><strong><em>memory overcommit</em></strong><em>. It can be tuned via </em><em>/proc/sys/vm/overcommit_memory. If overcommit is relaxed, the kernel might let you </em><em>malloc far more memory than the system can back – only when you actually use it (touch the pages) will it allocate and potentially run into issues.</em></blockquote><h3>The Page Cache and Buffers</h3><p>One of the biggest consumers of memory in a healthy Linux system is often the <strong>page cache</strong>. The page cache is the kernel’s disk cache, it uses otherwise free memory to cache contents of files and block devices. For example, if you read a file from disk, the kernel will cache that file’s data in RAM (so subsequent reads can be served from memory, which is much faster). This cache will be transparently used on future file reads. Likewise, when you write to a file, data may be buffered in memory (and written to disk later in the background).</p><p>The output of free might show something like “used” memory is high, but a lot of that may be “buff/cache”. That memory is <em>technically available</em> if applications need it – the kernel will shrink the cache if needed to supply RAM to programs. So, <strong>cached memory is not “leaked” or lost</strong>; it’s utilized to improve performance. This is why a Linux system often tries to use most of your RAM – if nothing else needs it, it might as well cache disk I/O.</p><p>You can observe cache behavior with commands like vmstat or by reading /proc/meminfo. For example, /proc/meminfo will show lines for Cached:, Buffers:, etc., indicating how much memory is used for caching file data and other buffers.</p><p>If you ever need to drop caches (for testing or emergency), you can do so by writing to /proc/sys/vm/drop_caches (e.g., echo 3 &gt; /proc/sys/vm/drop_caches frees pagecache and slab objects). But generally, you let the kernel manage this.</p><blockquote><strong><em>Common Pitfall:</em></strong><em> Interpreting Linux memory usage incorrectly. People often see “90% memory used” and panic, not realizing much of that is caches that will be freed if applications need more memory. Always check the “available” memory (which accounts for reclaimable cache). As a rule of thumb, Linux likes to keep free memory low and make use of it for caching. Free memory is wasted memory!</em></blockquote><h3>Memory Allocation and Overcommit</h3><p>When a process calls malloc(), the C library will request memory from the kernel as needed (often via the brk system call to expand the heap, or via mmap for large allocations). The kernel doesn’t immediately give physical pages for that memory; it typically just extends the process’s virtual address space. Actual physical pages are provided “on demand” when the process first accesses a new page (page fault -&gt; allocate physical page). This lazy allocation is part of the overcommit strategy.</p><p>Linux can operate in different overcommit modes (controlled by vm.overcommit_memory). By default (mode 0), it heuristically decides if an allocation request should be allowed. Mode 1 allows nearly everything (even ridiculous overcommit), and mode 2 is strict – don’t overcommit beyond swap + some percentage of RAM. If the kernel cannot honor memory allocations (in strict mode) it will make malloc fail (or more accurately, sbrk/mmap fail). In default mode, usually allocations succeed and only actual usage may hit a failure (in the form of OOM killer if truly out of memory).</p><h3>The Out-of-Memory (OOM) Killer</h3><p>What happens if memory is exhausted? If physical RAM (and swap, if any) are totally used up and the kernel cannot find or free any memory to satisfy a demand, the system is in trouble. At this point the <strong>OOM Killer</strong> kicks in. The OOM killer’s job is to <em>kill one or more processes</em> to free up memory and save the system as a whole.</p><p>The kernel will choose a process (or multiple) that are using a lot of memory (and perhaps less critical, though the heuristic isn’t perfect) and kill them to free memory. It often logs messages about “Out of memory: Kill process 1234 (myprogram) score, oom_adj…” etc. It calculates an OOM score for each process, roughly based on how much memory it’s using, with some adjustments (a process can be adjusted via /proc/&lt;PID&gt;/oom_score_adj). The process with the highest score is a prime candidate to kill. The OOM killer tries to avoid killing important system processes (it gives root-owned process a slight bonus, etc.), but it may still kill something like your database or app if it’s the biggest consumer.</p><p>From a DevOps angle, OOM killer events are important to notice, they indicate your system didn’t have enough memory for what it was doing. In container environments, each container often has its own cgroup memory limit, and hitting that will trigger an OOM kill <em>within that cgroup</em> (usually the container’s process is killed and you see “OOMKilled” in Kubernetes, for example). Monitoring and logs can alert you to OOM kills.</p><p>You can find the OOM kill log in dmesg or /var/log/kern.log. Each process has an /proc/&lt;PID&gt;/oom_score and oom_score_adj you can tune if needed (for example, you might protect certain processes by setting oom_score_adj to a large negative value so they’re less likely to be killed).</p><blockquote><strong><em>Did You Know?</em></strong><em> The Linux OOM killer assigns a “badness” score to each process based on its memory usage (among other factors). By reading </em><em>/proc/&lt;PID&gt;/oom_score you can see the current score – higher means more likely to be killed if OOM. Setting </em><em>/proc/&lt;PID&gt;/oom_score_adj to -1000 will essentially </em><strong><em>immunize</em></strong><em> a process from OOM killer (this is what happens for processes like </em><em>init (PID 1) by default). Use with caution – immunizing everything defeats the purpose; but it’s useful if there’s a critical process you never want the OOM killer to take out.</em></blockquote><h3>Memory and DevOps: What to Monitor</h3><p>Key metrics/commands to know:</p><ul><li>free -m or free -h: quick glance at used/free memory and swap.</li><li>/proc/meminfo: detailed breakdown of memory usage (including caches, buffers, swap usage, hugepages, etc.).</li><li>vmstat 1: shows memory stats and also paging (si/so for swap in/out) in real-time.</li><li>top or htop: can sort processes by memory usage (RES = resident set (physical memory used), VIRT = total virtual).</li><li>In containers, use docker stats or Kubernetes metrics to see memory usage vs limits.</li></ul><p>Also, be aware of features like <strong>Transparent Huge Pages (THP), </strong>THPs are 2MB large pages that Linux can use to reduce overhead in TLB (Translation Lookaside Buffer). THP is usually enabled by default on many distros and helps with memory-intensive workloads, but in some cases (databases like MySQL) it’s recommended to disable it for predictability. THP can be toggled via /sys/kernel/mm/transparent_hugepage/enabled.</p><p>Another kernel mechanism is <strong>NUMA (Non-uniform memory access)</strong> for multi-socket servers, memory is closer to one CPU socket vs another. The kernel tries to allocate memory on the same node as the CPU that’s using it (NUMA locality). If you’re running on big iron, there are NUMA controls (like numactl and /proc/sys/kernel/numa_balancing).</p><p>However, for most cloud and container uses, you deal with a single NUMA node (one VM or one socket) at a time, so it may not come up unless you intentionally use larger machines.</p><h3>Control Groups and Memory</h3><p>We will cover control groups in detail soon, but since memory is such a common resource to limit, it’s worth noting: With cgroups (v1 or v2), you can set memory limits on groups of processes. If a cgroup exceeds its memory limit, it will encounter an OOM situation <em>isolated to that cgroup</em>. The kernel will then either reclaim memory (if possible) or invoke the OOM killer to kill one of the processes in that cgroup (usually the one using the most memory or the one with the highest badness score). This is exactly how Kubernetes enforces container memory limits, if a container goes beyond its limit, the kernel OOM killer terminates it (usually the container’s main process), which Kubernetes then reports as OOMKilled.</p><p>As a DevOps engineer, when you see “OOMKilled” in Kubernetes, it means the process hit the cgroup memory limit. The solution might be to tune the application’s memory usage or increase the limit.</p><p>Now that we’ve covered how memory works, let’s test our understanding.</p><h3>Checkpoint Quiz: Memory Management</h3><ol><li>What is “virtual memory” and why don’t processes simply use physical memory addresses directly?</li><li>The free command on Linux shows a lot of memory under “buffers/cache”. Is that memory unavailable to applications? Explain briefly.</li><li>What does the OOM killer do when the system runs out of memory, and how does it decide which process to kill?</li></ol><p><strong>Answers:</strong></p><ol><li>Virtual memory is an <strong>abstraction layer</strong> where each process gets its own address space, which the kernel maps onto physical memory (and possibly swap) behind the scenes. This provides isolation (processes can’t see each other’s memory) and flexibility (the kernel can move memory around, use disk swap, etc., without processes knowing). Processes don’t use raw physical addresses because that would be insecure and inflexible, with virtual memory, the kernel maintains control and provides a consistent view to each process.</li><li>Memory in buffers/cache is actually being used to <strong>cache disk I/O</strong> (page cache) and other buffers. It <em>is available</em> to applications if needed, the kernel will drop cache to free memory for apps. In other words, cached memory improves performance but isn’t “tied up” permanently. So high buffers/cache is not a problem; it’s actually a good thing (better than having RAM sitting completely free).</li><li>The OOM killer frees up memory by <strong>terminating one or more processes</strong> when the system is critically low on memory. It calculates a score for each process (based on factors like RAM usage) and typically kills the process with the highest score (i.e., the one consuming the most memory, perhaps with some adjustments for root processes, etc.). The goal is to sacrifice one memory-hogging process to rescue the rest of the system.</li></ol><h3>Control Groups (cgroups)</h3><p>In a multi-tenant environment or anytime you want to manage resources per application, Linux <strong>Control Groups (cgroups)</strong> are the go-to mechanism. Cgroups allow the kernel to <strong>limit, prioritize, isolate, and account</strong> for resource usage (CPU, memory, I/O, etc.) of a group of processes. If you use Docker, Kubernetes, or systemd on your servers, you are already using cgroups heavily under the hood.</p><p><strong>What is a cgroup?</strong> Essentially, it’s a grouping of processes that the kernel applies certain resource policies to. Cgroups are organized in a hierarchy (tree), you can have parent and child cgroups. Resources can be limited or accounted at each level.</p><p>For example, you might have a cgroup for “BatchJobs” and set a memory limit of 2 GB on it, and put all your batch processing scripts’ processes in that cgroup. The kernel will ensure they collectively don’t use more than 2 GB; if they try, the OOM killer will target processes within that cgroup (and not touch others).</p><p><strong>Controllers:</strong> Cgroups come with various resource controllers (also called subsystems) for different resources: <strong>memory controller</strong> (limits memory, including swap), <strong>cpu controller</strong> (for CPU time shares and quotas), <strong>blkio (I/O) controller</strong> (limits disk I/O throughput or weight), <strong>pids controller</strong> (limits number of processes), <strong>net_cls/net_prio</strong> (to tag network packets or set priority), etc. In cgroups <strong>v1</strong>, each controller was mounted as a separate hierarchy (which got complicated when combining limits). In <strong>cgroups v2</strong> (unified hierarchy), there is one unified tree and all controllers mount there, which simplifies a lot of things and provides more consistent behavior.</p><p>Modern Linux systems (especially with systemd) often use cgroups v2 by default now (for example, RHEL 8/9, Ubuntu 22+, etc., and Kubernetes as of 1.25+ expects cgroup v2 on some distros). Cgroups v2 provides a single unified hierarchy and more sane semantics for how limits apply (e.g., memory.high vs memory.max, etc.).</p><p><strong>Basic usage example:</strong> cgroups can be managed via the cgroup filesystem interface (traditionally at /sys/fs/cgroup/). For instance, on a cgroups v1 system, you might do:</p><pre># Create a new cgroup in the memory controller hierarchy<br>mkdir /sys/fs/cgroup/memory/mygroup<br># Set a memory limit of 100MB<br>echo 104857600 &gt; /sys/fs/cgroup/memory/mygroup/memory.limit_in_bytes<br># Add a process to this cgroup by writing its PID<br>echo 12345 &gt; /sys/fs/cgroup/memory/mygroup/cgroup.procs</pre><p>After this, process 12345 (and any children it spawns) will be constrained to 100MB of memory. If it tries to use more, it’ll either get blocked or trigger OOM killer <em>within that cgroup</em> (killing one of its processes). Other processes not in “mygroup” are unaffected by this limit.</p><p>In practice, you often don’t manage cgroups by hand. Instead, systemd places each service in a cgroup (under /sys/fs/cgroup/system.slice/&lt;service name&gt;.service/ for example) and you can configure resource limits via systemd unit files (e.g., MemoryMax=, CPUQuota= in a .service file). Docker and Kubernetes also create cgroups for containers and pods – that’s how docker run --memory 500m works: Docker puts the container’s process in a cgroup with a 500MB memory.limit.</p><p><strong>Cgroups v1 vs v2 key differences:</strong> In cgroups v1, each resource had its own hierarchy, so you could put a process in different cgroups for different controllers (which was confusing). It also had inconsistent interfaces and sometimes surprising interactions. Cgroups v2 unified this: one process belongs to exactly one cgroup (which has all controllers applied). Controllers in v2 have more sane behavior in hierarchical enforcement. For example, in v2, if a parent cgroup has a CPU limit, all children share that limit (it’s truly hierarchical). In v1, some things were not perfectly hierarchical.</p><p>Another improvement in v2 is the interface files are more consistent and often more powerful (like memory.max is a hard limit, memory.high is a soft limit that triggers pressure but not immediate OOM, etc.). Also v2 added new features like <strong>pressure stall information (PSI)</strong> to see resource pressure (e.g. how often tasks are delayed due to lack of CPU or memory).</p><p>From a DevOps standpoint, the main conceptual understanding is: <strong>cgroups isolate and limit resources per group of processes.</strong> This is what containers use to pretend they have limited resources. For example, if you run a container with --cpus=1, Docker will create a cgroup that limits CPU for that container to 1 CPU worth of time (could still run on multiple cores, but overall usage is capped to 1 core’s worth). If you set memory and swap limits, those are enforced by cgroups.</p><p>You can observe cgroup info on a running process by checking /proc/&lt;PID&gt;/cgroup – it will list which cgroup (path) the process is in for each controller. On a typical systemd system, if you run cat /proc/$$/cgroup in your shell, you might see lines indicating you’re in some slice like user.slice or such.</p><blockquote><strong><em>Pro Tip:</em></strong><em> Use the </em><em>systemd-cgls command to view the cgroup hierarchy in a tree form, and </em><em>systemd-cgtop to see resource usage per cgroup (like a top-like view by cgroup). This can quickly show you which services or containers are using the most CPU/memory on a system managed by systemd.</em></blockquote><p><strong>Real-world example (Kubernetes):</strong> Suppose you have a pod with two containers, each limited to 100m CPU (0.1 core) and 256Mi memory. Kubelet (the node agent) will create a parent cgroup for the pod, then child cgroups for each container under it, applying the limits. If one container tries to use more than 256Mi, the kernel will OOM kill it (its process) but leave other containers alone. If it tries to use more CPU than 0.1 core worth, the scheduler will throttle it (it will still run but get fewer cycles, effectively it might see its processes go into “runnable but not running” state frequently as they wait for their next timeslice due to cgroup quota).</p><p><strong>Accounting and monitoring:</strong> Cgroups also let you <em>measure</em> usage easily. Each controller has usage counters (e.g., memory.current for current usage, cpu.stat for CPU time consumed, etc.). This is how tools like Docker stats or Kubernetes metrics work under the hood.</p><p>It’s worth noting that cgroups do not secure the system by themselves (they’re about resource control, not access control). For security isolation, namespaces (discussed next) and other mechanisms are used. But for DoS prevention and QoS, cgroups are fantastic.</p><h3>cgroups v2 Quick Recap (if needed):</h3><ul><li>Single hierarchy, typically mounted at /sys/fs/cgroup/. Under that, you’ll see some directories like system.slice, user.slice, etc., if systemd is using it.</li><li>Controllers are enabled or disabled in sub-cgroups automatically, but one must mount the unified cgroup and ensure controllers are delegated when using manually.</li><li>You interact via files like cpu.max, memory.max, etc. For instance, echo 50m &gt; mygrp/memory.max to limit to 50 MB, or echo &quot;20000 100000&quot; &gt; mygrp/cpu.max to set a 20ms per 100ms CPU quota (i.e., 20% of a CPU).</li><li>There’s also memory.swap.max for swap limits, and pids.max for max process count, etc.</li></ul><p>But those details are more for low-level tuning. If you just remember that cgroups are how Linux partitions resources, you’ve got the main point.</p><p>With cgroups explained, let’s test knowledge and then move on to namespaces (which complement cgroups by isolating <em>what</em> you can see rather than <em>how much</em> you can use).</p><h3>Checkpoint Quiz: Control Groups</h3><ol><li>What is the primary purpose of Linux control groups (cgroups)?</li><li>Name two types of resource constraints you can enforce with cgroups.</li><li>If a process in a cgroup exceeds the memory limit set on that cgroup, what will happen?</li></ol><p><strong>Answers:</strong></p><ol><li>Cgroups are used to <strong>limit, isolate, and account for resource usage</strong> of groups of processes. In other words, they allow the system to allocate resources (CPU, memory, I/O, etc.) to sets of processes and ensure they don’t exceed those allocations, as well as measure their usage.</li><li>You can enforce many kinds of limits; examples: <strong>CPU</strong> (cpu shares or quotas, e.g., only 20% of CPU or weighted fair sharing), <strong>Memory</strong> (limit to X bytes of RAM, with optional swap limit), <strong>Disk I/O</strong> (throttle read/write bandwidth or set weights), <strong>Number of processes (PIDs)</strong>, and others like <strong>network bandwidth</strong> (indirectly with tc, or tagging packets via net_cls). Any two of these would be a correct answer.</li><li>If a process tries to use more memory than the cgroup’s limit, the kernel’s OOM killer will <em>confine its actions to that cgroup</em>: it will likely <strong>kill one or more processes in the cgroup</strong> (usually the one using the most memory) to bring usage under the limit. The rest of the system (outside that cgroup) is not affected, which is exactly the benefit of cgroup isolation. In effect, the process (or one of the processes in that group) gets killed with an OOM signal.</li></ol><h3>Linux Namespaces</h3><p>If cgroups are about <em>how much</em> resources processes can use, <strong>namespaces</strong> are about <em>what a process can see</em> in terms of system resources. Linux <strong>namespaces</strong> provide isolation of various global resources, so that a group of processes can have its own view of the system, separate from other processes. Namespaces are a cornerstone of containerization, they’re what make a container feel like it’s running on its own separate system, even though it shares the same kernel.</p><p>There are several types of namespaces in Linux, each isolating a different resource domain:</p><ul><li><strong>PID Namespace:</strong> Isolates process IDs. Each PID namespace has its own PID 1, PID 2, etc. If you’re inside a PID namespace, you only see processes within that namespace (and child namespaces). This is how containers can have processes with PIDs that start at 1 (the init of the container) without colliding with host PIDs. The kernel maps those to different PIDs on the host. When a process in a nested PID namespace does a getpid(), it gets the pid in that namespace. The host (outside) can see all processes (e.g., via the host PID namespace which is the root), but inside the namespace you can’t see host processes.</li><li><strong>Mount Namespace:</strong> Isolates the set of mounted filesystems. Processes in different mount namespaces can have different views of the filesystem hierarchy. For example, inside a container’s mount namespace, you might have / pointing to some container-specific root filesystem, which is just a bind-mount or chroot-like environment. Mounting or unmounting in one namespace doesn’t affect another. This is how Docker gives each container its own filesystem view (by setting up an overlay filesystem and then using a mount namespace to make that the root).</li><li><strong>UTS Namespace:</strong> Isolates host name and domain name (UNIX Time-sharing System namespace). This allows each container to have its own hostname (so uname -n returns a different value inside container). It’s a simple namespace but useful for that “separate host” illusion.</li><li><strong>Network Namespace:</strong> Isolates network devices, IP addresses, ports, etc. Each network namespace has its own set of network interfaces, routing table, firewall rules, /proc/net, etc. If processes are in different network namespaces, they can have the same IP without conflict (because they are on different logical “net stacks”), and one can’t see the other’s sockets. By default, processes are in the initial (host) net namespace. Docker typically creates a new net namespace for each container, and then connects it via a virtual Ethernet pair to the host or a bridge. You can also have containers share the host network (in which case they just don’t get a new net ns).</li><li><strong>IPC Namespace:</strong> Isolates inter-process communication resources like System V IPC and POSIX message queues. So container A and container B could both have a shared memory segment with the same ID, but since they’re in different IPC namespaces, they won’t actually interfere. If you’re not using SysV IPC or message queues, this isn’t very visible, but it’s part of container isolation.</li><li><strong>User Namespace:</strong> Isolates user and group IDs. This one is special, it allows processes to have a different notion of UID inside the namespace vs outside. For example, inside a user namespace, a process can have <em>effective UID 0 (root)</em>, but the kernel can map that to a non-root UID outside. This is how unprivileged containers can run “as root” inside without actually being root on the host. User namespaces also allow unprivileged processes to create other namespaces (normally only root can create most namespaces). However, user namespaces can be a bit tricky and some distros (like older Ubuntu) disable unprivileged creation by default for security concerns (it’s enabled via /proc/sys/kernel/unprivileged_userns_clone).</li><li><strong>Cgroup Namespace:</strong> This one (introduced later) isolates the view of the cgroup mounts (so that containers can’t see the actual cgroup hierarchy of the host, and their /proc/self/cgroup appears root’d). It doesn’t prevent the cgroup limits from affecting you; it just makes it look like you’re in your own root cgroup. It’s mostly about tidying up what /proc reports.</li></ul><p>So those are 7 types: pid, mount (also called mnt), uts, net, ipc, user, and cgroup. Each type can be unshared independently (with some constraints – e.g., you can’t create a user namespace without also having a new set of UIDs/GIDs mapping).</p><p><strong>Using namespaces:</strong> The unshare command (and the underlying unshare(2) system call) can create new namespaces for a process. For example:</p><pre>sudo unshare --uts --ipc --net --pid --mount -r /bin/bash</pre><p>This would create new UTS, IPC, NET, PID, and mount namespaces and then execute a bash shell in them, with -r (or --map-root-user) mapping your user to root inside (requires user namespace if unprivileged, but with sudo we’re root so it’s fine). Inside that shell, you’d see a new PID 1 (the shell itself), a new network stack (no network interfaces except loopback unless you set them up), an independent mount table, etc. You could even mount things without affecting the host. When you exit that shell, those namespaces are destroyed (they exist as long as at least one process is in them).</p><p>Let’s do a simpler example explained in steps (similar to the tutorial referenced earlier):</p><pre># Show current hostname (in initial UTS namespace)<br>hostname <br># Suppose it prints &quot;hostmachine&quot;</pre><pre># Create a new UTS namespace and spawn a shell in it<br>sudo unshare --uts /bin/bash<br><br># Inside this new shell (now in new UTS ns):<br>hostname isolated-box   # change hostname to &quot;isolated-box&quot;<br>exec bash               # re-exec bash so prompt picks up new hostname<br>hostname                # now prints &quot;isolated-box&quot; inside<br><br># Open another terminal on the host:<br>hostname   # this will still show &quot;hostmachine&quot;<br><br># So, inside the namespace we had a different hostname that didn&#39;t affect host.<br>exit       # leaving the unshare shell</pre><p>This demonstrates UTS namespace isolation. Similarly, with a PID namespace (sudo unshare --pid --fork bash), your bash in new ns thinks it’s PID 1. If you run ps aux inside vs outside, you’ll see different sets of processes.</p><p>Namespaces can be combined, typically containers use a new IPC, UTS, net, mount, pid, and sometimes user namespace together for full isolation. Docker for instance by default uses all of those (user namespace is optional and off by default in many setups for compatibility reasons, but can be enabled).</p><p><strong>Why are namespaces useful for DevOps?</strong> Even outside of containers, you can use them for isolation in testing. For example, you can simulate a mini-environment: spin up a process with a clean mount namespace to test an installer, or use network namespaces to simulate networks or test networking scripts without affecting your host config (e.g., you could create two network namespaces and connect them with a veth pair to simulate two hosts). Tools like ip netns make managing network namespaces easier by giving them names and persisting them.</p><p>Kubernetes uses namespaces in a nuanced way: all containers in a pod share the same network namespace (so they can talk via localhost) and the same IPC and UTS by default (though you can configure some isolation). But pods do not share mount namespace (each container’s filesystem is separate, except for shared volumes). Also, Kubernetes doesn’t typically use user namespaces (at least not by default yet), so root in a container is root on host in terms of capability, this is why running as root in container is still sensitive.</p><p>Systemd also uses some namespaces for its services (for security, e.g., PrivateTmp for giving a service its own /tmp via a new mount namespace, ProtectHostname using UTS ns, etc.).</p><p><strong>Key point:</strong> Namespaces isolate <em>global resources</em>, making a set of processes appear as if they have their own instance of that resource. Combine all the namespaces and you basically have a container (plus cgroups to limit resources, plus maybe seccomp/apparmor/selinux for security).</p><p>One thing namespaces do <em>not</em> virtualize is the kernel itself, containers still share the same running kernel, which is why they are more lightweight than VMs but also why certain things (like kernel version or some sysctls) are shared among containers.</p><blockquote><strong><em>Did You Know?</em></strong><em> The first namespace implemented in Linux was the mount namespace (in 2002, Linux 2.4.19). Others followed: PID namespace around 2007 (2.6.24), network namespace around 2005–2007, user namespace by 2013, etc. By the time Docker came out in 2013, all the key namespaces were in place. Docker’s big innovation was combining them with cgroups through a high-level tool. Namespaces were originally inspired by older systems like FreeBSD Jails and Solaris Zones, but Linux’s user namespace (allowing non-root to create containers) is a particularly powerful feature that not all earlier systems had.</em></blockquote><h3>Checkpoint Quiz: Namespaces</h3><ol><li>Which Linux namespace would you use if you want to give a process a completely different view of the filesystem (so that changes to mounts don’t affect the host)?</li><li>How do network namespaces affect the network interfaces visible to a process?</li><li>True or False: With user namespaces, a process can have UID 0 (root) inside the namespace while the kernel treats it as an unprivileged UID outside.</li></ol><p><strong>Answers:</strong></p><ol><li>The <strong>mount (mnt) namespace</strong> is used to isolate filesystem mount points. By using a new mount namespace, you can have a different set of mounted filesystems (e.g., your own / or a private /tmp) without affecting the host. This is heavily used in containers (each container typically runs in its own mount namespace).</li><li>Network namespaces give processes <strong>separate network stacks</strong>. That means a process in a new network namespace will by default only see a loopback interface and whatever interfaces you explicitly add to that namespace. It has its own IP addresses, routing table, firewall rules, etc. If two processes are in different network namespaces, they cannot directly see each other’s network traffic or interfaces. (You’d have to connect namespaces via veth pairs or similar to enable communication.)</li><li>True. User namespaces allow UID mapping. So you could have root (UID 0) inside, which is mapped to, say, UID 1000 outside. From inside, it looks like you’re root (you can do many privileged things <em>within that namespace</em>), but the kernel restricts operations that would affect outside the namespace. This provides a layer of safety – it’s how unprivileged containers can run “as root” internally without giving them real root power on the host.</li></ol><h3>Filesystems and Storage</h3><p>The Linux kernel has a unified <strong>Virtual File System (VFS)</strong> layer that provides a common interface for all filesystem types. This means whether you’re reading from an ext4 filesystem on a disk, a tmpfs in-memory filesystem, or even a network filesystem like NFS, the system calls (open, read, write, etc.) work the same. The VFS abstracts the filesystem implementations and presents a uniform API to user space.</p><p>Let’s break down some key filesystem concepts and components:</p><p><strong>VFS (Virtual Filesystem Switch):</strong> This is an in-kernel abstraction. It defines core concepts like <em>inode</em> (which represents a file object), <em>dentry</em> (directory entry, used in path resolution and caching), <em>file</em> (an open file handle), and operations on these (like inode-&gt;i_op-&gt;lookup for looking up a name in a directory to get an inode, etc.). When a system call like open(&quot;/path/to/file&quot;) is made, the VFS kicks in: it parses the path (using dentries and the directory structure), finds the corresponding inode for the file (asking the specific filesystem driver to do the lookup), and then creates a file structure to represent the open file (with associated file operations).</p><ul><li>The beauty of this is that multiple filesystems (ext4, XFS, NTFS via fuse, etc.) can coexist. The VFS doesn’t care if /dev/sda1 is ext4 and /dev/sdb1 is XFS; each filesystem driver registers with VFS (using a file_system_type structure) and implements the required operations. So when you mount a filesystem, the kernel associates that mount point with a filesystem driver. Then any calls that go to that mount point get dispatched to the appropriate driver functions via the VFS indirection.</li></ul><p><strong>Inodes and Directories:</strong> In many filesystems (especially Unix-like ones), an <strong>inode</strong> represents file metadata: permissions, owner, timestamps, and pointers to data blocks. Directories are typically special inodes that map names to inode numbers (or references). The VFS inode (struct inode) and dentry (struct dentry) are core structures in the kernel. The kernel maintains a <strong>dentry cache (dcache)</strong> of recently used directory entries to speed up path lookups. For instance, if you do open(&quot;/etc/hosts&quot;), the kernel will traverse / -&gt; etc -&gt; hosts. Each step uses dentries and inodes. If it’s done once, it may cache that, so subsequent opens of /etc/hosts or files in the same directory are faster (no actual disk lookup needed).</p><p><strong>Major Filesystem Types:</strong> Common on Linux are <strong>ext4</strong> (the default for many distros, successor to ext3/ext2), <strong>XFS</strong> (often default in RHEL), <strong>Btrfs</strong> (advanced features like snapshots, used in some distros or scenarios), <strong>FAT/NTFS</strong> (for compatibility with Windows drives, typically via separate drivers or fuse), <strong>NFS</strong> (network filesystem), <strong>CIFS/Samba</strong> (SMB protocol, network). Also pseudo-filesystems like <strong>procfs</strong> (/proc) and <strong>sysfs</strong> (/sys), which aren’t real storage but interfaces to kernel info.</p><ul><li><em>ext4:</em> Ext4 is a journaling filesystem (meaning it keeps a journal of changes to help recover from crashes). It supports large volumes, extended attributes, and many features (extents for file storage, etc.). It’s stable and generally good for most use cases.</li><li><em>XFS:</em> Very scalable, high performance with large files and parallel I/O. Often used on servers, especially with very large disks.</li><li><em>Btrfs:</em> Supports copy-on-write, snapshots, subvolumes, built-in RAID, etc. It’s feature-rich (like ZFS in some ways) but historically had some stability concerns in certain corner cases. Many improvements have been made, and it’s used in some container systems for snapshotting images, etc., and as default in a few distros (SUSE, Fedora Silverblue, etc.).</li><li><em>tmpfs:</em> This is an in-memory filesystem (backed by swap if needed). Mounted typically at /dev/shm or sometimes used for /tmp (if PrivateTmp in systemd or if distro chooses). Data here doesn’t persist after reboot.</li><li><em>procfs (</em><em>/proc):</em> Exposes process and kernel info (like /proc/meminfo, /proc/&lt;pid&gt;/...). It’s generated on the fly by kernel when read – not actual stored data.</li><li><em>sysfs (</em><em>/sys):</em> Exposes kernel device tree and settings. E.g., /sys/class/net/eth0/ has info about eth0. You can often configure things by writing to sysfs files. It’s also not real storage.</li><li><em>devtmpfs (</em><em>/dev):</em> Kernel-managed tmpfs that udev uses to create device nodes.</li><li><em>overlayfs:</em> A special filesystem that allows layering (we’ll discuss below for containers).</li></ul><p><strong>Block Devices and the I/O Stack:</strong> Disks (like /dev/sda) are represented in Linux as <strong>block devices</strong>. The kernel has a block layer that handles scheduling of reads/writes to block devices, caching (the page cache we discussed is heavily used in reading/writing files), and more. Device drivers for disks (like an SSD’s NVMe driver, or SATA driver) feed into this block layer.</p><ul><li>When you read a file from ext4 on /dev/sda1, ext4 will map that file’s offset to a particular block on the disk (say block number 123456). It then calls the block I/O layer to fetch block 123456 from the device /dev/sda. The block layer will check if that block is in the page cache (if recently read). If not, it will issue a request to the disk driver to read it. The disk driver interacts with hardware (e.g., send SCSI or NVMe commands), gets the data, and eventually the kernel fills the page cache and returns data to your process. Similarly for writes, the kernel may cache writes (write-back cache) and write to disk asynchronously shortly after (unless you fsync or mount with options like sync).</li><li>The block layer also handles things like I/O schedulers (which can reorder requests for efficiency). Modern NVMe often uses the “none” or “mq-deadline” scheduler, older HDD might use CFQ or deadline. The idea is to optimize disk head movement and such.</li></ul><p><strong>Device Mapper and LVM:</strong> The kernel’s device-mapper allows creating virtual block devices on top of real ones. This is used by LVM (Logical Volume Manager) to combine disks or partition them flexibly. It’s also used by encryption (dm-crypt/LUKS), RAID (mdraid or dmraid), etc. If you use LVM, you’ll have device nodes like /dev/mapper/vgname-lvname which correspond to a device-mapper device that might map to a portion of a physical disk.</p><p><strong>OverlayFS and Union Filesystems:</strong> OverlayFS is particularly relevant to DevOps in the context of containers. Docker uses OverlayFS to implement container image layers. <strong>OverlayFS</strong> allows you to take two directories, a “lower” (read-only) layer and an “upper” (read-write) layer and mount a unified view. When reading, the kernel checks the upper layer first; if a file exists there, it uses it, otherwise it falls back to the lower layer When writing, any new files or changes go to the upper layer. If a file is deleted, OverlayFS marks it as “whiteout” (usually as a character device entry in upper that tells it the file is removed, even though it might still exist in lower).</p><ul><li>This layering is how images work: each Docker image layer is a directory with some files. When you run a container, Docker mounts an overlay with multiple lower layers (stacked) and one upper layer (the container’s writable layer). This way, the container sees a single unified filesystem. If it writes new files or modifies files, those go to the upper layer (so the image layers remain untouched).</li><li>OverlayFS greatly saves space and time: multiple containers can share the same read-only image layers, and each just has its own diff. It also allows quick creation of containers (no need to copy all data, just mount the overlay).</li><li>For example, if Alpine base layer has /bin/ash, and my container doesn’t change it, it remains only in the lower. If my container writes /etc/hosts, that goes into the upper layer only for my container.</li><li>It’s a simplistic union filesystem but very effective and fast for this use case (it’s implemented in the kernel). Earlier union fs attempts (AUFS, UnionFS) were either out-of-tree or had issues; OverlayFS became the standard.</li></ul><p><strong>Network Filesystems:</strong> Linux supports NFS (common in enterprise for sharing files over network) and CIFS/SMB (for Windows shares). These can be mounted like any filesystem. Under the hood, instead of reading from disk, the driver will use network protocols to fetch data. For instance, an NFS read might result in the kernel’s NFS client sending an RPC to an NFS server to get the file data. Once retrieved, it’s cached similarly in RAM.</p><p><strong>Security features:</strong> Filesystem permissions (the classic owner/group/others rwx bits, plus extended ACLs and attributes) are enforced by the kernel on each file access. The kernel checks the process’s credentials (UID/GIDs, capabilities, etc.) against the inode’s metadata. There’s also SELinux or AppArmor which can add additional security checks on file access (but that’s another layer above).</p><p>Given this background, some <em>DevOps-relevant scenarios</em>:</p><ul><li>If an application is slow reading files, consider that it may be I/O bound. Tools like iotop show per-process I/O, and iostat shows device usage. Maybe the page cache helps, but once in a while if data isn’t cached, you hit disk. Understanding page cache explains why repeated reads get faster.</li><li>Container storage: If you use Docker, container filesystems often reside under /var/lib/docker/overlay2/ (for OverlayFS). Sometimes you might need to clean those up or move that to a bigger disk. Knowledge of overlay helps in understanding why you see multiple layer directories.</li><li>Mount points: It’s useful to know how to check what’s mounted (mount or /proc/mounts). Also, the concept of bind mounts (mount --bind olddir newdir) which just creates another view of an existing directory (commonly used to, say, put something into a container’s namespace or to expose something at two places).</li><li>If a drive fills up, you may need to inspect large files. Tools like df show free space <em>per filesystem</em>, which ties into mount points. E.g., if /var is a separate partition, a full /var won’t show up in df / but in df /var.</li><li><strong>Inodes exhaustion:</strong> Each ext4 filesystem has a fixed number of inodes. If you create millions of tiny files, you can run out of inodes (df -i shows inode usage). It’s not common but can happen. Solutions include reformatting with more inodes or cleaning files.</li><li><strong>Proc and sys troubleshooting:</strong> /proc and /sys are helpful in day-to-day admin. For example, /proc/sys/kernel/hostname is where the hostname lives (used by uname and UTS ns). Or /proc/sys/vm/swappiness controls how aggressively to swap.</li><li><strong>FUSE (Filesystem in Userspace):</strong> Tools like sshfs (mount over SSH) or cloud storage mounts use FUSE, which means a user-space daemon implements the FS and kernel passes requests to it. FUSE is great for flexibility, but slower than kernel FS.</li></ul><p>Alright, let’s quiz a bit:</p><h3>Checkpoint Quiz: Filesystems</h3><ol><li>What is the role of the Virtual File System (VFS) layer in Linux?</li><li>True or False: In Linux, every open file or directory is represented internally by an inode (with a unique inode number within its filesystem).</li><li>How does OverlayFS allow multiple filesystem layers to appear as one, and why is this useful for containers?</li></ol><p><strong>Answers:</strong></p><ol><li>The VFS provides an <strong>abstraction</strong> that allows multiple filesystem types to coexist and be accessed with the same system calls. It defines common structures (inode, dentry, file) and dispatches operations to the appropriate filesystem driver. Essentially, it is the glue between user-level operations (open, read, write, etc.) and the specific implementations of filesystems.</li><li>True. Each file or directory on a disk-based filesystem is associated with an inode structure (which holds metadata and pointers to data). The VFS inode represents that object in memory. Some special filesystems (like procfs) generate inodes on the fly, but conceptually yes, an inode is the internal representation of a file. (Directories are a special kind of file with entries mapping names to inode numbers).</li><li>OverlayFS merges a <strong>lower (read-only) layer and an upper (writable) layer</strong> so that they appear as a single unified filesystem. If a file exists in the upper layer, it overrides the lower. If not, the lower’s version is seen. Writes go to the upper layer. This is extremely useful for containers: the lower layers can be shared between containers (common base images) and remain read-only, while each container gets a tiny upper layer for its specific changes. It saves disk space and allows fast container startup (no need to copy the whole filesystem; just overlay it). Plus, when the container is removed, its changes are largely confined to the upper layer which can be discarded, leaving the base image layers intact for reuse.</li></ol><h3>Linux Networking Internals</h3><p>Networking in Linux is a vast topic, but we’ll focus on the kernel’s networking stack and how packets flow through it, as well as important components like interfaces, routing, and firewall (netfilter/iptables/conntrack). As a DevOps engineer, understanding these helps when configuring network settings, debugging connectivity issues, or tuning performance (and also in container orchestration, where virtual networks abound).</p><h3>Network Interfaces and Devices</h3><p>A <strong>network interface</strong> in Linux (as shown by ip link or ifconfig) represents a connection that can send/receive packets. This could be a physical NIC (like eth0, representing an Ethernet port) or a virtual interface (like lo for loopback, vethXXX for virtual Ethernet peer, wlan0 for WiFi, tun0 for a VPN tunnel, etc.).</p><p>The kernel treats network interfaces as devices that have a name, an IP configuration (managed by the IP layer), and drivers that handle the low-level transmission. Each interface has an associated <strong>link layer</strong> type (Ethernet, loopback, etc.).</p><p>Physical NICs have drivers that register a <strong>net_device</strong> structure in the kernel for each interface. When you assign an IP address to eth0 (like ip addr add 192.168.1.5/24 dev eth0), the kernel associates that IP with eth0.</p><p><strong>Loopback interface (</strong><strong>lo):</strong> This is a special software interface that just loops packets back to the local host. It always has IP 127.0.0.1 (and ::1 for IPv6). Services binding to localhost are reachable via this interface only.</p><p><strong>Virtual Ethernet (veth):</strong> This comes in pairs, two linked virtual NICs. If you send a packet out one, it immediately arrives on the other. This is used to connect network namespaces or containers: one end is in the container’s net namespace, the other in the host (or a bridge). Think of it like a patch cable connecting two virtual interfaces. Kubernetes uses veth pairs to connect pods to the cluster network (one end in pod, one in root namespace connected to a bridge or vswitch).</p><p><strong>Bridges:</strong> A Linux bridge (br0 etc.) acts like a virtual switch. You can enslave multiple interfaces to a bridge, and it will forward packets between them at Layer 2 (based on MAC addresses). Docker by default sets up a docker0 bridge; each container gets a veth to that bridge, and thus containers can reach each other via the bridge (just like a switch).</p><p><strong>Tunnels:</strong> Interfaces like tun0 or tap0 are for tunneling (Tun is IP point-to-point, Tap is Ethernet layer). VPNs often create a tun0 device; the VPN software reads/writes to that interface, and the kernel sees it as just another interface. For example, OpenVPN or WireGuard create such devices.</p><p><strong>MAC Addresses:</strong> At link layer, Ethernet interfaces have a MAC address. The kernel’s Ethernet drivers handle frames with source/dest MAC. The ARP protocol is used to map IP addresses to MAC addresses in a LAN (kernel manages an ARP cache per interface in IPv4; IPv6 uses NDP which is similar concept).</p><h3>Packet Flow and Routing</h3><p><strong>Routing</strong> is handled by the kernel’s IP stack. The kernel keeps a <strong>routing table</strong> (viewable via ip route). When an IP packet is to be sent, the kernel looks up the destination in the routing table to decide which interface to send out on and what next-hop to use.</p><p>For example, if you have 192.168.1.0/24 dev eth0 and default via 192.168.1.1 dev eth0, and you try to send to 8.8.8.8, the kernel will use the default route, send to gateway 192.168.1.1 out eth0. If you send to 192.168.1.50, it sees it’s local (same /24) and sends directly (with ARP to resolve 192.168.1.50’s MAC).</p><p>Inbound packets: when a packet arrives on an interface, the kernel decides if it’s for local delivery (destination IP matches one of the host’s IPs or a broadcast/multicast we listen to) or if it’s to be forwarded (the host is a router). If forwarding is enabled and configured (and netfilter doesn’t drop it), it will attempt to route it to the appropriate interface (and do things like decrement TTL, etc.).</p><p><strong>Netfilter and iptables:</strong> This is the Linux firewall system. Netfilter provides <strong>hooks</strong> at various points in the packet processing pipeline, where firewall rules (iptables/nftables) can decide to accept, drop, modify, or redirect packets. The classic iptables divides rules into tables and chains:</p><ul><li><strong>PREROUTING</strong> (for packets just as they come in, before routing decision),</li><li><strong>INPUT</strong> (for packets destined to local host, before they go to a local socket),</li><li><strong>FORWARD</strong> (for packets being routed through this host, not local),</li><li><strong>OUTPUT</strong> (for packets generated by local processes, before they leave the host),</li><li><strong>POSTROUTING</strong> (after routing decision, about to actually go out on interface).</li></ul><p>In iptables, there are tables: <strong>filter table</strong> (for filtering: rules in INPUT, OUTPUT, FORWARD chains), <strong>nat table</strong> (for network address translation, mainly PREROUTING for DNAT and POSTROUTING for SNAT), <strong>mangle table</strong> (for other packet modifications), <strong>raw table</strong> (for deciding not to track certain packets in conntrack), <strong>security table</strong> (for SELinux marking).</p><p>Netfilter’s connection tracking (<strong>conntrack</strong>) is a module that monitors connections (for protocols like TCP, UDP, ICMP). This allows stateful firewall rules, e.g., iptables can have a rule “-m state, state RELATED,ESTABLISHED -j ACCEPT” on INPUT to allow replies to outgoing connections. Conntrack keeps a table of active connections (viewable via conntrack -L if you have the tool). It’s also used in NAT, because when you port-forward, conntrack ensures replies go back to the right place.</p><p>For example, when you do iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE, the kernel will SNAT all outgoing packets on eth0 to use the host’s IP. Conntrack remembers the original source, so when a reply comes, it un-SNATs it back to the internal IP. This is how internet connection sharing works (common in home routers or Docker containers reaching internet via host).</p><p><strong>Connection tracking</strong> is critical in Kubernetes kube-proxy (iptables mode): Kubernetes sets up rules so that accessing a Service IP gets DNAT’ed to a pod’s IP, and conntrack ensures subsequent packets of that connection go to the same pod (for session affinity by default).</p><p>From a performance perspective, iptables with very large rule sets can slow down (each packet goes through the chains until match). Nftables is a newer replacement that handles large rules more efficiently. Many distros now use nft under the hood.</p><p><strong>Interfaces in Containers:</strong> Each container gets typically a veth, connected to a Linux bridge or to something like a <em>veth to host</em> plus host routing. Tools like Calico, Flannel, etc., set up networking such that each container/pod has an IP and the network is routed or bridged across the cluster. Often this involves virtual interfaces and routing entries on each host. Understanding that under the hood, each pod’s interface is a part of the host’s network namespace (for host network, or moved into pod netns for normal pods) and how routes or encapsulation (VXLAN in Flannel, etc.) works can help debug cluster networking.</p><p><strong>TCP/UDP and Sockets:</strong> The kernel implements TCP/IP stack: it handles ACKs, sequence numbers, etc., for TCP connections. When you create a socket in a program (with socket() syscall), the kernel creates a socket structure. If you bind() an address, it associates it with that IP and port. When you listen(), the kernel will queue incoming connections. When a packet arrives destined to your IP and port, the kernel matches it to the listening socket and either queues a connection (SYN received, send SYN-ACK, etc. in background) or if UDP, it queues the datagram to the socket receive buffer. The app then does accept() or recvfrom() to get it.</p><p><strong>Procfs interfaces:</strong> Under /proc/net/ you find things like tcp, udp which list open sockets and their states (same info as netstat). Also /proc/sys/net/ is where a bunch of tunables are (like ip_forward, ipv4/conf/all/arp_ignore, etc.). These tunables control behaviors like whether the kernel routes packets, how it responds to ARP in certain cases, TCP settings (e.g., /proc/sys/net/ipv4/tcp_fin_timeout).</p><p><strong>Performance tuning:</strong></p><ul><li>Some sysctls like net.core.somaxconn (max listen backlog), net.core.rmem_max/wmem_max (max socket buffer sizes), or net.ipv4.tcp_congestion_control (algorithm) might be tuned for busy systems.</li><li>The kernel can offload some work to NICs (checksum, segmentation offload, etc.) which is usually beneficial.</li><li>For low-latency, sometimes disabling certain offloads or tuning interrupt coalescing on NICs can help.</li></ul><p><strong>Debugging Tools:</strong></p><ul><li>tcpdump/wireshark: capture packets via libpcap hooking into kernel, to see what’s on the wire or interface.</li><li>ss or netstat: view open sockets and their states, which the kernel tracks.</li><li>conntrack tool: see/flush connection tracking state.</li><li>iptables -L -v -n: see firewall rules and packet counts (to identify if firewall is dropping something).</li><li>ip route and ip rule: to see routing table and policy routing rules. Linux supports multiple routing tables and policy routing (via ip rule and ip route ... table X).</li></ul><p><strong>Net namespaces</strong> (we touched in the Namespaces section), recall that each net namespace has its own interfaces and routing. So ip link or ip route commands operate in the current net namespace. Docker uses that to isolate container networks.</p><h3>Checkpoint Quiz: Networking</h3><ol><li>In Linux’s netfilter (iptables), what is connection tracking (conntrack) used for?</li><li>If you add a rule to iptables in the FILTER table’s INPUT chain with -m state --state ESTABLISHED,RELATED -j ACCEPT, what does that accomplish?</li><li>True or False: A Linux bridge device (e.g., br0) allows VMs or containers on the same host to communicate with each other as if they were connected to the same physical LAN (layer 2 domain).</li></ol><p><strong>Answers:</strong></p><ol><li>Connection tracking monitors the state of network connections (like TCP streams, UDP “sessions”) so the kernel knows which packets belong to an existing connection. It enables stateful firewall rules, e.g., only allow responses to outgoing connections and is also used for NAT (to correctly map back replies to the originating host). Essentially, conntrack creates an entry for flows, marking them NEW, ESTABLISHED, etc., so iptables/nft can match on connection state.</li><li>That rule will accept any packets that are part of an <strong>already established connection or related to one</strong>. In practice, it means if you initiated a connection from inside (which would have been allowed out and tracked), the incoming reply packets (ESTABLISHED state) will be accepted. “RELATED” covers things like ICMP errors or FTP data connections that are related to an existing connection. This rule is commonly used to allow return traffic while having default drop on incoming new connections for security.</li><li>True. A Linux bridge works like a virtual switch: attach interfaces (physical or veth from VMs/containers) to a bridge and they can all reach each other at Layer 2 (just like plugging into the same Ethernet switch). This is indeed how Docker’s default network works and how one can set up a host-only or NAT network for VMs, by using a bridge to connect the virtual NICs. Communication is as if they share a LAN (same IP subnet, can ARP each other, etc.).</li></ol><h3>Device Drivers and Kernel Modules</h3><p>The Linux kernel is monolithic, meaning device drivers and core system components run in kernel space. However, you don’t have to compile them all into one big kernel binary; you can load them as needed. This is where <strong>loadable kernel modules (LKMs)</strong> come in. A <strong>kernel module</strong> is a piece of code that can be dynamically loaded into (or unloaded from) the running kernel, extending its functionality, often used for device drivers, filesystems, or other pluggable subsystems.</p><p><strong>Device Drivers:</strong> Drivers are the software that make hardware usable. For example, the disk controller has a driver, the network card has a driver, GPU has a driver, etc. Drivers typically handle the low-level communication with hardware (using bus interfaces like PCI, USB, I2C, etc.). The kernel abstracts common functionality, for instance, all block device drivers present a common block interface to the OS, and all network drivers present a net_device interface, but the driver itself knows how to program the device registers, handle interrupts, DMA, etc.</p><p>Linux has an enormous number of drivers to support the vast array of hardware out there. Many drivers are compiled as modules so that they can be loaded only when that hardware is present (saves memory and boot time).</p><p><strong>Kernel Modules vs Built-in:</strong> When you compile a kernel, you choose which features/drivers are built-in (Y) and which are modules (M). Built-in means it’s always present (like, you’d want the driver for your boot disk built-in, or you won’t be able to mount root FS). Modules are stored separately (often under /lib/modules/$(uname -r)/... directories). At boot, a program like udev or systemd or modprobe may auto-load modules based on what hardware is detected. For example, when a new USB device is plugged, the kernel’s uevent notifies udev, which then might call modprobe usb-storage if it’s a USB storage device.</p><p><strong>Using modprobe/insmod:</strong> To manually insert a module, you can use insmod module.ko. But usually you use modprobe modulename – modprobe is smarter: it will also load any dependency modules. Modules can depend on other modules (e.g., a filesystem module might depend on the crypto module). Modprobe references a configuration (like /etc/modprobe.conf or /lib/modules/depkm lists) to resolve these.</p><p>lsmod shows what modules are currently loaded (and how many instances or dependent usages they have). rmmod removes a module (if not in use – if a module is being used by some device or another module, you can’t remove it unless you force, which is not recommended).</p><p><strong>Example:</strong> Say you want to add support for NFS filesystem. You could compile the kernel with NFS as a module. Then when you run mount -t nfs ..., the mount program (via kernel) will request the module (kernels have a mechanism to ask user-space to load a needed module – modprobe via a utility called kmod). The system will load nfs.ko module. Now the kernel has NFS client support in place, and the mount proceeds. If you never use NFS, that code wasn’t loaded, saving memory.</p><p>Another example: you attach a new GPU, the kernel can load the appropriate driver module for it (if available). For proprietary drivers like NVIDIA, you often have an installer that compiles a kernel module and then modprobes it (this is the famous nvidia.ko for their binary driver).</p><p><strong>Working with modules (DevOps angle):</strong></p><ul><li>Sometimes you might need to blacklist a module (prevent it from loading), e.g., if a certain driver is causing problems or you want to use a different driver. You can do that via a modprobe config file.</li><li>Or, you might manually load a module in an init script if needed (though nowadays udev covers most cases).</li><li>Checking dmesg for module-related messages is useful (the kernel logs when a module is loaded and often when hardware is registered).</li><li>Kernel modules can also be used not just for drivers but for other features like Netfilter modules (for iptables to support certain match criteria), or filesystem modules (e.g., cifs.ko for mounting Windows shares, xfs.ko if XFS is not built-in, etc.).</li></ul><p><strong>Security note:</strong> Not all systems allow module loading by normal users; typically only root can load modules. Some environments (like highly secure or containerized) might even disable module loading at runtime (you can lock down with settings to prevent any new modules for safety, requiring reboot to change).</p><p><strong>When things go wrong:</strong> If a device isn’t working, often it’s because the driver module didn’t load or isn’t present. Running lspci -k can show which kernel driver is in use for a PCI device or which modules are available for it. If it says &quot;Kernel driver in use: xyz&quot;, then it’s loaded. If it shows &quot;Kernel modules: abc&quot;, that means module abc exists but maybe it’s not loaded. Then modprobe abc might fix the issue.</p><p><strong>Custom modules / Out-of-tree drivers:</strong> Sometimes hardware vendors provide their own modules separately (like a WiFi driver source on their site). You’d compile it against your kernel headers and then insert it. This is common in specialized or very new hardware not yet in mainline Linux.</p><p><strong>Procfs interface to modules:</strong> There’s /proc/modules which lists loaded modules (similar to lsmod output). And /proc/kallsyms lists symbol addresses (which sometimes matters in module debugging, but beyond scope here).</p><p><strong>Summary of workflow:</strong></p><ul><li>Boot kernel -&gt; it autoloads critical built-in drivers to mount root.</li><li>Userspace starts, udev sees hardware and loads needed modules.</li><li>Throughout runtime, modules can be loaded/unloaded as needed.</li></ul><p><strong>Capabilities via Modules:</strong> Some entire subsystems are optional modules. For instance, ipt_REJECT is an iptables extension that might be a module. If you add an iptables rule using -j REJECT, the kernel might auto-load that ipt_REJECT module. Similarly, for example, enabling bridging functionality might require bridge.ko module.</p><p><strong>Drivers and /dev:</strong> Many driver modules create device files under /dev. For example, loading the usblp (USB printer) module will cause /dev/usb/lp0 to appear (udev will create it). The major/minor numbers are allocated by the kernel and udev reads sysfs to create corresponding nodes. So, if you have missing device nodes, it might be that the module isn’t loaded or udev rules missing.</p><blockquote><strong><em>Did You Know?</em></strong><em> The output of </em><em>dmesg often shows module information. For example: </em><em>&quot;usbcore: registered new interface driver usb-storage&quot; or </em><em>&quot;e1000e: Intel(R) PRO/1000 Network Driver - 3.2.6-k&quot; meaning the e1000e module loaded and registered a new network interface. Also, kernel modules can have parameters (viewable in </em><em>modinfo modulename), which you can set via modprobe config or command line (e.g., </em><em>modprobe snd_hda_intel enable_pcsp=1 to enable PC speaker through that sound driver, etc.).</em></blockquote><h3>Checkpoint Quiz: Modules and Drivers</h3><ol><li>What is the main advantage of compiling a kernel feature as a loadable module instead of built-in?</li><li>How would you list currently loaded kernel modules and potentially see their size or usage count?</li><li>True or False: Removing (unloading) a kernel module that is in use by the system is a safe operation that the kernel will always allow.</li></ol><p><strong>Answers:</strong></p><ol><li>Using a loadable module provides <strong>flexibility, </strong>you only load it when needed, which can save memory and reduce boot time. It also allows updating or adding support for new hardware without rebooting (just insert the new module), and keeping the core kernel smaller (less attack surface, potentially). Essentially, it’s more dynamic: unused code doesn’t have to be in memory, and you can add/remove functionality on the fly.</li><li>You can use the <strong>lsmod</strong> command to list loaded modules. It shows the module name, size, and the number of references (usage count). Alternatively, viewing the file /proc/modules will give similar information. Each line of lsmod corresponds to an entry of /proc/modules.</li><li>False. The kernel will prevent unloading a module that is currently in use (has a non-zero reference count), unless you force it (with rmmod -f and the kernel was compiled with forced module removal option). Forcing removal can crash or destabilize the system if something was using that module’s functionality. So normally, you can only remove modules that are not actively in use. In practice, you should avoid forcing removal of in-use modules as it is unsafe.</li></ol><h3>Security: Capabilities, Seccomp, SELinux, and AppArmor</h3><p>Linux security at the kernel level involves several mechanisms that restrict or log what processes can do. For DevOps, understanding these helps in configuring secure containers, debugging permission issues, and setting up systems in compliance with security policies.</p><h3>Capabilities</h3><p>Traditionally, Unix had a binary notion of user permissions, either you are <strong>root</strong> (UID 0) with god-like powers, or you’re not (and then you have a limited set of permissions). <strong>Capabilities</strong> break down the all-powerful root privileges into finer-grained units. This way, a process can be given <em>some</em> (but not all) root powers.</p><p>For example, there is a capability CAP_NET_ADMIN for performing network administration tasks (like configuring interfaces, modifying routing tables), CAP_SYS_TIME for setting system clock, CAP_NET_RAW for using raw sockets (pinging etc.), CAP_SYS_MODULE for loading/unloading kernel modules, CAP_CHOWN for changing file ownership, and many others. There are around 30+ capabilities in Linux (the exact number grows occasionally as new ones are introduced).</p><p>Inside the kernel, whenever a privileged action is attempted, instead of just checking “UID == 0?”, it checks “does the current process have X capability?”. For instance, binding to a port below 1024 traditionally required root; now it requires CAP_NET_BIND_SERVICE. So if a process has that capability (and not necessarily full root), it can bind low ports.</p><p>By splitting privileges, you can run processes with just the capabilities they need, not full root. This is especially relevant in containers. Docker and Kubernetes by default drop many capabilities for containers (for example, containers typically don’t get CAP_SYS_MODULE or CAP_SYS_TIME, etc., but they might keep CAP_NET_RAW or CAP_NET_BIND_SERVICE depending on default seccomp profile). This limits the impact if a container is compromised, the attacker can’t just load kernel modules or reboot the machine via those privileged calls, because the capabilities aren’t there.</p><p><strong>Using capabilities:</strong> You can manage them with tools like capsh or setcap. For example, setcap cap_net_bind_service=+ep /usr/bin/nginx would give the nginx binary the capability to bind to low ports (so you could run it as non-root but still bind to 80). The +ep means “enable in effective and permitted set”. There are actually multiple sets (Effective, Permitted, Inherited, Bounding) – in practice, we usually manipulate the permitted set on binaries with setcap, which then the kernel grants when executing that binary.</p><p>For running processes, pscap or cat /proc/&lt;PID&gt;/status (which has fields like CapEff, CapPrm) can show current capabilities.</p><p>Linux also has the idea of bounding set (system-wide cap mask), which you can drop certain capabilities for the entire system (set in early boot) such that even root can’t use them. Some secure environments do that for e.g., CAP_SYS_MODULE to prevent any module loading after boot.</p><p><strong>Example:</strong> If you run a web server container, you might only give it CAP_NET_BIND_SERVICE (to bind port 80) and drop everything else. Then even if it’s compromised, it cannot (for instance) change file ownership system-wide (no CAP_CHOWN outside its namespace), can’t mount filesystems (no CAP_SYS_ADMIN in mount sense), etc. Docker has a default set of capabilities it keeps which are considered relatively safe, and drops more dangerous ones.</p><p>One common confusion: Even if you drop capabilities, if a process is running as root <em>and</em> still has powerful ones like CAP_SYS_ADMIN, that is nearly root anyway (CAP_SYS_ADMIN is a catch-all that covers many admin tasks). That’s why container security often tries to run processes as non-root and drop most caps.</p><p>To see what each capability allows, man 7 capabilities is very informative – it lists them with descriptions (like CAP_SYS_ADMIN is huge laundry list, CAP_DAC_OVERRIDE is bypass file permissions checks, etc.).</p><h3>Seccomp (Secure Computing Mode)</h3><p><strong>Seccomp</strong> is a mechanism to filter system calls that a process can make. With seccomp, you can say “this process is only allowed to use these specific syscalls, any others result in the kernel killing the process (or taking some action like returning an error)”. It’s like a syscall firewall.</p><p>Seccomp has a couple of modes: seccomp strict mode (very basic, not widely used now) and seccomp-bpf, which is the common one where you provide a Berkeley Packet Filter (BPF) program to evaluate each syscall against a policy. In practice, higher-level tools (like Docker) will generate a seccomp profile and pass it to the kernel.</p><p>For example, a container seccomp profile might disallow mount() syscall, ptrace(), kill (to other pids), etc., to limit what a compromised process could do. Or for a specific application, you tailor it to exactly what syscalls it needs. If the app tries anything outside that, it gets a SIGKILL or SIGSYS depending on the action configured (usually kill).</p><p>Kubernetes allows providing seccomp profiles for pods/containers, and Docker has a default profile that blocks calls known to be risky in containers (like keyctl, perf_event_open, etc.). Seccomp is nice because even if running as root with full caps, if seccomp prohibits a certain syscall, the kernel will refuse it, providing another layer of defense.</p><p><strong>Example:</strong> If an attacker somehow gets code execution in a container and tries to use syscall(__NR_ptrace, ...) to attach to another process, but seccomp denies ptrace, that attempt fails. Or tries to open /proc/self/mem (common for some exploits) but seccomp blocked open to that path – denied. Essentially narrowing what the process can do to the minimal syscalls needed.</p><p>Implementing seccomp filtering requires knowing what syscalls the app normally uses. Tools like strace can help determine that.</p><h3>SELinux and AppArmor (MAC systems)</h3><p>Both <strong>SELinux</strong> (Security-Enhanced Linux) and <strong>AppArmor</strong> are Linux Security Modules (LSMs) that implement <strong>Mandatory Access Control (MAC)</strong> policies beyond the standard discretionary Unix permissions.</p><p><strong>SELinux:</strong> Uses a labeling system. Every process and object (file, socket, etc.) has a <strong>security context</strong> (label). SELinux policies (which are very granular) specify which labels can access which, and in what ways. For example, an httpd_t process type may be allowed to read files labeled httpd_sys_content_t but not allowed to read ssh_key_t. Even if the Unix perms would allow it, SELinux can deny it because policy says that domain/type combo is not permitted.</p><ul><li>SELinux has modes (enforcing, permissive, disabled). In enforcing mode, if policy doesn’t explicitly allow something, it’s denied (and logged as an AVC denial). Policies can be quite complex (with users, roles, types, Booleans for toggling features, etc.). Typically, distributions ship SELinux in targeted policy mode, which confines certain daemons (like web server, database, etc.) but not all processes.</li><li>For DevOps, you often encounter SELinux preventing some actions. E.g., a web server can’t serve files in a home directory unless you set correct file context or toggle an SELinux boolean. Commands like chcon to change context or semanage fcontext to make policy exceptions, and getsebool/setsebool to adjust booleans.</li><li>SELinux is powerful but has a learning curve. Common tasks: ensure your program’s files are labeled correctly (the restorecon tool can apply default contexts), check audit logs /var/log/audit/audit.log when something fails to see if it was an SELinux denial, then either adjust context or policy via local module if needed (using audit2allow to generate a policy allow rule if truly necessary).</li></ul><p><strong>AppArmor:</strong> Instead of labels, AppArmor works with <strong>profiles</strong> for programs (by path/name). An AppArmor profile lists what a program can do: which files (paths) it can read/write, which capabilities it can use, etc. It’s somewhat easier to understand because it often uses human-readable file paths (with wildcards) and the profile attaches to processes by executable name or path. For example, there might be an AppArmor profile for tcpdump that says it can only open certain files, use certain network operations, etc.</p><ul><li>AppArmor is used by Ubuntu and some others. It’s not as all-encompassing as SELinux in theory but can still confine processes effectively. You might see AppArmor denials in syslog (/var/log/syslog) complaining about a profile violation.</li><li>With AppArmor, if a process tries to access something not allowed by its profile, the kernel denies it (or complains if in complain mode). Profiles can be set to enforce or complain mode. Tools like aa-status show which profiles are loaded.</li></ul><p><strong>Comparing SELinux vs AppArmor:</strong> SELinux is more fine-grained and system-wide (everything has a label, policy covers interactions between anything). AppArmor is easier to manage for specific services (just write a profile per service) but doesn’t do whole-system policy in the same way. One big difference: SELinux is path-insensitive (identifies files by inode label, not by where in filesystem), whereas AppArmor is path-based (so if you access same file via different path (hardlink, bind mount), AppArmor might not catch it if profile doesn’t cover that path). SELinux also has notions of Multi-Level Security (MLS) and categories which can enforce very strong isolation (like military classification levels), seldom used outside high security setups but it’s there.</p><ul><li>Many container runtimes use AppArmor or SELinux to further confine containers. E.g., Docker on Fedora uses SELinux (containers run in svirt_lxc_net_t type), on Ubuntu it might use AppArmor (with a default profile that restricts some file access etc. for container processes).</li></ul><p><strong>Why these matter:</strong> If you deploy an app and it’s not working, it might not be a code bug but a security policy denial. For example, trying to bind to port or write to a file and getting EPERM, could be capability missing or AppArmor/SELinux blocking. Recognizing that and adjusting policy (or container config to add needed capabilities, or correct label on a file) is important.</p><p><strong>Audit logs:</strong> Both SELinux and AppArmor log denials that you can inspect:</p><ul><li>SELinux: audit.log will show lines with AVC denied and details of source context, target context, attempted action.</li><li>AppArmor: syslog (kern) with lines like audit: APPARMOR=&quot;DENIED&quot; including operation, profile, name of file, etc.</li></ul><p><strong>Disabling</strong> is possible (e.g., set AppArmor to complain, or SELinux to permissive), but generally better to configure properly rather than turn off (especially in production with security requirements).</p><p><strong>Seccomp, capabilities, SELinux, AppArmor combined</strong> can provide defense in depth:</p><ul><li>Capabilities limit the blast radius of running as root.</li><li>Seccomp limits syscalls reachable in case some vulnerability might use an odd syscall.</li><li>SELinux/AppArmor limit filesystem and system resource access beyond what standard perms allow, to mitigate damage if something tries to break out or access unauthorized data.</li></ul><h3>Checkpoint Quiz: System Security</h3><ol><li>What does it mean when we say a process has dropped all capabilities except CAP_NET_BIND_SERVICE? What practical effect does that have?</li><li>If an SELinux policy is in enforcing mode, what happens when a process tries to access a file or resource in a way that is not allowed by the policy?</li><li>Fill in the blank: AppArmor restricts programs based on predefined ____, usually tied to the program’s executable name or path, whereas SELinux uses security ____ assigned to processes and objects.</li></ol><p><strong>Answers:</strong></p><ol><li>Dropping all but CAP_NET_BIND_SERVICE means the process is relinquishing root privileges except the specific privilege to bind to privileged ports (&lt;1024). In practice, that process could bind to, say, port 80 even if it’s not running as UID 0, but it cannot do other root-only things like changing system time, loading modules, changing interface settings, etc. It’s a way to run a network server as non-root while still being able to listen on a low port. Essentially, it has a very limited slice of “root power” – only the one capability kept.</li><li>In enforcing mode, SELinux will <strong>block the access</strong> (deny it) and log an AVC (Access Vector Cache) denial. The process will likely receive an error (like Permission Denied) or possibly be killed if the policy dictates (usually just denied with error). The action is not allowed to proceed, ensuring the MAC policy is upheld beyond the normal Unix permissions.</li><li>AppArmor uses predefined <strong>profiles</strong> for programs, whereas SELinux uses security <strong>labels/contexts</strong>. (Any equivalent term like “contexts” or “labels” for SELinux is fine, and “profiles” or “policies tied to executable path” for AppArmor’s blank is fine.)</li></ol><h3>eBPF and Kernel Tracing</h3><p>In recent years, <strong>eBPF (extended Berkeley Packet Filter)</strong> has emerged as a powerful technology in the Linux kernel that allows running custom code in the kernel, safely and efficiently. eBPF is often described as enabling “programming the kernel without changing kernel source or loading modules”. It started as a way to filter network packets (classic BPF was used in tcpdump filters), but has evolved to a general-purpose hook mechanism for many parts of the kernel.</p><p><strong>What can eBPF do?</strong> eBPF programs can be attached to various hook points:</p><ul><li>network events (packet reception, transmission, socket events),</li><li>tracepoints (static instrumentation points in kernel code),</li><li>kprobes/kretprobes (dynamic tracing of kernel function entry/exit),</li><li>uprobes (user-level function tracing),</li><li>perf events,</li><li>and more (like at system call entry/exit, or at specific kernel-life events).</li></ul><p>These eBPF programs run in kernel context but are verified and JIT-compiled for safety (so they can’t crash the kernel or loop indefinitely). They can only call a limited set of helper functions and use a scratch memory (maps) to communicate with userland or store data.</p><p><strong>Uses of eBPF:</strong></p><ul><li><strong>Tracing/Observability:</strong> Tools like bpftrace, BCC (BPF Compiler Collection) let you write scripts to trace what’s happening (like which process calls open() with what arguments, or track latency of I/O, etc.) all in kernel with minimal overhead. This is super useful for performance analysis in production without needing custom kernel modules or systemtap, etc.</li><li><strong>Networking:</strong> eBPF powers things like XDP (eXpress Data Path) for high-performance packet processing (allowing custom filtering or load balancing at the NIC driver level before normal stack), and Cilium (a container networking and security project) uses eBPF for implementing network overlay, load balancing, even firewalling at L3/L4 with connection tracking in a more efficient way than iptables.</li><li><strong>Security monitoring:</strong> eBPF programs can be attached to syscalls or kernel functions to monitor and log unusual behavior (this is how tools like Falco work, to detect e.g., if a container tries to open /etc/shadow or something, Falco’s eBPF sensor catches that).</li><li><strong>Performance monitoring:</strong> eBPF can aggregate stats (via maps) on things like CPU usage by function, or I/O latency distribution, etc., which can then be read by user-space. perf tool and syscount etc., are starting to leverage eBPF for finer analysis.</li><li><strong>Faster system calls (seccomp-bpf):</strong> Actually seccomp’s filter uses BPF internally (older seccomp-bpf, but conceptually eBPF).</li><li><strong>Others:</strong> Attach to tracepoints for disk I/O, scheduler events, etc., to get insights.</li></ul><p><strong>Running eBPF tools:</strong> As a DevOps engineer, you may come across eBPF-based tools:</p><ul><li><strong>bpftrace:</strong> A high-level tracing language (similar to DTrace). For example, bpftrace -e &#39;kprobe:vfs_read { printf(&quot;%s read\n&quot;, comm); }&#39; would print every time any process enters the vfs_read function (which underlies read syscalls). It’s very powerful for debugging.</li><li><strong>bcc (BPF Compiler Collection):</strong> Python or C++ frontends for writing BPF programs. There are lots of ready-made tools in BCC (like execsnoop, opensnoop, tcplife, etc. for snooping execs, file opens, TCP connections lifetime, etc.).</li><li><strong>Cilium &amp; Kubernetes:</strong> If you operate Kubernetes with Cilium for networking, you’re using eBPF to enforce network policies and do routing. eBPF helps avoid iptables complexity by doing in-kernel decisions.</li><li><strong>Systemd</strong> is beginning to incorporate eBPF for things like socket filters (to rate-limit stuff) or maybe cgroup monitoring.</li></ul><p><strong>Why eBPF is “safe”:</strong> The kernel has an eBPF verifier that checks the bytecode of the BPF program to ensure it:</p><ul><li>doesn’t have loops that could be infinite (only bounded loops or it unrolls them),</li><li>doesn’t access out-of-bounds memory (all map and context accesses are checked),</li><li>doesn’t call non-allowed kernel functions,</li><li>doesn’t exceed a certain instruction limit (like 1e6 insns by default).<br> If verification passes, the kernel JIT compiles the BPF bytecode to native machine code for performance. It then runs at hook points with near-native speed.</li></ul><p><strong>One example scenario:</strong> Let’s say we want to track every time a process does an execve syscall and log which user, which command. We could attach an eBPF program to the execve syscall entry tracepoint or kprobe on do_execve. The eBPF program would gather info (like current-&gt;uid, the command string from memory) and perhaps write it to a perf ring buffer or map. Then userland reads it and prints it. This could be done with BCC or bpftrace one-liners, much lighter than writing a kernel module for the same.</p><p><strong>Another:</strong> We find system calls have some overhead and we want to reduce context switches for certain high-volume kernel-user interactions. There’s something called io_uring which uses BPF for a concept of composable operations, but maybe too deep for now.</p><p><strong>Observability integration:</strong> Companies like Netflix have open-sourced tons of BPF tools (via BCC). Brendan Gregg’s tools like opensnoop (which prints file open events live) and execsnoop (prints exec events) or tcpconnect, etc., all allow real-time monitoring with minimal overhead.</p><p><strong>eBPF is mainstream.</strong> You might see roles or tasks involving writing eBPF code for custom monitoring or using frameworks like Tracee (by Aqua) for security threat detection, or in networking replacing iptables with eBPF-based XDP firewall in some setups.</p><h3>Checkpoint Quiz: eBPF</h3><ol><li>What is one key benefit of using eBPF for system tracing or monitoring compared to traditional methods like inserting kernel print statements or using kernel modules?</li><li>True or False: eBPF programs can be used to alter the behavior of the kernel at runtime, such as dropping certain network packets or filtering system calls, without recompiling the kernel.</li><li>Name a tool or framework that utilizes eBPF to provide observability (monitoring/tracing) in Linux systems.</li></ol><p><strong>Answers:</strong></p><ol><li><strong>Efficiency and safety.</strong> eBPF allows running custom code in the kernel <em>safely</em> (verified, without crashing or compromising security) and with very low overhead. This means you can do deep tracing or packet filtering <em>in production</em> without the performance hit of constantly context-switching to userland or the risk of a custom kernel module. Also, you don’t need to rebuild or reboot the kernel, you can dynamically load these tracing programs. In short: <strong>dynamic, safe, low-overhead introspection</strong> is a key benefit.</li><li><strong>True.</strong> eBPF effectively lets you inject logic into the kernel at runtime. For example, you can attach an eBPF program to a network hook to drop packets meeting certain criteria (like a custom firewall) or to a system call entry to filter syscalls (like seccomp does). No kernel recompile is needed, it’s done by loading a BPF program via the bpf() system call or similar mechanisms. The kernel ensures it’s safe, then it runs as part of the kernel workflow.</li><li>Many answers possible: <strong>BCC (BPF Compiler Collection)</strong>, <strong>bpftrace</strong>, <strong>Falco (security monitoring)</strong>, <strong>Cilium (networking)</strong>, <strong>Tracee</strong>, <strong>Katran (Facebook’s eBPF load balancer)</strong>, <strong>Perf tools like </strong><strong>execsnoop, </strong><strong>opensnoop</strong> from BCC, or even <strong>Systemd’s use of eBPF</strong> or <strong>Kubernetes with Cilium</strong>. The most straightforward: BCC and bpftrace are well-known for observability, or saying <em>“tools like </em><strong><em>bpftrace</em></strong><em> or the </em><strong><em>BCC</em></strong><em> toolkit which includes things like execsnoop, opensnoop, tcptop, etc.”</em> would be correct.</li></ol><h3>Kernel Boot Process and Init Systems</h3><p>When a Linux machine boots, several stages occur to get the kernel loaded and the user-space running:</p><ol><li><strong>Firmware/Bootloader:</strong> The system firmware (BIOS or UEFI on PCs) runs first. It performs hardware initialization and then loads the bootloader from disk (like GRUB). The bootloader’s job is to load the kernel (and an initial RAM disk, if needed) into memory and then transfer control to the kernel.</li><li><strong>Kernel Initialization:</strong> The kernel starts executing (on x86, in protected mode, etc., then it sets up its own environment). It first does low-level hardware setup (initializing memory paging, setting up basic data structures), then it uncompresses if it’s a compressed kernel, and initializes all compiled-in drivers for essential hardware.</li><li>The kernel will print messages (these you see via dmesg) as it detects CPU cores, memory, devices, etc. It also initializes subsystems (scheduler, networking stack, etc.). If an <strong>initramfs</strong> (initial RAM filesystem) is provided, the kernel mounts that as a temporary root filesystem. This initramfs contains helpers (like maybe drivers or scripts needed to find the real root FS).</li><li>Commonly, an initramfs is used on modern distros, it includes modules for disk controllers, filesystems, and LVM/RAID, etc., and maybe udev to find disks. The kernel executes the init program from initramfs (often a script or binary like /init in the archive).</li><li><strong>Switch to Real Root:</strong> The initramfs typically will mount the real root filesystem (e.g., on /dev/sda2, etc.). Once that’s available, it may pivot_root (or use switch_root) to make the real FS the new root. Then the initramfs’s job is done (and it’s freed from memory).</li><li>If no initramfs, the kernel directly tries to mount the root as specified by boot params (e.g., root=/dev/sda1 passed by bootloader). If that fails (no driver or wrong fs), kernel panics (you’ll get a “Kernel panic – unable to mount root fs”).</li><li><strong>Init Process (PID 1):</strong> After mounting root FS, the kernel looks for an init program to start. Typically, it tries /sbin/init, /etc/init, /bin/init, or as specified by init= boot param. On modern systems this is often <strong>systemd</strong> (/sbin/init is a symlink to systemd). In older, it might be SysV init or Upstart.</li><li>This init becomes PID 1, the first user-space process. The kernel will hand over control to it (some early processes like kthreadd, etc., are kernel threads started earlier, but PID 1 is special as the ancestor of all user processes and reaper of zombies).</li><li><strong>Init System responsibilities:</strong> The init (be it systemd or SysV) then starts services as configured.</li></ol><ul><li>In SysV init, it would execute scripts from /etc/rc.d/ or /etc/init.d/ in a certain order for a given runlevel.</li><li>In systemd, it reads unit files, parallelizes startup, etc. The target is to get all necessary system services running (like getty for console login, network, sshd, etc.).</li></ul><ol><li>Systemd has essentially replaced older init on most major distros. It brings features like socket activation, parallel start, explicit dependencies, cgroup management for services, etc. As a DevOps person, you often interact with systemd (using systemctl to manage services). Systemd also handles things like mount points, swap, device unit management, and can supervise processes, implement watchdogs, etc., all in the context of PID 1.</li><li><strong>Runlevels / Targets:</strong> Historically, runlevels 1–5 were used to define states (single-user, multi-user, graphical, etc.). Systemd uses “targets” (like multi-user.target, graphical.target). But the concept is the same: the system can boot to a certain state and only start certain services accordingly.</li><li><strong>Login:</strong> Once init has gotten the system into multi-user mode, you have login prompts spawned (getty on text consoles, or display manager for GUI, etc.). Logging in spawns a shell or GUI session, and you are in user-space fully.</li></ol><p><strong>Shutting down:</strong> When you issue reboot or shutdown, typically systemd handles it by stopping services in an orderly fashion (it’s also PID 1’s job to handle signals like SIGINT from ctrl-alt-del or such if configured, and to handle orphan processes termination). Finally, systemd or init will call the reboot() or poweroff() system call to instruct the kernel to reboot or halt. The kernel then does final steps (sync disks, maybe ACPI commands to power off).</p><p><strong>Init system differences:</strong></p><ul><li><strong>Systemd</strong> (used by Fedora, RHEL, CentOS, Ubuntu, Debian (since Jessie), etc.): uses .service unit files in /lib/systemd/system and /etc/systemd/system. Very feature-rich.</li><li><strong>Upstart</strong> (Ubuntu 2006–2014 era): event-based init, replaced by systemd in Ubuntu 15.04.</li><li><strong>SysV init</strong> (old Debian, Slackware, etc., or still some embedded maybe): uses /etc/inittab to define what to start at runlevels and basically runs through shell scripts.</li><li><strong>OpenRC</strong> (Gentoo, Alpine uses OpenRC on top of BusyBox’s init often).</li><li><strong>runit, s6, etc.</strong> (some distros or containers use these super minimal inits, e.g., Docker’s official images often don’t run any init at all unless you use something like dumb-init or s6-overlay to handle reaping zombies).</li></ul><p><strong>Containers and init:</strong> In a container, often the process you run becomes PID 1 inside that container’s namespace. It’s good to have a minimal init to handle signals and reap children (like PID 1 normally does). Tools like tini or dumb-init are often used as the ENTRYPOINT in Docker containers to act as PID 1 inside and forward signals to the actual app, etc.</p><p><strong>Boot loading config (GRUB):</strong> As DevOps, sometimes you need to adjust kernel boot parameters (in /etc/default/grub then update-grub, or editing grub.cfg). Boot params can control lots: from hardware options to kernel features (like selinux=0 to disable SELinux, or sysctl defaults, or memory and CPU options). This happens before kernel is up, passed by bootloader.</p><p><strong>Dracut / mkinitcpio:</strong> These are tools to build the initramfs on Fedora/CentOS and Arch respectively. Understanding that if you update a kernel and new drivers, you might need to ensure initramfs includes them, etc.</p><p><strong>Troubleshooting boot issues:</strong> If system doesn’t come up, knowing this sequence helps:</p><ul><li>Did BIOS/bootloader load kernel? (If not, maybe MBR/EFI issues).</li><li>Did kernel mount root FS? (Check if in emergency shell of initramfs or panic messages).</li><li>Did init start? If kernel says “Failed to execute /init” or “No init found”, means maybe wrong root or corrupted FS.</li><li>If it hangs later, maybe a service is stuck; sometimes using kernel param systemd.unit=rescue.target or adding single to boot might drop to single-user mode for debugging.</li><li>dmesg -k shows kernel ring buffer (or from dracut emergency, etc., to figure out issues).</li><li>For custom kernels, maybe missing drivers (like forgot to include NVMe driver so root on NVMe can’t mount).</li><li>Also how to get into GRUB menu (holding shift on boot for BIOS, or using rd.break param to break into initramfs for recovery tasks).</li></ul><h3>Checkpoint Quiz: Boot and Init</h3><ol><li>During the Linux boot process, what is the role of the initial RAM disk (initramfs)?</li><li>Which process is typically assigned PID 1, and what is its significance in the system?</li><li>On a system using systemd, how would you change the system’s target (for example, boot into rescue mode or graphical mode)?</li></ol><p><strong>Answer Key:</strong></p><p>1. The initramfs is a temporary root filesystem loaded into memory early in boot. It contains minimal tools and drivers needed to <strong>prepare the real root filesystem</strong>. For example, it may load disk controller modules, decrypt disks, assemble RAID/LVM, then mount the real root. It then switches (pivot_root) to the real root filesystem and executes the real init. In short, it bridges the gap between kernel boot and availability of the actual root FS (especially if the actual root is on complex storage or needs initialization).</p><p>2. PID 1 is the <strong>init process</strong> (on modern systems, typically systemd). It is the first userspace process started by the kernel. Its significance:</p><ul><li>It is the parent of all other processes (directly or indirectly).</li><li>It is responsible for starting and stopping system services and overall system state.</li><li>It also has the special role of reaping zombie processes (any orphaned child processes will be adopted by PID 1 and cleaned up).</li><li>If PID 1 dies, the kernel panics (since there’s no init).<br> Essentially, PID 1 is the <em>init system</em> that keeps the system running.</li></ul><p>3. In systemd, targets are used for different run levels. To change the target at boot, you could <strong>set a kernel parameter</strong> like systemd.unit=rescue.target for rescue mode. Or once running, use systemctl isolate rescue.target to immediately switch to rescue (single-user) mode. For graphical mode, the target is graphical.target (or multi-user.target for non-graphical multi-user). You can also change the default target with systemctl set-default &lt;target&gt;. For instance, systemctl set-default multi-user.target to boot in text mode by default. So, e.g., <em>“Use </em><em>systemctl isolate rescue.target to go into rescue mode (or edit the boot command to use </em><em>... systemd.unit=rescue.target). Graphical mode corresponds to </em><em>graphical.target, and you can switch to it with </em><em>systemctl isolate graphical.target or set it as default.”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6517b7655df4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Docker: Origins, Technology, and the Future of Containers]]></title>
            <link>https://pramodhm112.medium.com/understanding-docker-origins-technology-and-the-future-of-containers-ee0391fc1bac?source=rss-e1df5bff44a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee0391fc1bac</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[namespaces]]></category>
            <category><![CDATA[docker-image]]></category>
            <dc:creator><![CDATA[Pramodh Kumar M]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 06:02:24 GMT</pubDate>
            <atom:updated>2026-01-06T14:24:20.814Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker Origins and Concepts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UzWIOG66dvxierjzKF-xmA.png" /><figcaption>Docker Origins and Concepts</figcaption></figure><h3>Introduction</h3><p>Docker is an open platform that has revolutionized how developers package, ship, and run applications. It builds on the long history of Unix/Linux process isolation to create portable “containers” for software. Docker was introduced to solve a fundamental pain point: <em>“shipping code to the server is hard”</em>. By encapsulating an application and all its dependencies into a single standard format, Docker makes the deployment process repeatable and consistent. Containers ensure that an app will run the same way on a developer’s laptop, a test server, or a production cloud machine. This consistency underpins modern <strong>DevOps</strong> and <strong>CI/CD</strong> practices. In the words of the official documentation, Docker “streamlines the development lifecycle” by letting teams share and deploy software in containers with ease.</p><p>Behind this breakthrough lies both a compelling story and deep technical foundations. We will explore Docker’s origins from early container-like technologies to Solomon Hykes’ 2013 demo and then explain the core concepts (containers, images, registries, etc.). Along the way, we’ll cover the Linux kernel features (namespaces, cgroups, union filesystems) that make containers possible, and illustrate Docker’s impact on cloud-native development.</p><h3>Evolution of Container Technology</h3><p>The idea of isolating and packaging applications is not new. In fact, it traces back to classic Unix. In 1979, the <strong>chroot</strong> system call was introduced in Version 7 Unix. Chroot lets a process see a different “root” directory, effectively confining its filesystem view. This was a rudimentary form of sandboxing: a jailed process couldn’t access files outside its assigned directory tree. (A similar concept appeared in 1982’s 3BSD, which had <em>“changes root”</em> in the kernel.)</p><p>More sophisticated isolation appeared later. In 2000, <strong>FreeBSD Jails</strong> extended chroot by also isolating process IDs and IP addresses. Each jail could have its own network stack and hostname, making the container almost feel like a separate machine. Around the same time, Solaris Zones (later called Containers) and OpenVZ on Linux (both mid-2000s) provided full OS-level virtualization isolating processes, networking, users, and resource usage. These technologies required patched kernels or OS support, but they demonstrated that one host could securely run multiple isolated user environments without full virtual machines.</p><p>A key milestone was Google’s work on <strong>cgroups</strong> (control groups) in 2006. Originally called “Process Containers”, cgroups let administrators limit and account for CPU, memory, and I/O usage of a group of processes. Renamed and merged into Linux 2.6.24, cgroups became the resource-management backbone of containers. Around 2008, <strong>Linux Containers (LXC)</strong> combined cgroups with namespaces (another Linux kernel feature) to create the first full Linux container system. LXC allowed multiple containers to run on a single unmodified kernel, each with its own isolated /, /proc, network interfaces, and more.</p><p>Over time the pieces came together into a general concept: containerization. One common analogy captures this well: a <strong>software container</strong> is like a <strong>standard shipping container</strong>. In global trade, shipping containers have a uniform shape and locking mechanism, so any crane, ship, or truck can move them without knowing their contents. Similarly, a Docker container bundles an application with its runtime and libraries in a consistent package. Any host with Docker installed can run the container without needing to know what’s inside. This <em>separation of concerns </em>standardizing the interface between software and infrastructure enables portability and automation. As Solomon Hykes explained in 2013, the idea came from shipping containers: any container (software or metal) should work uniformly across systems.</p><p>All these developments set the stage for Docker. By early 2013, the kernel had namespaces (for isolating PID, network, mount, etc.) and cgroups (for resource limits), and union/overlay filesystems (for layering images). The Docker project built on these mature technologies to make containers accessible and developer-friendly. As one retrospective notes, when Docker appeared in 2013, “containers exploded in popularity,” because Docker provided a complete, easy-to-use ecosystem on top of the existing kernel features.</p><h3>DotCloud and the Birth of Docker</h3><p>Docker’s genesis was a startup called <strong>dotCloud</strong>, founded in Paris in 2008 by Solomon Hykes and partners. DotCloud was a cloud <strong>Platform-as-a-Service (PaaS)</strong>: developers could deploy apps without managing servers. Under the hood, dotCloud relied heavily on Linux containers to isolate customer workloads. As dotCloud’s users repeatedly asked for direct access to that container technology, Hykes realized the bigger opportunity was to open it up.</p><p>In March 2013, Hykes unveiled Docker at the Python conference PyCon. The event has gone down in history: “Solomon Hykes walked onto the stage at PyCon 2013 and revealed Docker to the world,” according to Docker’s official blog. In his demo, Hykes explained that Docker was essentially dotCloud’s container engine made available to everyone: <em>“Yes, here is our low-level piece. Now you can do Linux containers with us and go do whatever you want…”</em>. (In other words, Docker was designed so developers could <em>directly</em> “democratize” the same container technology that dotCloud had built its PaaS on.)</p><p>The response was immediate. The project was quickly open-sourced, and the startup rebranded itself as Docker, Inc. by late 2013. Venture capitalists poured in funding, and major tech companies took notice. By the end of 2013, dotCloud had even sold off its original PaaS business to focus solely on Docker. DockerCon events soon followed, building a vibrant community. The Docker ecosystem (engine, CLI, images, Hub, etc.) grew rapidly. Docker is an open source project launched in 2013, helped popularize containers by making build-once-run-anywhere easy.</p><p>Docker’s early technical innovations included the Dockerfile (for specifying images), the docker run command, and the notion of layered, immutable images. Initially, Docker actually used LXC under the hood, but by late 2013 it replaced LXC with its own implementation (libcontainer, later evolving into containerd and runC). The result was a full stack: Docker Engine (daemon + CLI), a standard image format, and a registry (Docker Hub) for distribution. This bundling of components made Docker unlike previous container systems it was a <em>turnkey</em> container solution. As one history notes, Docker “separated itself from the pack by offering an entire ecosystem for container management”.</p><h3>Containers vs. Virtual Machines</h3><p>To appreciate Docker’s impact, it helps to contrast containers with traditional virtualization. Virtual machines (VMs) run entire guest operating systems with their own kernels on virtualized hardware. Each VM boots a full OS, which consumes gigabytes of disk and minutes of startup time. In contrast, Docker <strong>containers</strong> are lightweight, sharing the host’s kernel while isolating processes. A container is essentially one or more processes running in isolation, with their own filesystem and network namespaces, but reusing the same operating system kernel.</p><p>Key differences include:</p><ul><li><strong>Isolation:</strong> VMs isolate at the hardware and OS level (each VM has its own kernel), whereas containers isolate at the process level (they share the host kernel). Containers use Linux namespaces so that each container “sees” only its own processes, filesystems, and networks.</li><li><strong>Overhead:</strong> VMs require a full guest OS, which takes extra CPU, memory, and storage. Containers, by contrast, package only the application and its dependencies; they share common libraries and the kernel. This makes containers much more lightweight. For example, Docker documentation notes that a container can run many applications on a host because it “isolate[s] processes with all the files it needs to run” while sharing a kernel with others.</li><li><strong>Startup Time:</strong> A VM can take tens of seconds to minutes to boot a full OS. Containers typically start in seconds or less, since they just spin up a process in an isolated environment.</li><li><strong>Density:</strong> Because of lower overhead, you can pack many more containers than VMs on the same hardware. This is why Docker “provides a viable, cost-effective alternative to hypervisor-based virtual machines”.</li><li><strong>Performance:</strong> Containers can achieve near-native performance because they run directly on the host kernel. VMs incur some overhead for virtualization. However, VMs can sometimes offer stronger security isolation (different kernels) than standard containers, which only logically isolate resources.</li></ul><p>In summary, while VMs and containers both keep software isolated, containers are far more lightweight and portable. One AWS documentation page illustrates this: containers share the host OS kernel and run isolated applications, whereas virtual machines run a complete OS and virtual hardware. In practice, this means Docker containers can “run much more applications on a given server than VMs”. Containers typically carry seconds-long boot times and fit on a few hundred MB, whereas VMs might be gigabytes in size and take minutes to start.</p><h3>Core Concepts of Docker</h3><h3>Docker Containers</h3><p>A <strong>Docker container</strong> is a runnable instance of an image. It represents a self-contained execution environment: the application process (or processes) runs inside the container, and everything it needs (files, libraries, config) comes from the image or local mounts. Containers are isolated by Linux namespaces (so processes, network, mounts, UTS, IPC namespaces keep them separate) and resource-controlled by cgroups. In practice, a container has its own <strong>isolated filesystem</strong>, its own network interfaces/IP, and its own process tree, even though it ultimately runs on the host kernel.</p><p>A helpful analogy is that a container is like a <strong>shipping container for software</strong>. Just as a cargo container holds goods and can be loaded on any ship or truck without regard to its contents, a Docker container holds an application and can be run on any system with Docker. The industry lore (and Hykes himself) likens this to physical shipping containers with standard size and locks. Inside the container you can put any combination of app code, libraries, executables, etc., and the host doesn’t care <em>how</em> it got in there, it just sees a filesystem with everything ready to execute. This separation of concerns -<em>“write once, run anywhere” </em>is central to container appeal.</p><p>Containers are lightweight: by sharing the host kernel, many can run on the same machine with small incremental cost. If you stop a container, you simply kill those processes; the container instance goes away (its ephemeral writable layer is discarded by default). Because containers are meant to be short-lived and immutable, any state you want to keep must be stored outside (e.g., in a volume or external service). This immutability is an advantage for reproducibility: the container always starts from the same image. In contrast to VMs, containers boot in seconds. As one source notes, containers are <em>“closer to the metal”</em> and share a single kernel, so they “boot in seconds instead of minutes”, making them efficient for high-density workloads.</p><h3>Docker Images and Dockerfiles</h3><p>A <strong>Docker image</strong> is the static blueprint for a container. It is a read-only template, usually composed of layered filesystem changes, that includes everything needed to run the app. Images are built in layers: each instruction in a Dockerfile adds a new layer. For example, one layer might add an operating system (like Debian), another might add runtime libraries (like Python), and others might add application files. When you run a container, Docker mounts all these image layers (unioned together) plus a thin writable layer on top. Importantly, images are <em>immutable</em>: once built, the files in that image do not change. If you want a different setup, you build a new image. This immutability guarantees that an image is a fixed snapshot of an application environment.</p><p>Think of a Docker image like a <strong>house blueprint</strong>. The blueprint has all the instructions to build the house (foundation, walls, plumbing, etc.). Similarly, a Docker image “contains all of the files, binaries, libraries, and configurations to run a container”. It is analogous to a snapshot of a VM’s disk, but specialized for containers. An image is a snapshot of an environment, it’s like a blueprint. The image can be versioned by tags (e.g. app:v1, app:latest) so that you can update and roll back reliably. Any number of containers can be created from the same image (just like many houses from the same blueprint).</p><p>A <strong>Dockerfile</strong> is how you create images. It is a plain text file that contains a sequence of instructions. Each line of the Dockerfile (e.g. FROM, RUN, COPY, CMD) tells Docker how to assemble the image. Official Docker documentation describes it as “a text-based script that provides the instruction set on how to build the image”. For example, a simple Python app might use a Dockerfile like:</p><pre>FROM python:3.9-slim<br>WORKDIR /app<br>COPY requirements.txt .<br>RUN pip install -r requirements.txt<br>COPY . .<br>CMD [&quot;python&quot;, &quot;app.py&quot;]</pre><p>This script starts from a base image (python:3.9-slim), sets a working directory, copies files, installs dependencies, and finally specifies how to run the app. When you run docker build -t myapp:1.0 ., Docker processes this file: it pulls the base layers (if not present), then executes each step to form new layers. The result is an image tagged myapp:1.0. If you change the Dockerfile later, only the changed steps (layers) need rebuilding, thanks to Docker’s layer caching. In this way, the Dockerfile embodies <em>infrastructure-as-code</em>: the environment specification lives in version-controlled text, and anyone can rebuild the exact same image from it.</p><h3>Docker Registry and Docker Hub</h3><p>To share and deploy images, Docker uses container <strong>registries</strong>. A registry is a service where images are stored and managed. The default public registry is <strong>Docker Hub</strong>. Docker Hub acts like GitHub for containers: you can find millions of pre-built images there (official images for Ubuntu, nginx, Redis, etc.) or push your own. When you run docker pull ubuntu or docker run redis, Docker automatically fetches the image from Docker Hub. You can also push your images (docker push) to Docker Hub under your account.</p><p>Organizations often run private registries (e.g. Amazon ECR, Google GCR, or self-hosted Harbor) for proprietary images. Regardless, the workflow is the same: images are tagged by name and version, and the Docker Engine uses the registry’s HTTP API to download/upload layers<a href="https://docs.docker.com/get-started/docker-overview/#:~:text=Docker%20registries">docs.docker.com</a>. Docker’s docs emphasize that <em>“a Docker registry stores Docker images”</em>, and by default the client looks at Docker Hub<a href="https://docs.docker.com/get-started/docker-overview/#:~:text=Docker%20registries">docs.docker.com</a>. In Docker terminology, a <strong>repository</strong> is a collection of related images (often differentiated by tags). For example, myapp:1.0 and myapp:latest may be two tags in the myapp repository on a registry.</p><h3>Docker Engine (Daemon and Client)</h3><p>At the heart of Docker is the <strong>Docker Engine</strong>, which implements a <em>client-server architecture</em>. The server side is the <strong>Docker daemon</strong> (dockerd), a long-running background process. The client side is the docker command-line interface (CLI) that users type. When you run a command like docker run or docker build, the CLI sends an API request to the daemon. These two components communicate over RESTful APIs, typically via a Unix domain socket or network port. Docker also provides SDKs for various languages to call the same APIs.</p><p>The Docker daemon performs the heavy lifting: it manages images, containers, networks, and volumes. It listens for commands, pulls layers from registries, assembles the union filesystem, sets up namespaces and network bridges, and creates or stops container processes. For instance, Docker’s documentation notes that the daemon <em>“listens for Docker API requests and manages Docker objects such as images, containers, networks, and volumes”</em>. The CLI translates user commands (like docker ps, docker run, docker build) into these API calls. You can even have one Docker client communicate with multiple remote daemons. Docker Compose (discussed later) is another client that orchestrates multi-container apps by talking to the same daemon.</p><p>The relationship between client, daemon, and registry can be visualized as follows:</p><p>In the illustration above, the user types a docker run command on the client. The Docker daemon receives it, checks if the image is available locally (pulling from the registry if needed), and then creates a container. Under the hood, Docker uses a lightweight runtime (such as runC) to actually spawn the container process with the given namespaces and cgroup limits. The container then starts and runs the application as specified (entrypoint, commands, etc.). This client–daemon–container flow is the essence of Docker’s architecture.</p><h3>Layers and Filesystems</h3><p>An important technical detail is Docker’s <strong>union filesystem</strong> and layered image structure. Docker images are built layer by layer, and Docker uses a union mount to present them as a single unified root filesystem at runtime. Each layer is essentially a set of filesystem changes. For example, a layer might add a directory, install a package, or create a file. These layers are stored (often compressed) on disk, and many images can share common lower layers for efficiency.</p><p>When Docker <strong>runs</strong> a container, it assembles all the image’s layers into a union. On top of this, it adds a thin writable layer for the container’s runtime changes. Docker then sets the container’s root directory to this combined view (using chroot or similar). The result is that the container sees a single coherent filesystem. However, the read-only base layers remain untouched, so if the container writes or modifies files, those changes go into the top writable layer only.</p><p>This design has two benefits: (1) Disk space savings and speed, since shared layers don’t need to be duplicated for each container; (2) Immutability of images, because the original image layers are not altered by running containers. The Docker documentation explains: <em>“the container is created by setting the container’s root directory as the parent directory of the mounted union of all layers”</em>. If you start multiple containers from the same image, they each get their own top layer but share the lower layers. This means building images (with docker build) and transferring them (with docker push) is very efficient, because only changed layers need to move.</p><h3>Underlying Linux Features: Namespaces and Cgroups</h3><p>The isolation in Docker containers relies on two core Linux features: <strong>namespaces</strong> and <strong>cgroups</strong>. Namespaces partition kernel resources so that one set of processes only sees one view of the world. Docker typically uses several types of namespaces:</p><ul><li><strong>PID namespace:</strong> So the container’s process IDs start at 1 and are isolated from the host’s processes.</li><li><strong>Mount (filesystem) namespace:</strong> Each container gets its own root filesystem mount point (provided by the union filesystem layers).</li><li><strong>Network namespace:</strong> Each container can have its own virtual network interface, IP address, and routing table.</li><li><strong>IPC namespace:</strong> Isolates inter-process communication primitives (semaphores, message queues).</li><li><strong>UTS namespace:</strong> Allows the container to have its own hostname/domain.</li><li><strong>User namespace (optional):</strong> Can map container root user to a non-root on the host.</li></ul><p>Docker’s docs succinctly state: <em>“Docker uses a technology called namespaces to provide the isolated workspace called the container.”</em>. In practical terms, this means a process inside one container cannot see or affect processes, network, or files in another container or on the host. From the host’s perspective, all container processes still run (they just happen to be in different namespaces).</p><p><strong>Control groups (cgroups)</strong> enforce resource constraints on containers. When Docker starts a container, it places the container’s process into a new cgroup. The daemon can then limit how much CPU, memory, block I/O, and other resources that group can use. For example, you might limit a container to 512 MB of RAM or to at most 50% of one CPU core. Cgroups also account for usage so the system knows how much each container has consumed. As one source explains, cgroups allow each container to have its own “CPU, memory, and I/O bandwidth settings” and ensure those limits are enforced. In other words, cgroups make containers <em>resource-controlled</em>, just as VMs can have capped resources. Together, namespaces (isolation) and cgroups (resource limiting) are what truly make containers akin to lightweight VMs under the hood, all while avoiding the overhead of virtualization.</p><h3>Using Docker: Building and Running Containers</h3><p>Let’s walk through a simple example to see Docker in action. Suppose you have a web application (in Python, Node.js, Go, etc.). You start by writing a <strong>Dockerfile</strong> in the app’s directory, describing how to build an image. For instance:</p><pre>FROM python:3.9-slim<br>WORKDIR /app<br>COPY requirements.txt .<br>RUN pip install -r requirements.txt<br>COPY . .<br>CMD [&quot;python&quot;, &quot;app.py&quot;]</pre><p>This file declares a base image (python:3.9-slim), copies your app’s code, installs dependencies, and sets the command to run. Once the Dockerfile is ready, you build the image with:</p><p><strong>Build the image:</strong></p><pre>docker build -t myapp:1.0 .</pre><p>The docker build command tells Docker to read the Dockerfile in the current directory (.) and construct a new image tagged myapp:1.0. This process may involve downloading base layers from Docker Hub (if not cached) and then applying the instructions one layer at a time.</p><p><strong>Verify the image (optional):</strong></p><pre>docker image ls</pre><p>You should see myapp 1.0 listed among your local images.</p><p><strong>Run a container:</strong></p><pre>docker run -d -p 5000:5000 myapp:1.0</pre><p>This tells Docker to start a container from the myapp:1.0 image. The -d flag (detach) runs the container in the background. The -p 5000:5000 flag maps port 5000 of the container to port 5000 on the host. For example, if your app listens on port 5000, it will now be accessible at localhost:5000 on your machine. As the Docker docs illustrate, -d means <em>“start in background”</em> and -p means <em>“publish ports”</em>. After a moment, the container is running and your app is live.</p><p>This simple workflow can be summarized:</p><ol><li><strong>Write a Dockerfile</strong> describing the environment and app.</li><li><strong>Build the image</strong> with docker build -t name:tag ..</li><li><strong>Run the container</strong> with docker run, specifying any needed options.</li></ol><p>Behind the scenes, docker run did the following: (1) if needed, pulled the image layers from the registry; (2) allocated a filesystem (overlay of image layers + writable layer); (3) allocated networking (bridge and port mapping); (4) created a new container and started the app process. You can see this by running docker ps (lists running containers) or docker inspect &lt;container&gt; for details. Stopping the container (docker stop) will terminate those processes; deleting it (docker rm) will remove the ephemeral writable layer. If you update your code, you rebuild the image and start new containers, ensuring reproducibility.</p><p>Throughout this process, note that the <strong>image</strong> you built is like a packed box that can be shared. You can push myapp:1.0 to Docker Hub or another registry with docker push, and anyone else (or any server) could then docker pull myapp:1.0 and run the exact same container. Docker’s documentation emphasizes that an image “contains everything needed to run a process”, so moving it between systems doesn’t break the application.</p><h3>Docker Ecosystem and Related Tools</h3><p>Docker itself is just one part of a larger ecosystem of tools and standards around containers. Key components include:</p><ul><li><strong>Docker Compose:</strong> A tool for defining and running multi-container applications via a YAML file. Instead of manually running each docker run command, you create a docker-compose.yml that lists all the services (containers), their images, networks, and volumes. Then docker-compose up brings up the whole application stack with one command. For example, a web app might have a service for the front-end container and another for a database. Compose handles creating a shared network so they see each other by service name. The Docker docs describe Compose as <em>“a command-line tool that uses YAML files to define and run multicontainer applications”</em>. This makes it easy to version-control and reproduce complex setups (often used in development or simple deployments).</li><li><strong>Container Registries:</strong> We covered Docker Hub as the default public registry. In addition, most cloud providers offer container registries: AWS ECR, Google GCR, Azure Container Registry, etc. Organizations often run private registries (like Harbor or private Docker Registry) for proprietary images. The workflows (push/pull by name) are the same regardless of registry. Some CI/CD systems (like GitHub Actions or GitLab) can automatically build and publish images after code is merged.</li><li><strong>Docker Swarm:</strong> Docker includes built-in cluster management called <em>Swarm mode</em>. When you initialize a swarm (docker swarm init), your Docker Engine joins or creates a Swarm cluster. In Swarm mode, you can deploy services (sets of identical containers) and Docker will schedule them across the nodes. Swarm provides features like load balancing, scaling, and rolling updates. Notably, Swarm is <em>integrated into the Docker Engine</em>, so no separate installation is needed. As Docker Docs say, <em>“Current versions of Docker include Swarm mode for natively managing a cluster of Docker Engines”</em>. (Swarm uses manager and worker nodes internally, but Docker manages all coordination.) However, Swarm’s popularity declined once Kubernetes became dominant (Docker later deprecated parts of Swarm in favor of Kubernetes support).</li><li><strong>Container Runtimes - containerd and runC:</strong> Docker originally included its own low-level runtime, but it eventually spun those out. Today, Docker Engine actually uses containerd under the hood, and containerd in turn uses runC. In 2017, Docker donated containerd to the Cloud Native Computing Foundation. Containerd’s job is to provide basic container lifecycle (create, start, stop, etc.), managing namespaces and cgroups on behalf of Docker. The higher-level Docker daemon (or Kubernetes via the CRI) interacts with containerd to run containers. There are other OCI-compliant runtimes too (for example, CRI-O in Kubernetes setups). Docker’s contribution of containerd and runc to open standards helped ensure a consistent ecosystem: “any container runtime that implements the [OCI runtime spec] can run a Docker/OCI image”.</li><li><strong>Docker Desktop:</strong> For developer convenience on Windows/Mac, Docker Desktop packages the Docker Engine inside a lightweight VM along with a GUI. It includes Docker Engine, CLI, Docker Compose, Kubernetes (optional), and credential helpers. Docker Desktop makes it easy to run containers on a laptop. (It also has licensing for enterprise use now, but fundamentally it’s just Docker Engine packaged with user-friendly tools.)</li><li><strong>Other Tools:</strong> The ecosystem also includes things like Docker Compose (mentioned above), Docker Swarm (above), Docker Trusted Registry, and alternatives like Podman or Buildah that can build/run OCI containers. The Open Container Initiative (OCI) defines the image and runtime standards that Docker helped originate (Docker’s original image format became the OCI Image Spec). In practice, most developers simply say “Docker” when they mean “OCI-compliant container.”</li></ul><h3>Impact on Cloud-Native Development</h3><p>Docker’s influence goes far beyond the tool itself; it reshaped how software is built and delivered. Before Docker, packaging an application often meant configuring servers or installing libraries manually (or building bulky VM images). Docker introduced the idea that <em>everything can be containerized</em>, enabling new development paradigms:</p><ul><li><strong>Microservices:</strong> Because containers are small and isolated, teams started breaking monolithic apps into many containerized services. Each microservice could be developed, scaled, and deployed independently. Docker made it practical to spin up dozens or hundreds of service instances. As one analysis notes, containers made application building blocks easily composable and modular. This, combined with container orchestration (Kubernetes, etc.), underpins modern microservices architectures.</li><li><strong>DevOps and CI/CD:</strong> Docker brought developer workflows closer to production. A container image provides a consistent environment, so CI systems can build and test inside containers identical to production. The Docker docs highlight a CI example: developers “share their work… using Docker containers,” push the container to a test environment for automated tests, and then simply push the updated image to production if all is good. This pipeline reduces “works on my machine” issues and accelerates release cycles. In fact, teams often deploy dozens (or hundreds) of times more frequently thanks to container-based CI/CD.</li><li><strong>Infrastructure as Code:</strong> By encoding system configuration in Dockerfiles, YAML, and other artifacts, Docker helped popularize <em>infrastructure-as-code</em>. The entire environment (OS libs, dependencies, config) is captured in code that can be version-controlled and reviewed. This practice adds traceability and repeatability to operations.</li><li><strong>Orchestration and Clusters:</strong> As applications became containerized, the need to manage many containers arose. Docker’s success spurred the creation and adoption of orchestration platforms. Kubernetes, originally built at Google, quickly became the industry standard. It was donated to the CNCF in 2016 and is now the most widely used container orchestrator. Docker itself integrated Kubernetes into Docker Desktop. (Docker’s own Swarm mode is now less common, but it was an early answer to multi-host clustering.) Thanks to containers, it’s possible to automate scaling, self-healing, service discovery, and rolling updates at a level not previously possible with VMs alone.</li><li><strong>Cloud Providers and Standardization:</strong> Major clouds embraced Docker images. Every cloud provider’s container service (AWS ECS/EKS, Azure AKS, Google GKE, etc.) is based on the Docker/OCI image format. Docker images became the universal packaging unit for cloud deployments. The Open Container Initiative (OCI) emerged to prevent fragmentation: Docker donated runc to OCI, which became the first OCI runtime, and containerd was contributed to CNCF. As a result, any OCI-compliant container image can run on any compliant runtime and orchestrator. This open standardization was a direct outcome of Docker’s influence.</li><li><strong>Community and Ecosystem:</strong> Docker’s creation of a container-centric ecosystem paved the way for CNCF and other cloud-native efforts. The CNCF now hosts a large portfolio of projects (Kubernetes, Prometheus, Envoy, etc.) that all assume container-based deployment. Docker itself donated key pieces (containerd, runC) and many tools built on Docker (like Moby and BuildKit) became open source projects. Today, the phrase “cloud-native” often implies running in Docker (or OCI) containers.</li><li><strong>Legacy and Future:</strong> While Docker Inc. restructured (selling its enterprise arm to Mirantis in 2019, refocusing on developers), the technology lives on. Containers remain the standard for packaging software. New developments (lightweight VMs like Firecracker, sandboxed runtimes like gVisor, even WebAssembly-based containers) all extend the same core concept Docker popularized. In short, Docker made containers first-class citizens in software development, and that legacy continues to drive innovation.</li></ul><h3>Conclusion</h3><p>Docker fundamentally changed software delivery. By packaging applications and their dependencies into portable containers, Docker solved longstanding consistency problems and unlocked new ways of building systems. We’ve seen how Docker grew out of older container efforts (from Unix <em>chroot</em> to LXC), and how Solomon Hykes’s 2013 pivot turned dotCloud’s internal tech into the open source Docker Engine. Docker’s core concepts, container vs image vs registry, the layered filesystem, infrastructure-as-code via Dockerfiles revolutionized developer workflows.</p><p>Technically, Docker rests on Linux namespaces, cgroups, and union filesystems. These primitives provide the “sandbox” in which Docker containers run: isolated yet lightweight. In Docker’s architecture, the daemon manages images and containers while the CLI (and tools like Docker Compose) orchestrate multi-container apps. Official docs define these parts clearly: a Docker container is an isolated, runnable instance of an image, an image is an immutable template or “blueprint” for containers, and the registry is where images are stored.</p><p>Docker’s impact extends to the cloud-native era. Containers became the standard deployment unit, enabling microservices, Kubernetes orchestration, and modern DevOps at scale. Developers now routinely build, test, and deploy software in containers, as Docker promotes “fast, consistent delivery” across environments. The shift from monolithic VMs to agile containers has led to more scalable, reliable, and efficient systems. Today, tools like Docker Compose, Docker Hub, and containerd (now a CNCF project) round out the ecosystem that Docker sparked.</p><p>In summary, Docker matters because it democratized and standardized containerization. It turned kernel features (namespaces, cgroups) into a developer-friendly platform. It combined the portability of shipping containers with the flexibility of code, and it integrated the workflow (build, ship, run) in a seamless way. The industry has responded by reorganizing itself around containers (see the rise of Kubernetes and CNCF). As Docker’s own retrospective notes, “the rise of containers led to a shift in the way applications are built from monoliths to networks of microservices”.</p><p>Today, Docker’s legacy endures. Containerization is ubiquitous in cloud, edge, and even IoT deployments. Future trends (microVMs, wasmtime, serverless) often build on Docker’s principles. The <em>shipping container</em> metaphor lives on: just as cargo containers transformed global trade, Docker containers have transformed software delivery. The key takeaway is that Docker provides a reliable, repeatable way to package and run software anywhere, a concept that has irreversibly changed how we build and operate systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee0391fc1bac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ImagePolicy Webhook in Kubernetes Part 2]]></title>
            <link>https://pramodhm112.medium.com/imagepolicy-webhook-in-kubernetes-continued-7c5bdc65d755?source=rss-e1df5bff44a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c5bdc65d755</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kubernetes-cluster]]></category>
            <category><![CDATA[k8s-security]]></category>
            <category><![CDATA[kubernetes-security]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[Pramodh Kumar M]]></dc:creator>
            <pubDate>Sun, 28 Apr 2024 14:13:14 GMT</pubDate>
            <atom:updated>2024-04-28T14:20:08.125Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y1DrxnIcv_dhTKr4kmuWsw.jpeg" /></figure><p>In the previous <a href="https://pramodhm112.medium.com/imagepolicy-webhook-in-kubernetes-85f25d3f09fb">article</a>, I provided an overview of the admission controller, covering its general functionality and offering a high-level explanation of its implementation.</p><p>In this step-by-step guide, we will walk through the process of implementing an admission controller. The specific Linux operating system you use is not crucial, as long as you have Python 3 and Docker installed on your system.</p><p>Below are the commands to set up the project</p><pre>#check python version<br>python3 -V<br><br>#ensure you have pip and venv installed, below is an example for ubuntu<br>sudo apt install -y python3-pip<br>sudo apt install -y build-essential libssl-dev libffi-dev python3-dev<br>sudo apt install -y python3-venv<br><br>mkdir environments<br>cd environments<br><br>python3 -m venv k8s<br>source k8s/bin/activate<br>cd k8s<br><br>pip install flask</pre><p>Create image_policy_webhook.py file</p><pre>from flask import Flask, request, jsonify<br><br>app = Flask(__name__)<br><br>@app.route(&#39;/validate&#39;, methods=[&#39;POST&#39;])<br>def validate_image():<br>    allowed_registries = [&#39;registry.example.com&#39;, &#39;docker.io&#39;]<br><br>    admission_review = request.get_json()<br>    pod = admission_review[&#39;request&#39;][&#39;object&#39;]<br><br>    for container in pod[&#39;spec&#39;][&#39;containers&#39;]:<br>        image = container[&#39;image&#39;]<br>        registry = image.split(&#39;/&#39;)[0]<br><br>        if registry not in allowed_registries:<br>            return jsonify({<br>                &#39;apiVersion&#39;: &#39;admission.k8s.io/v1&#39;,<br>                &#39;kind&#39;: &#39;AdmissionReview&#39;,<br>                &#39;response&#39;: {<br>                    &#39;uid&#39;: admission_review[&#39;request&#39;][&#39;uid&#39;],<br>                    &#39;allowed&#39;: False,<br>                    &#39;status&#39;: {<br>                        &#39;message&#39;: f&quot;Image {image} is not allowed. Allowed registries: {&#39;, &#39;.join(allowed_registries)}&quot;<br>                    }<br>                }<br>            })<br><br>    return jsonify({<br>        &#39;apiVersion&#39;: &#39;admission.k8s.io/v1&#39;,<br>        &#39;kind&#39;: &#39;AdmissionReview&#39;,<br>        &#39;response&#39;: {<br>            &#39;uid&#39;: admission_review[&#39;request&#39;][&#39;uid&#39;],<br>            &#39;allowed&#39;: True<br>        }<br>    })<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(host=&#39;0.0.0.0&#39;, port=8080, ssl_context=(&#39;tls.crt&#39;, &#39;tls.key&#39;))</pre><p>Create requirements.txt file</p><pre>pip freeze &gt; requirements.txt</pre><p>Create Dockerfile</p><pre>FROM python:3.9-slim<br><br>WORKDIR /app<br><br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br><br>COPY image_policy_webhook.py .<br><br>CMD [&quot;python&quot;, &quot;image_policy_webhook.py&quot;]</pre><pre>docker build -t image-policy-webhook .</pre><p>Generate the certificate with the configuration file webhook-server.conf</p><pre>[req]<br>distinguished_name = req_distinguished_name<br>x509_extensions = v3_req<br>prompt = no<br><br>[req_distinguished_name]<br>CN = image-policy-webhook.default.svc<br><br>[v3_req]<br>basicConstraints = CA:FALSE<br>keyUsage = critical, digitalSignature, keyEncipherment<br>extendedKeyUsage = serverAuth<br>subjectAltName = DNS:image-policy-webhook.default.svc</pre><p>The command below shows that I have generated the certificate in the master node where K8s is set up. The path for the CA certs is the default (/etc/kubernetes/pki/ca.key &amp; /etc/kubernetes/pki/ca.key)</p><pre>openssl genrsa -out webhook-server-key.pem 2048<br><br>openssl req -new -key webhook-server-key.pem -out webhook-server.csr -config webhook-server.conf<br><br>sudo openssl x509 -req -in webhook-server.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial -out webhook-server-cert.pem -days 365 -extfile webhook-server.conf -extensions v3_req<br><br>sudo openssl x509 -in webhook-server-cert.pem -text -noout<br><br>mv webhook-server-key.pem tls.key<br><br>mv webhook-server-cert.pem tls.crt</pre><p>Create Secret</p><pre>kubectl create secret tls tls-secret --cert=tls.crt --key=tls.key</pre><p>Create a new file named webhook-deployment.yaml and add the following content</p><pre>---<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: image-policy-webhook<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: image-policy-webhook<br>  template:<br>    metadata:<br>      labels:<br>        app: image-policy-webhook<br>    spec:<br>      containers:<br>      - name: webhook<br>        image: image-policy-webhook<br>        ports:<br>        - containerPort: 8080<br>        volumeMounts:<br>        - name: tls-certs<br>          mountPath: /app/certs<br>          readOnly: true<br>      volumes:<br>      - name: tls-certs<br>        secret:<br>          secretName: tls-secret<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: image-policy-webhook<br>spec:<br>  selector:<br>    app: image-policy-webhook<br>  ports:<br>  - port: 443<br>    targetPort: 8080</pre><p>Apply the deployment YAML file</p><pre>kubectl apply -f webhook-deployment.yaml</pre><p>Create a new file named validating-webhook-configuration.yaml and add the following content</p><pre>apiVersion: admissionregistration.k8s.io/v1<br>kind: ValidatingWebhookConfiguration<br>metadata:<br>  name: image-policy-webhook<br>webhooks:<br>- name: image-policy.example.com<br>  clientConfig:<br>    service:<br>      name: image-policy-webhook<br>      namespace: default<br>      path: &quot;/validate&quot;<br>      port: 443<br>    caBundle: &quot;&lt;base64-encoded-ca-certificate&gt;&quot;<br>  rules:<br>  - operations: [&quot;CREATE&quot;, &quot;UPDATE&quot;]<br>    apiGroups: [&quot;&quot;]<br>    apiVersions: [&quot;v1&quot;]<br>    resources: [&quot;pods&quot;]<br>  admissionReviewVersions: [&quot;v1&quot;]<br>  sideEffects: None</pre><p>Replace &lt;base64-encoded-certificate&gt; with the base64-encoded certificate obtained using the below command</p><pre>cat tls.crt | base64 | tr -d &#39;\n&#39;</pre><p>Apply the ValidatingWebhookConfiguration YAML file</p><pre>kubectl apply -f validating-webhook-configuration.yaml</pre><p>Test the Image Policy Webhook</p><p>Create a pod with an allowed image:</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: allowed-pod<br>spec:<br>  containers:<br>  - name: test-container<br>    image: docker.io/nginx:latest</pre><p>The pod should be created successfully.</p><p>Create a pod with a disallowed image:</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: disallowed-pod<br>spec:<br>  containers:<br>  - name: test-container<br>    image: gcr.io/google-containers/nginx:latest</pre><p>The pod creation should be rejected with the reason “Image not allowed”.</p><p>That’s it! You have now implemented the Image Policy Webhook in your Kubernetes cluster. The webhook server will intercept pod creation and update requests and allow or reject them based on the specified image policy.</p><p>Note: Make sure to replace the registry with your actual container registry URL and adjust the allowed image name in the webhook server code according to your requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c5bdc65d755" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ImagePolicy Webhook in Kubernetes Part 1]]></title>
            <link>https://pramodhm112.medium.com/imagepolicy-webhook-in-kubernetes-85f25d3f09fb?source=rss-e1df5bff44a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/85f25d3f09fb</guid>
            <category><![CDATA[kubernetes-cluster]]></category>
            <category><![CDATA[kubernetes-security]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[k8s-security]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[Pramodh Kumar M]]></dc:creator>
            <pubDate>Sat, 20 Apr 2024 00:35:36 GMT</pubDate>
            <atom:updated>2024-04-28T14:19:41.506Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TNzpiv9UmpZ0gu8x.png" /></figure><p>ImagePolicy webhook is a Kubernetes feature that allows you to enforce policies and restrictions on the container images that can be deployed in your cluster. They provide a way to intercept and validate requests to the Kubernetes API server before a pod is created or updated.</p><p>Here are some key points about ImagePolicy webhooks:</p><p>Admission Control: ImagePolicy webhooks are part of the Kubernetes admission control process. When a pod creation or update request is sent to the API server, the ImagePolicy webhook is invoked to validate the container images specified in the pod specification.</p><p>External Webhook Server: The ImagePolicy webhook is implemented as an external webhook server. You must deploy and configure the webhook server separately from your Kubernetes cluster. The webhook server receives admission requests from the Kubernetes API server and returns an admission response indicating whether the pod should be allowed or denied.</p><p>Policy Evaluation: The ImagePolicy webhook server evaluates the container images against predefined policies. These policies can be based on various criteria, such as:</p><ul><li>Image registry: Restrict images to specific trusted registries.</li><li>Image tag: Enforce the use of specific image tags, such as “latest” or versioned tags.</li><li>Image vulnerability scanning: Integrate with image scanning tools to allow only images that pass vulnerability checks.</li><li>Image signing: Require images to be digitally signed by trusted authorities.</li></ul><p>Webhook Configuration: To enable ImagePolicy webhooks, you need to create a Kubernetes MutatingWebhookConfiguration or ValidatingWebhookConfiguration object. This configuration specifies the webhook server URL, the API version and resource (pods) to intercept, and any additional settings like certificate authentication.</p><p>Webhook Response: When the ImagePolicy webhook server receives an admission request, it evaluates the container images against the defined policies. If the images comply with the policies, the webhook server returns an admission response with “allowed: true”. If the images violate the policies, the response will have “allowed: false”, and the pod creation or update will be rejected.</p><p>Feedback and Reporting: ImagePolicy webhooks can provide detailed feedback and reasons for policy violations. The webhook server can include explanatory messages in the admission response, which are then visible in the Kubernetes API server logs and can be surfaced to users through kubectl or other tools.</p><p>Integration with Other Systems: ImagePolicy webhooks can be integrated with external systems for enhanced functionality. For example, you can integrate with image scanning tools to automatically validate images against known vulnerabilities or with image signing systems to verify the integrity and authenticity of images.</p><p>By implementing ImagePolicy webhooks, you can enforce granular control over the container images deployed in your Kubernetes cluster. This helps to improve security by ensuring that only approved and trusted images are allowed to run, reducing the risk of deploying malicious or vulnerable containers.</p><p>It’s important to carefully design and test your ImagePolicy webhook policies to strike a balance between security and usability. Overly restrictive policies can hinder development and deployment workflows, while overly permissive policies may introduce security risks.</p><p>When configuring ImagePolicy webhooks, ensure that the webhook server is highly available and can handle the volume of admission requests. Also, consider the performance impact of the webhook on pod creation and update operations, as the admission control process adds an additional step to the API server request flow.</p><p>Here’s an example of how you can implement an ImagePolicy webhook in Kubernetes:</p><p>Webhook Server: First, you need to create a webhook server that will handle the ImagePolicy validation. Here is an example using a Python Flask server:</p><pre>from flask import Flask, request, jsonify<br><br>app = Flask(__name__)<br><br>@app.route(&#39;/validate&#39;, methods=[&#39;POST&#39;])<br>def validate_image():<br>    allowed_registries = [&#39;registry.example.com&#39;, &#39;docker.io&#39;]<br><br>    admission_review = request.get_json()<br>    pod = admission_review[&#39;request&#39;][&#39;object&#39;]<br><br>    for container in pod[&#39;spec&#39;][&#39;containers&#39;]:<br>        image = container[&#39;image&#39;]<br>        registry = image.split(&#39;/&#39;)[0]<br><br>        if registry not in allowed_registries:<br>            return jsonify({<br>                &#39;apiVersion&#39;: &#39;admission.k8s.io/v1&#39;,<br>                &#39;kind&#39;: &#39;AdmissionReview&#39;,<br>                &#39;response&#39;: {<br>                    &#39;uid&#39;: admission_review[&#39;request&#39;][&#39;uid&#39;],<br>                    &#39;allowed&#39;: False,<br>                    &#39;status&#39;: {<br>                        &#39;message&#39;: f&quot;Image {image} is not allowed. Allowed registries: {&#39;, &#39;.join(allowed_registries)}&quot;<br>                    }<br>                }<br>            })<br><br>    return jsonify({<br>        &#39;apiVersion&#39;: &#39;admission.k8s.io/v1&#39;,<br>        &#39;kind&#39;: &#39;AdmissionReview&#39;,<br>        &#39;response&#39;: {<br>            &#39;uid&#39;: admission_review[&#39;request&#39;][&#39;uid&#39;],<br>            &#39;allowed&#39;: True<br>        }<br>    })<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(host=&#39;0.0.0.0&#39;, port=8080, ssl_context=(&#39;/app/certs/tls.crt&#39;, &#39;/app/certs/tls.key&#39;))</pre><p>In this example, the webhook server validates the container images against a list of allowed registries. If any image is not from an allowed registry, the webhook returns a response with allowed: False and a corresponding message. If all images are from allowed registries, the webhook returns allowed: True.</p><p>Webhook Configuration: Next, you need to create a Kubernetes ValidatingWebhookConfiguration to register the ImagePolicy webhook. Here is a configuration:</p><pre>apiVersion: admissionregistration.k8s.io/v1<br>kind: ValidatingWebhookConfiguration<br>metadata:<br>  name: image-policy-webhook<br>webhooks:<br>  - name: image-policy.example.com<br>    clientConfig:<br>      service:<br>        name: image-policy-webhook<br>        namespace: default<br>        path: &quot;/validate&quot;<br>        port: 443<br>      caBundle: &lt;base64-encoded-ca-certificate&gt;<br>    rules:<br>      - operations: [&quot;CREATE&quot;, &quot;UPDATE&quot;]<br>        apiGroups: [&quot;&quot;]<br>        apiVersions: [&quot;v1&quot;]<br>        resources: [&quot;pods&quot;]<br>    admissionReviewVersions: [&quot;v1&quot;]<br>    sideEffects: None</pre><p>In this configuration:</p><ul><li>The clientConfig section specifies the URL of the webhook server. In this example, it assumes the webhook server is running as a Kubernetes service named image-policy-webhook in the default namespace.</li><li>The caBundle field should contain the base64-encoded CA certificate used to sign the webhook server&#39;s TLS certificate.</li><li>The rules section defines the API operations, groups, versions, and resources that the webhook should intercept. In this case, it intercepts pod creation and update operations.</li></ul><p>Deploy the Webhook: Deploy the webhook server and the ValidatingWebhookConfiguration to your Kubernetes cluster. You can create a Kubernetes deployment for the webhook server and apply the webhook configuration using kubectl apply.</p><p>Test the ImagePolicy Webhook: Create a pod that specifies a container image from an allowed registry and another pod with an image from a disallowed registry. Observe the behavior of the ImagePolicy webhook:</p><ul><li>The pod with the allowed image should be successfully created.</li><li>The pod with the disallowed image should be rejected, and you should see a corresponding error message in the Kubernetes API server logs or when describing the pod.</li></ul><p>This is a basic example to illustrate the concept of ImagePolicy webhooks. In a real-world scenario, you would enhance the webhook server to include more sophisticated policy evaluation logic, handle edge cases, and integrate with external systems as needed.</p><p>More on configuration:</p><p>To configure the Flask server for the ImagePolicy webhook, you need to follow these steps:</p><p>Install Dependencies: Make sure you have Python and Flask installed. You can install Flask using pip:</p><pre>pip install flask<br><br>pip freeze &gt; requirements.txt</pre><p>Create the Flask Server: Create a new Python file, for example, image_policy_webhook.py, and add the Flask server code provided in the previous example:</p><pre>from flask import Flask, request, jsonify<br><br>app = Flask(__name__)<br><br>@app.route(&#39;/validate&#39;, methods=[&#39;POST&#39;])<br>def validate_image():<br>    # Webhook validation logic goes here<br>    # ...<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(host=&#39;0.0.0.0&#39;, port=8080, ssl_context=(&#39;/app/certs/tls.crt&#39;, &#39;/app/certs/tls.key&#39;))</pre><p>Configure TLS: To secure the communication between the Kubernetes API server and the webhook server, it’s recommended to use TLS encryption. You must generate a TLS certificate and key for the webhook server.</p><p>You can generate a self-signed certificate using OpenSSL:</p><pre>openssl genrsa -out webhook-server-key.pem 2048<br><br>openssl req -new -key webhook-server-key.pem -out webhook-server.csr -config webhook-server.conf<br><br>openssl x509 -req -in webhook-server.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial -out webhook-server-cert.pem -days 365 -extfile webhook-server.conf -extensions v3_req</pre><p>Below is the configuration for file named webhook-server.conf</p><pre>[req]<br>distinguished_name = req_distinguished_name<br>x509_extensions = v3_req<br>prompt = no<br><br>[req_distinguished_name]<br>CN = image-policy-webhook.default.svc<br><br>[v3_req]<br>basicConstraints = CA:FALSE<br>keyUsage = critical, digitalSignature, keyEncipherment<br>extendedKeyUsage = serverAuth<br>subjectAltName = DNS:image-policy-webhook.default.svc</pre><p>Containerize the Webhook Server: Create a Dockerfile to containerize the Flask server:</p><pre>FROM python:3.9-slim<br><br>WORKDIR /app<br><br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br><br>COPY image_policy_webhook.py .<br><br><br>CMD [&quot;python&quot;, &quot;image_policy_webhook.py&quot;]</pre><p>Build the Docker image:</p><pre>docker build -t image-policy-webhook .</pre><p>Create a secret as below</p><pre>kubectl create secret tls tls-secret --cert=tls.crt --key=tls.key</pre><p>Deploy the Webhook Server: Create a Kubernetes deployment and service for the webhook server. Here’s the deployment YAML:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: image-policy-webhook<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: image-policy-webhook<br>  template:<br>    metadata:<br>      labels:<br>        app: image-policy-webhook<br>    spec:<br>      containers:<br>      - name: webhook<br>        image: pramodhm/image-policy-webhook:v5<br>        ports:<br>        - containerPort: 8080<br>        volumeMounts:<br>        - name: tls-certs<br>          mountPath: /app/certs<br>          readOnly: true<br>      volumes:<br>      - name: tls-certs<br>        secret:<br>          secretName: tls-secret<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: image-policy-webhook<br>spec:<br>  selector:<br>    app: image-policy-webhook<br>  ports:<br>  - port: 443<br>    targetPort: 8080</pre><p>Apply the deployment and service YAML:</p><pre>kubectl apply -f webhook-deployment.yaml</pre><p>Configure the Webhook in Kubernetes: Create the ValidatingWebhookConfiguration YAML as shown in the previous example, and apply it to your Kubernetes cluster:</p><pre>kubectl apply -f validating-webhook-configuration.yaml</pre><p>Make sure to replace the &lt;base64-encoded-ca-certificate&gt; placeholder in the webhook configuration with the actual base64-encoded CA certificate used to sign the webhook server&#39;s TLS certificate.</p><p>With these steps, the Flask server should be configured and deployed as an ImagePolicy webhook in your Kubernetes cluster. The webhook will intercept pod creation and update requests and validate the container images based on the defined policies.</p><p>Remember to update the webhook server code with your specific policy evaluation logic and any additional required configurations.</p><p>While ImagePolicy Webhooks offer significant benefits in terms of security and control, it’s important to carefully design and test the policies to ensure they strike the right balance between security and usability. Overly restrictive policies can hinder development and deployment workflows, while overly permissive policies may introduce security risks.</p><p>In conclusion, the ImagePolicy Webhook is a valuable tool in the Kubernetes security arsenal. By implementing custom admission control policies for container images, you can enforce granular security controls, mitigate the risk of deploying vulnerable or untrusted containers, and maintain a secure and compliant Kubernetes environment. It empowers you to define and enforce image policies that align with your organization’s security requirements and best practices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85f25d3f09fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basics of API in Jira, Confluence, and Bitbucket]]></title>
            <link>https://pramodhm112.medium.com/basics-of-api-in-jira-confluence-and-bitbucket-8d248ecce42d?source=rss-e1df5bff44a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d248ecce42d</guid>
            <dc:creator><![CDATA[Pramodh Kumar M]]></dc:creator>
            <pubDate>Sat, 04 Mar 2023 04:06:43 GMT</pubDate>
            <atom:updated>2023-03-04T04:06:43.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d7kl_8ZyTbMlEG_pJE0Gww.png" /></figure><p>How many times have you thought in your mind about the tasks that were given to you or the tasks that you would do via User Interface in your company and whether they can be achieved via API/Automation?<br>Here’s an article that will get you started on the basics of the API journey in Atlassian products.</p><p>We will look at creating basic elements in Jira, Confluence, and Bitbucket</p><p>Let me start with Jira, it’s the issue<br>To create an issue</p><pre>curl --request POST \<br> --url &#39;https://your-site.atlassian.net/rest/api/3/issue&#39; \<br> --user &#39;your-email:api-token&#39; \<br> --header &#39;Accept: application/json&#39; \<br> --header &#39;Content-Type: application/json&#39; \<br> --data &#39;{&quot;fields&quot; : {&quot;summary&quot; : &quot;Issue Summary - Test&quot;,<br> &quot;issuetype&quot; : {&quot;id&quot; : &quot;10000&quot;},<br> &quot;project&quot; : {&quot;id&quot; : &quot;10000&quot;},<br> &quot;assignee&quot; : {&quot;id&quot; : &quot;5d36b583beedf60c26aa372d&quot;} } }&#39;</pre><p>Where to get the details like token, issue type ID, project ID, and assignee ID?</p><p>The token can be generated here<br><a href="https://id.atlassian.com/manage-profile/security/api-tokens">https://id.atlassian.com/manage-profile/security/api-tokens</a></p><p>Here’s the link that will help you in getting Project ID<br><a href="https://confluence.atlassian.com/jirakb/how-to-get-project-id-from-the-jira-user-interface-827341414.html">https://confluence.atlassian.com/jirakb/how-to-get-project-id-from-the-jira-user-interface-827341414.html</a></p><p>With API, to get project ID it goes like this</p><pre>curl --request GET \<br> --url &#39;https://your-domain.atlassian.net/rest/api/3/project/{projectKey}&#39; \<br> --user &#39;your-email:api-token&#39; \<br> --header &#39;Accept: application/json&#39;<br>https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-projects/#api-rest-api-3-project-projectidorkey-get</pre><p>Issue ID</p><pre>curl --request GET \<br> --url &#39;https://your-domain.atlassian.net/rest/api/3/issuetype&#39; \<br> --user &#39;your-email:api-token&#39; \<br> --header &#39;Accept: application/json&#39;</pre><p>Get the Account ID of Users</p><pre>curl --request GET \<br> --url &#39;https://your-domain.atlassian.com/rest/api/3/user/bulk/migration&#39; \<br> --user &#39;your-email:api-token&#39; \<br> --header &#39;Accept: application/json&#39;</pre><p>Now that you have all the fields to create an issue, fill in the values and create an issue!</p><p><strong>Explore more and master yourself in API!</strong><br>The link to API documentation is here<br><a href="https://developer.atlassian.com/cloud/jira/platform/rest/v3/intro/">https://developer.atlassian.com/cloud/jira/platform/rest/v3/intro</a></p><p>How to create Confluence pages using API?<br>To create an empty page</p><pre>curl --request POST \<br> --url &#39;https://your-domain.atlassian.net/wiki/rest/api/content&#39; \<br> --user &#39;your-email:api-token&#39; \<br> --header &#39;Accept: application/json&#39; \<br> --header &#39;Content-Type: application/json&#39; \<br> --data &#39;{&quot;title&quot;: &quot;Page title&quot;, &quot;type&quot;: &quot;page&quot;, &quot;space&quot;: {&quot;key&quot;: &quot;spaceKey&quot;}, &quot;status&quot;: &quot;current&quot;}&#39;</pre><p>Here’s how you would add the data in the API</p><pre>curl --request POST \<br> --url &#39;https://your-domain.atlassian.net/wiki/rest/api/content&#39; \<br> --user &#39;your-email:api-token&#39; \<br> --header &#39;Accept: application/json&#39; \<br> --header &#39;Content-Type: application/json&#39; \<br> --data &#39;{&quot;title&quot;: &quot;Page title&quot;, &quot;type&quot;: &quot;page&quot;, &quot;space&quot;: {&quot;key&quot;: &quot;spaceKey&quot;}, &quot;status&quot;: &quot;current&quot;, &quot;body&quot;:{&quot;storage&quot;:{&quot;value&quot;:&quot;&lt;p&gt;This is a new page&lt;/p&gt;&quot;, &quot;representation&quot;:&quot;storage&quot; }}}&#39;</pre><p>The confluence REST API documentation is here<br><a href="https://developer.atlassian.com/cloud/confluence/rest/intro/">https://developer.atlassian.com/cloud/confluence/rest/intro</a></p><p>Now let’s go with Bitbucket<br>Creating a Private Repository</p><pre>curl -X POST \<br> --url &#39;https://api.bitbucket.org/2.0/repositories/{workspace}/{repo-name}&#39; \<br> --user &#39;bitbucket-username:app-password&#39; \<br> --header &quot;Content-Type: application/json&quot; \<br> --data &#39;{&quot;scm&quot;: &quot;git&quot;, &quot;project&quot;: {&quot;key&quot;: &quot;projectKey&quot;}, &quot;is_private&quot;: true }&#39;</pre><p>The Bitbucket API Documentation is here<br><a href="https://developer.atlassian.com/bitbucket/api/2/reference/">https://developer.atlassian.com/bitbucket/api/2/reference</a></p><p>I hope you find this article gets the motivation to start with API in your instance. Please share your thoughts in the comments.</p><p>Thanks,<br>Pramodh</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d248ecce42d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>