<?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 Akash Chevli on Medium]]></title>
        <description><![CDATA[Stories by Akash Chevli on Medium]]></description>
        <link>https://medium.com/@akashchevli888?source=rss-66b1638b797------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*m39Jr28j4Zk6Su7i.jpg</url>
            <title>Stories by Akash Chevli on Medium</title>
            <link>https://medium.com/@akashchevli888?source=rss-66b1638b797------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:39:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akashchevli888/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[Spark Shuffle Internals: How Data Moves Across the Cluster]]></title>
            <link>https://medium.com/@akashchevli888/spark-shuffle-internals-how-data-moves-across-the-cluster-92f69a06b863?source=rss-66b1638b797------2</link>
            <guid isPermaLink="false">https://medium.com/p/92f69a06b863</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[spark-internals]]></category>
            <dc:creator><![CDATA[Akash Chevli]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 15:59:20 GMT</pubDate>
            <atom:updated>2026-07-05T15:59:20.595Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Prerequisites</strong></blockquote><blockquote>This article assumes you’re already familiar with basic Spark concepts such as DataFrames, transformations, actions, and partitions. You don’t need to know Spark internals , we’ll build those concepts from scratch throughout the article.</blockquote><p>If you’ve spent any time working with Spark, you’ve probably come across statements like:</p><ul><li>Shuffle is expensive.</li><li>groupBy() triggers a shuffle.</li><li>Joins often involve a shuffle.</li><li>Watch out for Exchange nodes in the Spark UI.</li></ul><p>These statements are all true to some extent, but they rarely explain <strong>why</strong>.</p><p>What exactly is a shuffle?</p><p>Why does Spark stop one stage and start another?</p><p>Where does the data actually go?</p><p>Why are .data and .index files created?</p><p>And how do reducers know which bytes to fetch from machines spread across the cluster?</p><p>In this article, we’ll answer those questions by following a shuffle from start to finish. We’ll begin with the fundamental reason a shuffle exists, trace how Spark writes and reads shuffle files, explore the partitioning strategies behind different operations, and finally see how Spark reduces network traffic using local aggregation before data is exchanged across the cluster.</p><h3>1. Why Shuffle Exists</h3><p>Before we dive into Spark’s internals, let’s first understand what a <strong>shuffle </strong>means in simple terms.</p><p>Outside the world of big data, <em>shuffling</em> simply means mixing things up, for example, shuffling a deck of cards to rearrange their order.</p><p>The core goal of a shuffle is straightforward:</p><blockquote><strong>Take records that are scattered across different physical machines and bring matching keys together into the same partition.</strong></blockquote><p>Once matching keys are grouped together, Spark can safely perform operations like groupBy, join, distinct, and orderBy.</p><h4>1.1 Partitions Are Completely Independent</h4><p>Before looking at how data moves, we have to ask a foundational question:</p><blockquote>Why can’t Spark tasks just talk to one another and share data while processing?</blockquote><p>When Spark processes a DataFrame, it divides the massive dataset into smaller, manageable pieces called partitions, and launches exactly one task to process each piece.</p><p>To maximize speed, these tasks execute with total independence. A task processing <strong>Partition 0</strong> has no knowledge of, or access to, the data inside <strong>Partition 1</strong>. There is zero communication between them while they work.</p><p>This isolation is the exact reasons Spark scales so well, but it also creates an interesting challenge.</p><h4>1.2 The Problem: Skipping the Shuffle Leads to Incorrect Results</h4><p>Let’s see what happens when we try to bypass this design. Suppose we want to count how many times each fruit appears in our dataset using a group-by operation.</p><p>If Spark skipped the shuffle phase entirely and blindly ordered each partition to calculate its fruit counts inside its own isolated space, the tasks could only count the records they could physically see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kOPw3fAXExWFJEFA4brdCA.png" /><figcaption>Figure 1: Why Shuffle Exists Fruit Example</figcaption></figure><p>As shown in the <strong>Input Data (Box 1)</strong> and <strong>Without Shuffle (Box 2)</strong> sections of our diagram, the key Apple is split across multiple partitions. Partition 0 counts 2 Apples, while Partition 1 counts 1 Apple.</p><p>If Spark stopped execution here, your final output would contain two separate, conflicting rows for Apple instead of a single consolidated total. The counting math itself isn’t broken; the problem is that the identical keys are completely trapped inside separate, isolated partitions.</p><h4>1.3 Shuffle Exists for Correctness</h4><p>To produce a mathematically accurate answer, Spark must intentionally break this partition isolation. This is where the shuffle comes to the rescue.</p><p>As shown in <strong>With Shuffle (Box 3)</strong>, Spark opens up network channels and redistributes the data across the cluster. It routes every single Apple record to a single destination partition, every Banana to another, and every Orange to its own.</p><p>Once all identical keys are sitting in the same place, the final aggregation task can execute safely <strong>(Box 4)</strong>. The task responsible for the Apple partition can now see every single Apple record in the entire dataset and correctly output Apple = 3.</p><p>This reveals the ultimate purpose of a shuffle:</p><blockquote><strong>A shuffle isn’t just a random data movement — it is a mandatory, structural rearrangement required to guarantee absolute correctness in global results.</strong></blockquote><blockquote>Note: This example intentionally simplifies the physical process to build strong mental intuition. In a real cluster, Spark avoids sending millions of raw rows over the network by running a partial aggregation locally on the map side first (sending a single summary record like (Apple, 2) instead of two individual Apple rows). We will trace this exact optimization using real Spark UI plans in the next sections.</blockquote><h3>2. How Spark Performs a Shuffle</h3><p>Now that we understand <strong>why</strong> Spark needs a shuffle, the next question is:</p><blockquote>What actually happens inside Spark once a shuffle is triggered?</blockquote><p>At a high level, every shuffle goes through two phases:</p><ol><li><strong>Shuffle Write (Map Side):</strong> Upstream tasks organize their output and write it to the local disk.</li><li><strong>Shuffle Read (Reduce Side):</strong> Downstream tasks fetch only the data they need from those shuffle files over the network.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eYb_AFvh0kFF3paFTg8kUA.png" /><figcaption>Figure 2: Basic shuffle read and shuffle write</figcaption></figure><p>We’ll follow this entire journey step by step. But before we do, let’s quickly introduce a few Spark concepts that will appear throughout the rest of this article.</p><ul><li><strong>Worker Node:</strong> A physical (or virtual) machine in the Spark cluster that provides CPU and memory resources.</li><li><strong>Executor:</strong> A dedicated JVM process running on a Worker Node. It performs the actual data processing and executes tasks.</li><li><strong>Partition:</strong> A chunk of your dataset. Spark splits large datasets into multiple partitions so they can be processed in parallel.</li><li><strong>Task:</strong> A unit of work scheduled by Spark to process exactly one partition.</li></ul><p>The most important distinction to remember is this:</p><blockquote><strong><em>A partition is data. A task is the work performed on that data.</em></strong></blockquote><p>Spark creates <strong>exactly one task for every partition</strong>. While they are closely related, they are not the same thing. A partition never executes anything on its own; a task does.</p><h4>2.1 Cores, Executors, and Parallelism</h4><p>Before we look at the data moving, we have to ask:</p><blockquote>How do tasks actually execute inside these executors concurrently?</blockquote><p>A task typically occupies one CPU core while it is running.</p><p>For example, imagine a Worker Node. Spark’s cluster manager might allocate an executor with <strong>2 CPU cores</strong> and a portion of memory. Since each task requires one CPU core, the executor can execute <strong>up to two tasks simultaneously</strong>.</p><p>The important takeaway is much simpler:</p><blockquote>Your data is spread across multiple partitions, and those partitions are often distributed across different executors running on different worker nodes.</blockquote><p>This distribution is what allows Spark to process massive datasets in parallel. However, it also creates a challenge. Suppose one partition contains two Apple records while another partition contains three more. If we want the final result to be Apple = 5, Spark somehow needs to bring those records together.</p><p>That is exactly why a shuffle exists.</p><p>Throughout the rest of this section, we’ll use the cluster layout shown below. It contains two Worker Nodes, each running two Executors. Every Executor has two CPU cores, allowing it to process two tasks concurrently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_Sm5NLUimbE-YJNXMaN4A.png" /><figcaption>Figure 3: Initial cluster layout</figcaption></figure><h4>2.2 Shuffle Write (Map Side)</h4><p>Let’s now follow what happens when Spark reaches a shuffle operation.</p><p>The first phase is called <strong>Shuffle Write</strong>, and it runs entirely on the <strong>map side</strong> (the upstream stage).</p><p>To see how this works in practice, let’s look at what happens under the hood when we want to calculate the <em>total count of each fruit</em> in our dataset. We will trace exactly how Spark handles this data flow, manages the processing steps across the cluster, and returns the final correct results.</p><h4>Step 1: Assigning Rows to Destination Blocks</h4><p>Imagine a task processing <strong>Partition 0 </strong>(See Figure 3). As it scans each row, it has to answer one simple question:</p><blockquote>Why do we need to assign a destination block to this row right now?</blockquote><p>We do this because downstream tasks need a predictable way to collect matching keys. Since our goal is to find the total count of each fruit, we rely on a group-by operation. Under the hood, Spark handles group-by operations using a strategy called <strong>hash partitioning</strong>. For every row, it computes:</p><pre>hash(key) % num_shuffle_partitions</pre><p>By default, Spark sets spark.sql.shuffle.partitions = 200. This means Spark normally divides the shuffled data into 200 destination partitions. To keep our diagrams simple and easy to follow, we&#39;ll configure Spark to use <strong>8 shuffle partitions</strong> for this example.</p><p>So our formula becomes:</p><pre>hash(key) % 8</pre><p>Every row now receives a destination shuffle block numbered from <strong>0 to 7</strong>.</p><p>For our fruit dataset, we’ll assume the hash function produces the following mapping:</p><pre>| Fruit Name | Shuffle Block |<br>|------------|---------------|<br>| Apple      | 0             |<br>| Peach      | 0             |<br>| Orange     | 1             |<br>| Grape      | 1             |<br>| Melon      | 3             |<br>| Banana     | 5             |<br>| Plum       | 5             |<br>| Lemon      | 6             |<br>| Mango      | 7             |<br></pre><p>Notice an important property of hash partitioning: <strong>Every occurrence of the same key always hashes to the same shuffle block.</strong></p><p>No matter which input partition an Apple record originally came from, it will always be assigned to <strong>Shuffle Block 0</strong>. Likewise, every Orange record always goes to <strong>Shuffle Block 1</strong>, every Banana to <strong>Shuffle Block 5</strong>, and so on.</p><p>This guarantee is what makes a shuffle possible. It ensures that identical keys from completely different partitions eventually meet in the same downstream partition.</p><h4>Step 2: Buffering and Spilling</h4><p>Once the rows are assigned to a block, we have to ask:</p><blockquote>Should Spark immediately send every row across the network or write it straight to disk?</blockquote><p>The answer is <strong>no</strong>.</p><p>Imagine processing a dataset with 10 million rows. If every task sent each row over the network the moment it was processed, Spark would generate millions of tiny network requests. Likewise, writing every processed row directly to disk would create millions of small disk writes. Both approaches would be extremely inefficient.</p><p>Instead, Spark first organizes the data locally.</p><p>As the map task processes each row and determines its destination shuffle block, it appends that row to an <strong>in-memory shuffle buffer</strong>. Inside this buffer, Spark groups the rows by their destination shuffle blocks, preparing them for the next stage of the shuffle.</p><p>Spark continuously monitors how much memory this buffer is consuming. Once it reaches a certain threshold, Spark <strong>spills</strong> the buffered data to a temporary file on the executor’s local disk. If the dataset is large enough, the same task may spill multiple times during execution.</p><h4>Step 3: Writing One Shuffle File Per Input Partition</h4><p>After the task finishes processing, the next question is:</p><blockquote>How does Spark consolidate these temporary files on disk for the reducers?</blockquote><p>A common misconception is that Spark creates one file for every shuffle block. It doesn’t. Instead, <strong>every input partition produces exactly one shuffle data file and one index file.</strong></p><p>For example, suppose an executor processes <strong>Partition 0</strong>. Once that task finishes, Spark creates, shuffle_p0.data , shuffle_p0.index .</p><p>So the number of shuffle files depends on the <strong>number of input partitions</strong>, not the number of shuffle blocks. If there are 8 input partitions, Spark eventually creates 8 data files and 8 index files (<em>P0</em> through P7).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qAS7zrJzzaFrzZIMJtjmxA.png" /><figcaption>Figure 4: Shuffle Write — Each Map Task Writes One File</figcaption></figure><h4>What Does the <strong>.data</strong> File Contain?</h4><p>Although Spark creates only <strong>one </strong>.data<strong> file per input partition</strong>, that file contains data for <strong>every destination shuffle block</strong>.</p><p>Conceptually, shuffle_p0.data looks like this:</p><pre>+----------------------------------------------------------------------------+<br>| Shuffle Block 0 | Shuffle Block 1 | Shuffle Block 2 | .. | Shuffle Block 7 |<br>+----------------------------------------------------------------------------+</pre><p>Each block stores the rows that hash to that particular destination.</p><p>For example (as per figure 4), Partition 0 originally contained: Apple, Banana, and Orange, after applying the hash function, the rows are grouped inside the shuffle file by their destination block, like this:</p><pre>Shuffle Block 0<br>---------------<br>Apple<br><br>Shuffle Block 5<br>---------------<br>Banana<br><br>Shuffle Block 1<br>---------------<br>Orange</pre><p>Notice something important: The rows are no longer stored in their original input order. Instead, they are grouped by <strong>destination shuffle block</strong>, because downstream tasks will later fetch one block at a time.</p><h4>But How Will Reducers Find Their Block?</h4><p>At this point, another question naturally comes up.</p><blockquote>Why do we need a separate .index file alongside our data file?</blockquote><p>Suppose <strong>Reducer Task 0</strong> is responsible for <strong>Shuffle Block 0</strong>. How does it know where Block 0 begins inside shuffle_p0.data?</p><p>One option would be to scan the entire file from beginning to end every time, but clearly, that would be wasteful.</p><p>Instead, Spark creates a second file alongside every .data file which is .index file (e.g.,shuffle_p0.index)</p><p>Think of the index file as the <strong>table of contents</strong> for the shuffle data file. It doesn’t store any actual rows. Instead, it stores the <strong>byte offsets</strong> that tell Spark exactly where each shuffle block begins inside the corresponding .data file.</p><p>Conceptually, it looks like this:</p><pre>| Shuffle Block | Starts At |<br>|---------------|-----------|<br>| Block 0       | Byte 0    |<br>| Block 1       | Byte 520  |<br>| Block 2       | Byte 910  |<br>| Block 3       | Byte 1240 |<br>| ...           | ...       | </pre><p>Suppose Block 0 occupies the first <strong>520 bytes</strong> of the data file.</p><p>Naturally, Block 1 begins immediately after it at <strong>Byte 520</strong>.</p><p>Likewise, if Block 1 occupies an additional 390 bytes, Block 2 starts at <strong>Byte 910</strong>.</p><p>This allows Spark to jump directly to the required portion of the data file rather than scanning the entire file.</p><p>For example, if a reducer needs <strong>Block 1</strong>, it simply reads the index and knows that <em>Block 1 starts at Byte 520</em> and <em>Block 2 starts at Byte 910</em>. From this, Spark immediately knows that Block 1 occupies the byte range 520 -&gt; 909. Only those bytes need to be read from the .data file.</p><p>This small .index file is the reason Spark can efficiently retrieve individual shuffle blocks without repeatedly scanning large shuffle files.</p><h4>2.3 Shuffle Read (Reduce Side)</h4><p>During the <strong>Shuffle Write</strong> phase, every map task organized its output and stored the resulting .data and .index files on the local disks of the executors. Once every upstream map task has finished writing, the first stage officially comes to an end.</p><p>At this point, an interesting thing happens: <strong>None of the shuffled data has actually moved across the network yet.</strong> Every shuffle file is still sitting on the local disk of the executor that produced it.</p><p>This naturally raises an important question:</p><blockquote>If all the data is still sitting on local disks, how do downstream tasks know where to find it?</blockquote><p>The answer lies in Spark’s <strong>pull-based shuffle architecture</strong>.</p><p>Unlike many distributed systems where producers actively send data to consumers, Spark does the opposite. The map tasks never push shuffle data across the network. Instead, once every map task has completed, Spark launches a new set of downstream tasks (often called <strong>reduce tasks</strong>) to pull the data.</p><p>Recall that we configured Spark to use <strong>8 shuffle partitions</strong>. As a result, Spark launches <strong>8 reducer tasks</strong>, with each reducer responsible for processing one shuffle partition. To see how this works, we’ll follow <strong>Reducer Task 0</strong>, which is responsible for collecting <strong>Shuffle Block 0</strong> from every single map output across the cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i4Yp-ECvEv5xWwDh-KW8Dw.png" /><figcaption>Figure 5: Shuffle Read Final Result</figcaption></figure><h4>Step 1: Asking the Driver for Map Statuses</h4><p>Before the reducer can pull any data, we have to ask:</p><blockquote>How does Reducer Task 0 discover which executors hold the data files it needs?</blockquote><p>The reducer doesn’t immediately start guessing or scanning network locations. Instead, it first contacts the Driver.</p><p>Throughout the Write stage, every completed map task reports the exact location of its shuffle output back to the Driver. Spark stores this metadata as <strong>Map Statuses</strong>. A Map Status tells the reducer exactly which executor produced the shuffle file, the network location of that executor, and the file names associated with that map task.</p><p>Conceptually, the Driver provides a directory map to the reducer like this:</p><pre>| Input Partition | Shuffle Output Location                                            |<br>|---------------- |--------------------------------------------------------------------|<br>| P0              | **Executor 1 (Worker 1)** -&gt; `shuffle_p0.data`, `shuffle_p0.index` |<br>| P1              | **Executor 1 (Worker 1)** -&gt; `shuffle_p1.data`, `shuffle_p1.index` |<br>| P2              | **Executor 2 (Worker 1)** -&gt; `shuffle_p2.data`, `shuffle_p2.index` |<br>| ...             | ...                                                                |  <br>| P7              | **Executor 2 (Worker 2)** -&gt; `shuffle_p7.data`, `shuffle_p7.index` |</pre><p>Notice what the reducer has learned. It now knows <strong>where every shuffle output is located</strong>, but it still doesn’t know where <strong>Block 0</strong> lives inside each .data file.</p><h4>Step 2: Reading the .index Files</h4><p>Now that the reducer knows which executors to talk to, the next question is:</p><blockquote>How does the reducer pinpoint the exact byte locations of its block without reading the whole file?</blockquote><p>To do this, the reducer contacts each remote executor and reads only the corresponding .index file. It does not read the heavy .data files yet.</p><p>Suppose the reducer looks at shuffle_p0.index:</p><pre>| Shuffle Block | Starts At |<br>|---------------|-----------|<br>| Block 0       | Byte 0    |<br>| Block 1       | Byte 520  |<br>| ...           | ...       |</pre><p>From this information, Spark immediately knows that Block 0 inside shuffle_p0.data occupies the exact byte range from Byte 0 to Byte 519</p><p>The same lookup is performed for every shuffle output (shuffle_p0.index through shuffle_p7.index).</p><p>Notice something important. Spark never scans an entire shuffle file looking for Block 0; Instead, it performs a direct lookup using the byte offsets stored inside the .index file.</p><h4>Step 3: Fetching Only the Required Bytes</h4><p>Now that the exact byte locations are known, we ask:</p><blockquote>How does Spark handle the actual network transfer efficiently, especially if some partitions don’t have data for this block?</blockquote><p>Once the reducer knows the exact byte boundaries, it initiates a network request to fetch only those specific bytes from each executor’s .data file.</p><p>The process looks like this:</p><ul><li>Read Block 0 byte range from shuffle_p0.data over the network</li><li>Read Block 0 byte range from shuffle_p1.data over the network</li><li>…</li><li>Read Block 0 byte range from shuffle_p7.data over the network</li></ul><p>But what happens if an input partition had no records that belonged to Block 0? Look at <strong>Partition 1 (</strong><em>P1</em><strong>)</strong> in our layout (Figure 4). It contains only <em>Mango</em> and <em>Grape</em>, which hash to Blocks 7 and 1.</p><p>When the reducer checks shuffle_p1.index, it will see:</p><ul><li>Block 0 -&gt; Starts at Byte 0</li><li>Block 1 -&gt; Starts at Byte 0</li></ul><p>Since both offsets are identical, Spark immediately knows that <strong>Block 0 occupies zero bytes</strong> inside that shuffle file. Instead of making an unnecessary network call or reading the disk anyway, Spark simply skips it and moves on to the next shuffle output. This saves immense amounts of disk and network I/O.</p><h4>Step 4: Building the Reducer’s Input</h4><p>Finally, after communicating with all executors, we ask:</p><blockquote>What does the final consolidated input look like for our reducer task?</blockquote><p>After repeating this process for every shuffle output, Reducer Task 0 has successfully gathered every Block 0 chunk produced across the entire cluster. It brings them together into its own local memory buffer to construct its final input partition.</p><p>If we look at our Shuffle Read diagram (Figure 5), we can see exactly what Reducer Task 0 has pulled into its partition:</p><pre>| REDUCER TASK 0 (P0)       |<br>|---------------------------|<br>| Apple  (Fetched from P0)  |<br>| Apple  (Fetched from P4)  |<br>| Apple  (Fetched from P7)  |<br>| Peach  (Fetched from P3)  |<br>| Peach  (Fetched from P5)  |</pre><p>Look at what we have achieved! Every single <em>Apple</em> and <em>Peach</em> record that was originally scattered across completely separate physical machines and separate input partitions has traveled across the network to group together inside <strong>Partition 0 (</strong><em>P0</em><strong>) on Executor 1.</strong></p><p>Meanwhile, Reducer Task 1 is doing the exact same thing for <em>Orange</em> and <em>Grape</em>, Reducer Task 5 is doing it for <em>Banana</em> and <em>Plum</em>, and so on.</p><p>Now that all matching keys live in the exact same place, the downstream reduce tasks can finally run aggregation logic safely and compute the final results. The shuffle is complete!</p><h4>Why Are Some Reducer Partitions Empty?</h4><p>If you look closely at the <strong>Shuffle Read diagram (Figure 5)</strong>, you will notice something interesting: <strong>Partition 2 (</strong><em>P2</em><strong>) and Partition 4 (</strong><em>P4</em><strong>) are completely empty and doing absolutely nothing.</strong></p><p>Why does this happen?</p><p>This goes back to our hash partitioning formula:</p><pre>hash(key) / 8</pre><p>In our example dataset, out of all the fruits processed across the cluster (Apple, Banana, Orange, etc.), the hash function simply never output a 2 or a 4 for any of the keys. Because no rows were assigned to Shuffle Block 2 or Shuffle Block 4 during the map phase, Reducer Task 2 and Reducer Task 4 have zero bytes to fetch. They sit idle.</p><h4>How Spark Smartly Handles This via AQE (Adaptive Query Execution)</h4><p>To prevent wasting cluster resources on these empty blocks, Spark includes a feature called <strong>Adaptive Query Execution (AQE)</strong>.</p><p>With AQE, Spark doesn’t just blindly stick to a rigid runtime plan. Instead, it behaves like a smart coordinator. At the exact moment the Shuffle Write phase finishes (after each stage completion), Spark looks at the <strong>Map Statuses</strong> and inspects the actual sizes of the generated shuffle blocks.</p><p>If it notices that certain shuffle blocks are empty (like Block 2 and Block 4 in our example, see Figure 5), or if it sees a bunch of tiny shuffle blocks that don’t justify having their own dedicated tasks, AQE automatically <strong>coalesces (combines) them on the fly</strong>.</p><p>Instead of launching empty, useless tasks, Spark dynamically shrinks and adjusts the downstream reducer partitions before launching them. This ensures that Spark spins up tasks only for partitions that have work to do.</p><p>This optimization keeps the cluster highly efficient, prevents CPU cycles from being wasted on scheduling ghost tasks, and spares us from constantly stressing over manual partition tuning!</p><h4>2.4 Shuffle Creates a Stage Boundary</h4><p>Before we look at how a shuffle splits a Spark job into pieces, let’s step back and look at the big picture of what we just built.</p><p>When we connect the entire process, we see map tasks writing their files on one side, and reducer tasks pulling those blocks across the network on the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C_2PqrDcm24naFRo2Iz87Q.png" /><figcaption>Figure 6: Shuffle Data Write and Shuffle Reader Process</figcaption></figure><p>As shown in the diagram above, the Shuffle Data Writer and the Shuffle Data Reader form a complete pipeline. Each input partition runs a write task to generate a local disk file, and then the downstream read tasks independently fetch their specific data slices from those files.</p><h4>Why Does a Shuffle Break a Job in Two?</h4><p>This end-to-end connection brings us to one of the most useful concepts for tuning Spark jobs: <strong>Stages.</strong></p><p>Spark is known for lazy evaluation and pipelining. If you are executing simple transformations — like filtering out null values or converting text to lowercase, Spark doesn’t process rows one by one or save intermediate results to disk. Instead, it streams the data through memory in one continuous, efficient chain. That unbroken chain of operations is what Spark calls a <strong>Stage</strong>.</p><p>But the exact moment your code hits a shuffle operation (like a groupBy, join, or distinct), that smooth in-memory chain has to stop.</p><p>Why must the chain stop?</p><blockquote><strong><em>A reducer task cannot start reading until every single upstream map task has finished writing.</em></strong></blockquote><p>Let’s look at the intuition behind this rule using our fruit example. Suppose <strong>Reducer Task 0</strong> starts pulling Apple records while <strong>Map Task 7</strong> is still lagging behind and hasn&#39;t finished writing its file yet. Reducer Task 0 would end up with an incomplete dataset, completely missing whatever Apple records were still sitting inside Partition 7.</p><p>To avoid missing records and incorrect calculations, Spark must pause all forward progress. It ensures that downstream tasks cannot start fetching data until every single upstream task has completely finished writing its files.</p><h4>The Architecture of a Stage Boundary</h4><p>Because of this physical dependency, Spark splits your application’s execution into two completely separate blocks of time:</p><ol><li><strong>Stage 1 (the map stage):</strong> all tasks run in parallel, processing the input partitions and writing their .data and .index files to local disk.</li><li><strong>The Stage Boundary:</strong> Spark pauses the execution pipeline and waits. It will not allow the job to move forward until the very last task in Stage 1 completes. Once done, the Driver collects the final file locations from every executor (the Map Statuses).</li><li><strong>Stage 2 (The Reduce Stage):</strong> Only when Stage 1 is 100% complete does the Driver finally launch the downstream reducer tasks. These new tasks read the Map Statuses, pull their assigned shuffle blocks over the network, and finish the computation.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBdOIc9B6m5AqLnzTCPxsw.png" /><figcaption>Figure 7: Stage 1 and Stage 2 split with shuffle files in the middle</figcaption></figure><p>As you can see in the layout diagram, Stage 1 handles data generation on the left, the shuffle files act as a hard checkpoint in the middle, and Stage 2 handles pulling the data on the right.</p><p>This strict separation is what they say a shuffle creates a <strong>Stage Boundary</strong>. Understanding this boundary is the secret to debugging Spark performance, because any bottleneck or slow task in Stage 1 completely blocks Stage 2 from starting!</p><h3>3. Partitioning Strategies Behind Shuffle</h3><p>We discussed the entire lifecycle of a shuffle — from map tasks writing shuffle files to reducer tasks fetching them over the network.</p><p>But throughout that discussion, we quietly assumed Spark already knew <strong>where every row should go</strong>.</p><p>That naturally leads to another question:</p><blockquote>How does Spark decide the destination partition for each row?</blockquote><p>The answer lies in Spark’s <strong>partitioning strategies</strong>.</p><p>Whenever a shuffle is triggered, Spark doesn’t distribute records across the cluster randomly. Instead, it applies a partitioning strategy that determines the destination partition for every row. The strategy Spark chooses depends on the type of operation being performed.</p><p>The three most common partitioning strategies are:</p><ol><li><strong>Hash Partitioning</strong> — Used for key-based operations like groupBy(), join(), and distinct().</li><li><strong>Range Partitioning</strong> — Used for operations that require globally sorted data, such as orderBy() and sort().</li><li><strong>Round-Robin Partitioning</strong> — Used to distribute rows as evenly as possible across partitions without considering the row values.</li></ol><p>Let’s start with the partitioning strategy you’ll encounter most often: <strong>Hash Partitioning</strong>.</p><h4>3.1 Hash Partitioning</h4><p>Imagine we want to count the number of flights departing from each airport.</p><pre>flight_df.groupBy(&quot;origin_airport&quot;).count()</pre><p>At first glance, this looks like a straightforward aggregation.</p><p>Behind the scenes, however, Spark has to solve a much bigger problem.</p><p>The flight records are distributed across multiple input partitions, and those partitions may be running on completely different executors. Before Spark can calculate the final count for each airport, it has to make sure that <strong>every record with the same airport code ends up in the same downstream partition.</strong> (You can picture architecture structure like figure 4 in your head)</p><p>That is exactly what <strong>Hash Partitioning</strong> is designed to do.</p><h4>Why Can’t Spark Distribute Rows Randomly?</h4><p>Suppose Spark ignored the grouping key and simply distributed rows randomly during the shuffle.</p><p>A few BOM records might end up in one partition, while the remaining BOM records are sent somewhere else.</p><pre>Partition 0<br>------------<br>BOM<br>BOM<br>DEL<br><br>Partition 1<br>------------<br>BOM<br>BLR<br>HYD</pre><p>When the downstream tasks later perform the aggregation, neither task has the complete picture.</p><p>One task only sees two BOM records. The other only sees one.</p><p>Neither task can produce the correct global count because the matching keys have been split across different partitions.</p><p>For operations like groupBy(), join(), and distinct(), Spark therefore needs a deterministic way to ensure that <strong>every identical key always reaches the same destination partition.</strong></p><h4>How Spark Chooses the Destination Partition</h4><p>Spark solves this using a <strong>hash function, </strong>as we discussed already in the blog.</p><p>For every row, it computes the destination partition using the following formula:</p><pre>partition_id = abs(hash(key)) % num_partitions</pre><p>Although the formula looks mathematical, the underlying idea is quite simple.</p><p>First, Spark converts the grouping key into a numeric hash value.</p><p>It then applies the modulo (%) operator to map that number into one of the available shuffle partitions.</p><p>For example, if the shuffle is configured with <strong>8 partitions</strong>, the possible destination partition IDs are:</p><pre>0, 1, 2, 3, 4, 5, 6, 7</pre><p>Every row is assigned to exactly one of these partitions.</p><p>The most important property of this calculation is that it is <strong>deterministic</strong>. As long as the input key and the number of shuffle partitions remain the same, Spark will always produce the same partition ID. That means every flight with origin_airport = &quot;BOM&quot; will always be routed to the same destination partition. Likewise, every DEL record will always be routed to another consistent partition.</p><p>It doesn’t matter whether those rows originally came from Partition 0, Partition 7, or even different executors. Every task performs the exact same calculation, guaranteeing that matching keys eventually meet in the same downstream partition.</p><p>This deterministic behavior is what makes distributed aggregations possible.</p><h4>Following the Execution in Spark UI</h4><p>Now that we understand the algorithm, let’s see how Spark actually executes this query.</p><p>We’ll follow the physical execution plan step by step and connect each operator back to the concepts we’ve learned.</p><p>Along the way, you’ll see:</p><ul><li>How Spark reduces the amount of data before the shuffle,</li><li>Where Hash Partitioning is actually applied,</li><li>How the shuffle is optimized at runtime using Adaptive Query Execution (AQE), and</li><li>Finally, how Spark combines all matching keys to produce the final result.</li></ul><h4>Step 1: Reducing the Data Before Hash Partitioning</h4><p>Let’s begin by looking at the first part of the physical execution plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*dmSzTiRMGrcRZJepOaybgg.png" /><figcaption>Figure 8: HashAggregate Before Exchange</figcaption></figure><p>Spark starts by scanning the input CSV file, which in our example contains approximately <strong>10 million flight records</strong> (around <strong>2 GB</strong> of data).</p><p>If Spark immediately shuffled all 10 million rows across the network, the shuffle would be unnecessarily expensive.</p><p>Instead, Spark first performs a <strong>local aggregation</strong> within each input partition.</p><p>This optimization is represented by the first <strong>HashAggregate</strong> operator inside the WholeStageCodegen (1) container.</p><p>Rather than forwarding every individual flight record, Spark groups identical airport codes <strong>within each partition</strong> and computes <strong>partial counts</strong> locally.</p><p>For example, suppose one input partition contains the following rows:</p><pre>BOM<br>DEL<br>BOM<br>HYD<br>DEL<br>BOM</pre><p>Instead of sending all six rows into the shuffle, Spark converts them into a much smaller summary:</p><pre>(BOM, 3)<br>(DEL, 2)<br>(HYD, 1)</pre><p>The same optimization happens independently on every input partition.</p><p>As a result, the amount of data that needs to be shuffled drops dramatically.</p><p>In our execution plan, Spark reduces:</p><pre>Input Rows<br>----------<br>10,000,000</pre><p>down to just</p><pre>Rows After Local Aggregation<br>----------------------------<br>28,080</pre><p>before the shuffle even begins.</p><p>Reducing the dataset at this stage significantly lowers both the network traffic and the amount of shuffle data written to disk.</p><blockquote><strong>Note:</strong> This optimization is known as <strong>Map-Side Aggregation</strong> (or <strong>Local Aggregation</strong>). We’ll explore how it works internally later in this article.</blockquote><h4>Step 2: Applying Hash Partitioning During the Shuffle</h4><p>Once the local aggregation finishes, Spark reaches the shuffle boundary.</p><p>This is represented by the <strong>Exchange</strong> operator in the physical plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*K_uO9K-_eELadImP9fOvAg.png" /><figcaption>Figure 9: Exchange Operator (Shuffle)</figcaption></figure><p>This is the point where <strong>Hash Partitioning</strong> is actually applied.</p><p>For every partially aggregated record, Spark computes:</p><pre>partition_id = abs(hash(origin_airport)) % num_partitions</pre><p>Since Spark uses <strong>200 shuffle partitions</strong> by default, the calculation becomes:</p><pre>abs(hash(origin_airport)) % 200</pre><p>Every airport code is now assigned to one of the <strong>200 destination shuffle partitions</strong>.</p><p>For example, every occurrence of origin_airport = BOM produces exactly the same partition ID.</p><p>Likewise, every DEL, BLR, or HYD record is consistently mapped to its own destination partition.</p><p>This deterministic mapping guarantees that matching keys from completely different executors eventually meet in the same downstream partition.</p><p>The Exchange operator also reports an interesting statistic:</p><pre>Shuffle Records Written: 28,080</pre><p>Notice how this number exactly matches the output of the previous <strong>HashAggregate</strong> operator.</p><p>Spark isn’t redistributing the original <strong>10 million flight records</strong> anymore. Instead, it is redistributing only the <strong>28,080 partially aggregated records</strong> produced during the local aggregation.</p><p>This is one of the biggest reasons Spark can execute large aggregations efficiently. By reducing the dataset before applying hash partitioning, it dramatically decreases the amount of data that needs to cross the network.</p><p>Finally, the shuffle write tasks organize these records into their destination shuffle partitions and write them to the executor’s local shuffle files, ready for the next stage to consume.</p><h4>Step 3: Adaptive Query Execution (AQE) Optimizes the Shuffle</h4><p>At this point, Stage 1 has finished.</p><p>Every shuffle write task has completed, the shuffle files have been written to local disk, and the Driver now knows where every shuffle partition is located.</p><p>Only now can Spark see something it couldn’t know earlier:</p><blockquote>How much data actually ended up inside each shuffle partition?</blockquote><p>This is where <strong>Adaptive Query Execution (AQE)</strong> comes into play.</p><p>Unlike the original physical plan, which is generated before execution begins, AQE allows Spark to <strong>re-optimize the query while it is running</strong>, using the statistics collected during the previous stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*6gbIHfnh8fUk8xQf4AOiEQ.png" /><figcaption>Figure 10: AQE Shuffle Read</figcaption></figure><p>In our example, the map-side aggregation reduced the original dataset from <strong>10 million rows</strong> down to just <strong>28,080 partial records</strong>.</p><p>By the time those records are written to the shuffle files, the total shuffle size is only about 831.8 KB</p><p>Spark now asks a simple question:</p><blockquote>Does it still make sense to launch 200 reducer tasks for less than 1 MB of data?</blockquote><p>The answer is clearly <strong>no</strong>.</p><p>Launching hundreds of tasks introduces scheduling overhead, task startup costs, and unnecessary coordination between executors. Most of those tasks would end up processing only a handful of records before immediately finishing.</p><p>Instead, AQE decides to <strong>coalesce</strong> multiple small shuffle partitions into fewer, larger partitions.</p><p>In our execution plan, Spark goes one step further and merges all <strong>200 shuffle partitions</strong> into <strong>a single partition</strong>.</p><p>As a result, the AQE Shuffle Read operator reports Number of Partitions: 1</p><p>Notice something important here.</p><p>Spark is <strong>not recomputing the hash values</strong>, nor is it changing where individual records were written during the Shuffle Write phase. Those decisions have already been made.</p><p>AQE simply observes that many of the shuffle partitions are extremely small and combines them before launching the reduce stage. By adapting the execution plan to the actual runtime statistics instead of relying purely on estimates, Spark can significantly reduce scheduling overhead and execute the remaining stages more efficiently.</p><h4>Step 4: Bringing Matching Keys Together</h4><p>During the Shuffle Write phase, Spark ensured that every airport code was assigned to a deterministic destination partition.</p><p>Now, during the Shuffle Read phase, the downstream tasks fetch those partition blocks from every executor.</p><p>As a result, all records for BOM are finally brought together into the same partition. The same is true for every other airport code.</p><p>Only after this redistribution is complete can Spark perform the final aggregation.</p><h4>The Catch: Data Skew</h4><p>Hash partitioning works extremely well when the keys are distributed reasonably evenly across the dataset.</p><p>However, Spark makes its partitioning decision based <strong>only on the key</strong>. It has no knowledge of how frequently that key appears.</p><p>Imagine our flight dataset contains significantly more records for <strong>Mumbai Airport (</strong>BOM<strong>)</strong> than any other airport.</p><p>Because hash partitioning is deterministic, <strong>every </strong>BOM<strong> record will always be routed to the same shuffle partition</strong>. If BOM accounts for a large percentage of the dataset, that one partition can become much larger than the others.</p><p>As a result, most reducer tasks finish quickly, while the task responsible for processing the BOM partition continues running long after the others have completed.</p><p>This uneven distribution of work is known as <strong>Data Skew</strong>, and it is one of the most common performance challenges in shuffle-heavy Spark workloads.</p><h4>3.2 Range Partitioning</h4><p>In the previous section, we saw how <strong>Hash Partitioning</strong> guarantees that identical keys always end up in the same shuffle partition. That makes it an excellent choice for operations like groupBy(), join(), and distinct().</p><p>However, hash partitioning has one major limitation.</p><p>It completely ignores the <strong>natural ordering</strong> of the data.</p><p>Imagine we want to sort our flight dataset by departure time:</p><pre>flight_df.orderBy(&quot;departure_time&quot;)</pre><p>Hash partitioning simply computes a hash value for every key and applies a modulo operation.</p><pre>partition = hash(key) % numPartitions</pre><p>A hash value has no relationship to the actual value being sorted.</p><p>For example, a flight departing at 01:10 might be assigned to <strong>Partition 3</strong>, while another flight departing just two minutes later (01:12) might be assigned to <strong>Partition 0</strong>.</p><p>Although those timestamps are almost identical, they now live on completely different machines.</p><p>If Spark distributed the data this way, there would be no straightforward way to produce a globally sorted result.</p><p>To sort data across an entire cluster, Spark needs a different strategy.</p><p>Instead of scattering rows based on a hash value, it must ensure that <strong>smaller values are placed in earlier partitions and larger values in later partitions</strong>.</p><p>This is exactly what <strong>Range Partitioning</strong> does.</p><p>Suppose we want to sort our flight records into <strong>four final shuffle partitions</strong>.</p><p>Ideally, the data should be distributed like this:</p><ul><li><strong>Partition 0:</strong> 00:00 - 06:00</li><li><strong>Partition 1:</strong> 06:00 - 12:00</li><li><strong>Partition 2:</strong> 12:00 - 18:00</li><li><strong>Partition 3:</strong> 18:00 - 24:00</li></ul><p>Once the data is organized this way, Spark only needs to sort the rows <strong>within each partition</strong>.</p><p>Since the partitions themselves already represent ordered time ranges, reading them sequentially naturally produces a globally sorted dataset.</p><p>At first glance, this sounds simple.</p><p>But it immediately raises an important question.</p><blockquote>How does Spark know where those boundaries should be?</blockquote><p>It certainly cannot guess them beforehand.</p><p>If Spark simply divided the day into four equal six-hour windows, one partition might receive millions of morning flights while another receives only a handful of late-night flights.</p><p>The result would be an extremely unbalanced shuffle.</p><p>Instead, Spark first learns how the data is distributed and then chooses boundaries that produce <strong>roughly equal amounts of data</strong> in every partition.</p><p>This logic is implemented by Spark’s <strong>RangePartitioner</strong>, which works in three phases:</p><ol><li><strong>Sampling &amp; Boundary Determination</strong></li><li><strong>Shuffle Write (Routing Rows into Buckets)</strong></li><li><strong>Shuffle Read &amp; Final Local Sort</strong></li></ol><p>Let’s walk through each phase.</p><h4>Phase 1: Sampling &amp; Boundary Determination</h4><p>Before Spark can decide where each row should go, it first needs a rough understanding of how the data is distributed.</p><p>Notice that we said <strong>rough understanding</strong>, not a complete understanding.</p><p>Reading the entire dataset just to decide partition boundaries would require scanning billions of rows before the actual shuffle even begins, making the process unnecessarily expensive.</p><p>Instead, Spark performs a lightweight sampling phase.</p><p>It reads only a small fraction of the data, which is usually enough to estimate where good partition boundaries should be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d67rB8rtBZ_hEaRUlGn2Fg.png" /><figcaption>Figure 11: Phase 1: Sampling &amp; Boundary Determination</figcaption></figure><p>The process works as follows.</p><p><strong>Step 1 — Lightweight Sampling</strong></p><p>Each executor scans its local partition and collects a small random sample of the departure_time values.</p><p>For example, one executor might sample:</p><pre>01:10<br>09:20<br>15:30</pre><p>while another might sample:</p><pre>21:50<br>13:40<br>18:00<br>20:10</pre><p>Only these sampled values are collected.</p><p>The vast majority of the dataset is completely ignored during this phase.</p><p><strong>Step 2 — Send Samples to the Driver</strong></p><p>Each executor sends its sampled values back to the Driver.</p><p>The Driver gradually builds a combined sample representing the overall distribution of the dataset.</p><p>Conceptually, it might receive something like:</p><pre>01:10<br>09:20<br>13:40<br>15:30<br>18:00<br>20:10<br>21:50<br>...</pre><p>Although this is only a tiny fraction of the original dataset, it usually provides a good approximation of where the data is concentrated.</p><p><strong>Step 3 — Calculate the Range Boundaries</strong></p><p>Once all the samples have been collected, the Driver sorts them and calculates the partition boundaries.</p><p>The goal is <strong>not</strong> to create equal time windows.</p><p>The goal is to create partitions containing <strong>roughly the same number of rows</strong>.</p><p>For example, if the sampled data shows that most flights depart during the morning, Spark may choose boundaries like:</p><pre>05:30<br>11:10<br>17:45</pre><p>instead of simply dividing the day into four equal six-hour intervals.</p><p>This produces a much more balanced shuffle because each partition is expected to receive a similar amount of data.</p><p><strong>Step 4 — Broadcast the Boundaries</strong></p><p>Finally, the Driver broadcasts the computed boundary array to every executor.</p><p>For example:</p><pre>rangeBounds = [06:00, 12:00, 18:00]</pre><p>Every executor receives the exact same boundary array.</p><p>This is important because every executor must classify rows using <strong>identical rules</strong>.</p><p>If different executors used different boundaries, the same timestamp could end up in different partitions, breaking the global ordering guarantee.</p><p>At this point, Spark has everything it needs.</p><p>Every executor now knows exactly where the partition boundaries are.</p><p>The next step is deciding where each individual row belongs.</p><h4>Phase 2: Shuffle Write (Routing Rows into Buckets)</h4><p>Once the Driver has broadcast the boundary array to every executor, the actual <strong>Shuffle Write</strong> phase begins.</p><p>At this point, every executor has the exact same copy of the boundaries:</p><pre>rangeBounds = [06:00, 12:00, 18:00]</pre><p>Now each task starts scanning its input partition, one flight record at a time.</p><p>For every row, Spark looks at the departure_time and asks a simple question:</p><blockquote>Which range does this value belong to?</blockquote><p>Unlike hash partitioning, Spark isn’t computing a hash value here. Instead, it compares the value against the boundary array until it finds the correct range.</p><p>Conceptually, it works like this:</p><p>For a flight departing at <strong>01:10</strong>:</p><ul><li>Is 01:10 &lt; 06:00? -&gt; Yes.</li><li>Assign it to <strong>Bucket 0</strong>.</li></ul><p>For a flight departing at <strong>08:15</strong>:</p><ul><li>Is 08:15 &lt; 06:00? -&gt; No.</li><li>Is 08:15 &lt; 12:00? -&gt; Yes.</li><li>Assign it to <strong>Bucket 1</strong>.</li></ul><p>For a flight departing at <strong>14:20</strong>:</p><ul><li>Is 14:20 &lt; 06:00? -&gt; No.</li><li>Is 14:20 &lt; 12:00? -&gt; No.</li><li>Is 14:20 &lt; 18:00? -&gt; Yes.</li><li>Assign it to <strong>Bucket 2</strong>.</li></ul><p>For a flight departing at <strong>22:10</strong>:</p><ul><li>It is greater than every boundary.</li><li>Assign it to <strong>Bucket 3</strong>.</li></ul><p>Notice something interesting here.</p><p>Spark isn’t deciding the bucket using any complicated formula. The bucket is simply determined by <strong>where the value fits inside the ordered boundary array</strong>.</p><p>With three boundaries:</p><pre>rangeBounds = [06:00, 12:00, 18:00]</pre><p>Spark naturally ends up with four buckets:</p><ul><li>Bucket 0 -&gt; values before 06:00</li><li>Bucket 1 -&gt; values between 06:00 and 12:00</li><li>Bucket 2 -&gt; values between 12:00 and 18:00</li><li>Bucket 3 -&gt; values after 18:00</li></ul><p>This is exactly why <strong>N-1 boundaries create N partitions.</strong></p><p>For a small number of partitions, Spark simply walks through the boundary array from left to right until it finds the correct range.</p><p>When there are many partitions, Spark switches to a <strong>binary search</strong> internally to find the correct bucket more efficiently. The routing logic stays exactly the same — the implementation is simply faster.</p><p>Once the bucket has been determined, Spark places the row into the corresponding shuffle bucket in its in-memory shuffle buffer.</p><p>As the buffer fills up, Spark may spill it to temporary files on local disk. When the task finishes, those spill files are merged into the final .data and .index shuffle files, just like we saw earlier in the Shuffle Write section.</p><p>As the buffer fills up, Spark may spill it to temporary files on local disk. When the task finishes, those spill files are merged into the final .data and .index shuffle files, just like we saw earlier in the Shuffle Write section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7AY1UWKIscWXXJ66iwMTsg.png" /><figcaption>Figure 12: Phase 2: Routing Rows into Range Buckets</figcaption></figure><p>Notice what has <strong>not</strong> happened yet.</p><p>Rows have been grouped into the correct buckets, but they are still scattered across multiple executors. Every executor has produced its own local Bucket 0, Bucket 1, Bucket 2, and Bucket 3.</p><p>For example, all early-morning flights (00:00–06:00) are now sitting inside various <strong>Bucket 0</strong> files across the cluster.</p><p>They belong to the same range, but they haven’t been brought together yet, and they certainly haven’t been sorted.</p><p>That is exactly what happens in the final phase.</p><h4>Phase 3: Shuffle Read and Final Local Sort</h4><p>At the end of the Shuffle Write phase, every executor has produced its own local shuffle files.</p><p>Each one contains four buckets based on the boundaries we calculated earlier.</p><p>Conceptually, every executor maintains one local bucket for each destination partition (Bucket 0 through Bucket 3).</p><blockquote>Why does every executor create all four buckets?</blockquote><p>Remember that the input data is distributed across the entire cluster. One executor might process flights departing at 05:00, 08:30, and 21:15, while another processes flights at 01:45, 14:20, and 18:50. As each executor scans its own partition, it routes every row into the appropriate bucket using the same boundary array.</p><p>That means every executor can contribute rows to any bucket. For example, both executors may have flights departing before 06:00, so both will place those rows into their local <strong>Bucket 0</strong>. Similarly, they may also have afternoon or evening flights, which get written into <strong>Bucket 2</strong> or <strong>Bucket 3</strong> respectively.</p><p>Although rows have now been grouped into the correct ranges, each bucket still exists as multiple local copies spread across different executors. Spark’s next job is to bring those matching buckets together.</p><p>This is where the <strong>Shuffle Read</strong> phase begins.</p><p>Spark launches one reducer task for each final shuffle partition.</p><p>Since our example uses <strong>4 shuffle partitions</strong>, Spark creates <strong>4 reducer tasks</strong>:</p><ul><li><strong>Reducer Task 0</strong> is responsible for <strong>Bucket 0</strong></li><li><strong>Reducer Task 1</strong> is responsible for <strong>Bucket 1</strong></li><li><strong>Reducer Task 2</strong> is responsible for <strong>Bucket 2</strong></li><li><strong>Reducer Task 3</strong> is responsible for <strong>Bucket 3</strong></li></ul><p>Rather than explaining all four reducers separately, let’s continue following <strong>Reducer Task 0</strong>.</p><p>Its job is simple: collect <strong>Bucket 0</strong> from every executor.</p><p>Reducer Task 0 reaches out to every executor in the cluster and pulls only their <strong>Bucket 0</strong> data over the network.</p><p>At this point, something important has happened.</p><p>Every flight departing between <strong>00:00</strong> and <strong>06:00</strong> has now been brought together into a single partition, regardless of where it originally lived.</p><p>Likewise:</p><ul><li>Reducer Task 1 collects every flight between <strong>06:00</strong> and <strong>12:00</strong></li><li>Reducer Task 2 collects every flight between <strong>12:00</strong> and <strong>18:00</strong></li><li>Reducer Task 3 collects every flight between <strong>18:00</strong> and <strong>24:00</strong></li></ul><p>The global range layout is now complete.</p><p>However, there is still one final step.</p><p>Although every partition now contains the correct range of values, the rows inside each partition are <strong>not necessarily sorted</strong>.</p><p>For example, Reducer Task 0 might receive rows in this order:</p><pre>04:10<br>00:45<br>05:30<br>01:20<br>03:15</pre><p>All of these flights belong to the correct time range (00:00–06:00), but they arrived from different executors, so their order is essentially arbitrary.</p><p>To produce a sorted result, Spark performs one final <strong>local sort</strong> inside each reducer.</p><p>After sorting, the partition becomes:</p><pre>00:45<br>01:20<br>03:15<br>04:10<br>05:30</pre><p>The same local sort happens independently in every reducer.</p><p>Once this finishes, each partition is internally sorted, and the partitions themselves already represent ordered ranges:</p><ul><li>Partition 0 -&gt; 00:00–06:00</li><li>Partition 1 -&gt; 06:00–12:00</li><li>Partition 2 -&gt; 12:00–18:00</li><li>Partition 3 -&gt; 18:00–24:00</li></ul><p>Because the partitions themselves are already arranged in ascending order, Spark doesn’t need another global sorting step.</p><p>Reading the partitions sequentially naturally produces a fully sorted dataset across the entire cluster.</p><blockquote>If you want to see how this is implemented under the hood, the actual sampling logic and binary search routing live in the RangePartitioner class in the Apache Spark source code: <a href="https://github.com/apache/spark/blob/master/core/src/main/scala/org/apache/spark/Partitioner.scala">Spark Partitioner Source Code</a></blockquote><h4>3.3 Round Robin Partitioning</h4><p>So far, we’ve looked at two partitioning strategies that make decisions based on the <strong>values</strong> inside the data.</p><ul><li><strong>Hash Partitioning</strong> uses the hash of a key.</li><li><strong>Range Partitioning</strong> uses where a value falls within a set of boundaries.</li></ul><p>Round-robin partitioning works very differently.</p><p>It doesn’t look at any column. It doesn’t compute a hash. It doesn’t compare values against boundaries.</p><p>Instead, it simply distributes rows one by one across the available partitions in a rotating cycle, much like a dealer handing out cards around a table.</p><p>This is exactly the strategy Spark uses when you call df.repartition(4) without specifying any partitioning column.</p><h4>How It Works</h4><p>Imagine you have 12 flight records and you call repartition(4). Spark distributes the rows like this:</p><ul><li>Row 1 goes to Partition 0</li><li>Row 2 goes to Partition 1</li><li>Row 3 goes to Partition 2</li><li>Row 4 goes to Partition 3</li><li>Row 5 goes to Partition 0</li><li>Row 6 goes to Partition 1</li><li>…and so on until all rows are distributed.</li></ul><p>Each partition ends up with <strong>exactly three rows</strong>.</p><p>The same idea scales to larger datasets. If you have <strong>10 million rows</strong>, each partition receives roughly <strong>2.5 million rows</strong>. No partition is intentionally favored over another.</p><p>This is the only goal of round-robin partitioning: <strong>distribute data as evenly as possible.</strong></p><h4>What the Code Is Doing</h4><pre>selected_flight_df = flight_df.select(<br>    &quot;departure_time&quot;,<br>    &quot;arrival_time&quot;,<br>    &quot;origin_airport&quot;,<br>    &quot;destination_airport&quot;,<br>    &quot;flight_id&quot;<br>)<br> <br>selected_flight_df.repartition(4).show()</pre><p>When you call repartition(4) with only the number of partitions and no column, Spark automatically chooses <strong>Round-Robin Partitioning</strong>.</p><p>This operation triggers a full shuffle. Every row is redistributed across the cluster, but unlike hash or range partitioning, the destination partition is chosen purely by turn rather than by the row’s value.</p><h4>Reading the Spark UI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*D7Vt9sq00mvnAe59S96OrA.png" /><figcaption>Figure 13: Round-Robin Exchange</figcaption></figure><p>Before looking at the shuffle itself, there is one detail worth noticing in the Spark UI.</p><p>Now look at the Exchange metrics.</p><p>One metric says local blocks read: 16. Where did those <strong>16</strong> blocks come from? We never asked Spark to create 16 partitions.</p><p>This comes from Spark’s default file-reading behavior.</p><p>When Spark reads a large file from local disk or HDFS, it splits the input into blocks. The default block size is typically <strong>128 MiB</strong>, and Spark creates one input partition for each block.</p><p>For our dataset:</p><pre>2010 MiB ÷ 128 MiB ≈ 15.7</pre><p>which becomes <strong>16 input partitions</strong>.</p><p>At this point, no shuffle has happened yet. Spark has simply divided the input file into 16 partitions so they can be processed in parallel.</p><p>Now consider what happens when we call repartition(4)</p><p>Spark now has <strong>16 input partitions</strong> spread across the cluster, but the final result should contain only <strong>4 partitions</strong>.</p><p>This cannot be done locally.</p><p>Rows from many different input partitions need to contribute to each of the four final partitions, so Spark must redistribute the data across the network.</p><p>In other words, <strong>a shuffle is unavoidable.</strong></p><p>This is exactly what the <strong>Exchange</strong> operator represents.</p><p>Notice the physical plan:</p><pre>Exchange RoundRobinPartitioning(4), REPARTITION_BY_NUM</pre><p>The important part here is: REPARTITION_BY_NUM</p><p>This tells us that Spark is repartitioning <strong>only by the requested number of partitions</strong>.</p><p>Since no partitioning column was provided, Spark uses <strong>Round-Robin Partitioning</strong>, distributing rows evenly rather than grouping them by value.</p><h4>What Happens During the Shuffle?</h4><p>The Exchange performs the shuffle in two familiar phases.</p><p><strong>Shuffle Write (Map Side)</strong></p><p>Each of the <strong>16 input partitions</strong> runs its own map task.</p><p>As each task scans its rows, it assigns them to one of four destination buckets in round-robin order.</p><p>The rows are buffered in memory, spilled to disk if necessary, and finally written as the task’s shuffle output.</p><p>By the end of this phase, Spark has produced one shuffle output for each of the <strong>16 input partitions</strong>. Each shuffle output contains <strong>four logical buckets</strong>, one for each destination partition.</p><p><strong>Shuffle Read (Reduce Side)</strong></p><p>Spark now launches <strong>4 reducer tasks</strong>, one for each final partition.</p><p>Reducer Task 0 fetches <strong>Bucket 0</strong> from every shuffle output.</p><p>Reducer Task 1 fetches <strong>Bucket 1</strong> from every shuffle output.</p><p>The same process happens for Bucket 2 and Bucket 3.</p><p>Each reducer merges the data it receives into one final partition.</p><p>As a result, the original <strong>10 million rows</strong>, which were spread across <strong>16 input partitions</strong>, are now evenly distributed across <strong>4 output partitions</strong>.</p><h4>Reading the Exchange Metrics</h4><p>Now the Exchange metrics tell the complete story (Figure 13):</p><ul><li><strong>shuffle records written: 10,000,000 — </strong>every row participated in the shuffle.</li><li><strong>local blocks read: 16</strong> — confirms that the dataset originally consisted of 16 input partitions.</li><li><strong>number of partitions: 4</strong> — the four output partitions requested by repartition(4).</li><li><strong>shuffle bytes written total: 503.5 MiB</strong> — the compressed shuffle data written to local disk.</li><li><strong>data size total: 773.2 MiB</strong> — the in-memory size of the data before compression.</li></ul><p>The difference between <strong>773.2 MiB</strong> and <strong>503.5 MiB</strong> simply reflects Spark compressing the shuffle data before writing it to disk.</p><h4>When Should You Use Round-Robin Partitioning?</h4><p>Round-robin partitioning is useful when your only goal is to create <strong>evenly sized partitions</strong>.</p><p>For example, imagine a previous operation left one partition containing <strong>8 million rows</strong>, while the remaining three partitions together contain only <strong>2 million rows</strong>.</p><p>This kind of imbalance causes some tasks to finish quickly while one task continues running much longer than the others.</p><p>A simple repartition(n) redistributes the rows evenly, allowing all downstream tasks to process roughly the same amount of data.</p><p>Of course, there is a trade-off.</p><p>Because rows are distributed without considering their values, related records are no longer kept together.</p><p>For example, flights departing from the same airport may now be scattered across all four partitions.</p><p>If you later run:</p><pre>groupBy(&quot;origin_airport&quot;)</pre><p>Spark has no choice but to perform <strong>another shuffle</strong> to bring matching airport codes back together before it can aggregate them.</p><p>As a rule of thumb:</p><ul><li>Use <strong>Hash Partitioning</strong> when identical keys need to stay together.</li><li>Use <strong>Range Partitioning</strong> when global ordering matters.</li><li>Use <strong>Round-Robin Partitioning</strong> when your only goal is to distribute data evenly across partitions.</li></ul><h3>4. Local Aggregation vs Global Aggregation</h3><p>Suppose we execute the following query:</p><pre>flight_df.groupBy(&quot;origin_airport&quot;).count()</pre><p>At first glance, you might imagine Spark shuffling every flight record across the network before calculating the counts.</p><p>Fortunately, that isn’t what happens.</p><p>Think about what each flight record contains. Besides the origin_airport, it also includes information such as the departure time, arrival time, flight ID, destination airport, and several other columns. None of those fields are required to calculate a simple count.</p><p>Moving millions of complete rows across the network just to increment a counter would waste both network bandwidth and disk I/O.</p><p>Instead, Spark performs the aggregation in two phases:</p><ul><li><strong>Local Aggregation (Map Side)</strong></li><li><strong>Global Aggregation (Reduce Side)</strong></li></ul><p>This optimization dramatically reduces the amount of data that needs to be shuffled across the cluster.</p><h4>Phase 1: Local Aggregation (Map Side)</h4><p>Assume our dataset contains <strong>10 million flight records</strong> distributed across <strong>16 input partitions</strong>.</p><p>Each partition is processed independently by its own task.</p><p>Rather than immediately preparing every row for the shuffle, Spark first asks a simple question:</p><blockquote><strong><em>Can I aggregate the records that already exist inside this partition?</em></strong></blockquote><p>For aggregation functions such as count(), sum(), min(), max(), and many others, the answer is yes.</p><p>As each task scans its partition, it maintains an in-memory hash map. The key is the airport code, while the value stores the running aggregate.</p><p>For example, while processing one partition:</p><pre>BOM -&gt; 1<br>DEL -&gt; 1<br>BOM -&gt; 2<br>LHR -&gt; 1<br>BOM -&gt; 3<br>...</pre><p>After scanning the entire partition, the hash map might look like this:</p><pre>BOM -&gt; 10,000<br>DEL -&gt; 8,500<br>LHR -&gt; 6,200<br>...</pre><p>Notice what happened.</p><p>Spark didn’t preserve hundreds of thousands of individual flight records.</p><p>Instead, it condensed them into a much smaller set of partial results.</p><p>For example, if a partition originally contained <strong>625,000 rows</strong> but only <strong>200 unique airports</strong>, then only those <strong>200 partial counts</strong> need to continue to the shuffle.</p><p>This optimization becomes very obvious in the Spark UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*dmSzTiRMGrcRZJepOaybgg.png" /><figcaption>Figure 14: Scan CSV + Partial Aggregate</figcaption></figure><p>The execution plan shows:</p><ul><li><strong>Scan CSV:</strong> 10,000,000 input rows (~2 GB)</li><li><strong>HashAggregate:</strong> 28,080 output rows</li></ul><p>In other words, Spark reduced <strong>10 million flight records</strong> into just <strong>28,080 partial aggregates</strong> before the shuffle even began.</p><p>That is why aggregation queries are often much cheaper than people expect.</p><p>Spark isn’t shuffling the original dataset.</p><p>It’s shuffling summarized results.</p><h4>Preparing for the Shuffle</h4><p>Those partial aggregates now need to be redistributed across the cluster.</p><p>Imagine one executor finishes with:</p><pre>(BOM, 10000)<br>(DEL, 8500)<br>(LHR, 6200)</pre><p>while another executor produces:</p><pre>(BOM, 11200)<br>(DEL, 9000)<br>(LHR, 5800)</pre><p>Eventually, every partial count for <strong>BOM</strong> must arrive at the same reducer so Spark can calculate the final total.</p><p>To guarantee that, Spark uses the same <strong>hash partitioning</strong> mechanism we learned earlier.</p><p>For every partial aggregate, Spark computes:</p><pre>target_partition = abs(hash(origin_airport)) % num_shuffle_partitions</pre><p>For example:</p><pre>hash(&quot;BOM&quot;) % 4 = 0<br>hash(&quot;DEL&quot;) % 4 = 0<br>hash(&quot;LHR&quot;) % 4 = 2</pre><p>This guarantees that every partial result for <strong>BOM</strong> is written into <strong>Shuffle Bucket 0</strong>, regardless of which executor produced it.</p><p>Likewise, every partial result for <strong>LHR</strong> always goes into <strong>Bucket 2</strong>.</p><p>Once all map tasks finish writing their shuffle files, the first stage ends.</p><p>The shuffle read can now begin.</p><h4>Phase 2: Global Aggregation (Reduce Side)</h4><p>During the Shuffle Read phase, Spark launches one reducer task for each shuffle partition.</p><p>Suppose <strong>Reducer Task 0</strong> is responsible for <strong>Shuffle Bucket 0</strong>.</p><p>Just as we learned earlier in the article, it fetches <strong>only Bucket 0</strong> from every map output.</p><p>Its input now looks something like this:</p><pre>(BOM, 10000)<br>(BOM, 11200)<br>(BOM, 9800)<br>(BOM, 10500)<br><br>(DEL, 8500)<br>(DEL, 9000)<br>(DEL, 7600)<br>(DEL, 8200)<br><br>...</pre><p>Notice something important.</p><p>The reducer never receives the original flight records.</p><p>It only receives the partial aggregates produced during the map-side aggregation.</p><p>Now the final aggregation becomes extremely simple.</p><pre>BOM = 10000 + 11200 + 9800 + 10500 + ...<br><br>DEL = 8500 + 9000 + 7600 + 8200 + ...</pre><p>The final result becomes:</p><pre>BOM -&gt; 168,450<br>DEL -&gt; 142,980<br>LHR -&gt; 101,320<br>...</pre><p>This is exactly the result returned by:</p><pre>flight_df.groupBy(&quot;origin_airport&quot;).count()</pre><h4>Verifying It in the Spark UI</h4><p>The Spark UI clearly shows the benefit of this optimization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*K_uO9K-_eELadImP9fOvAg.png" /><figcaption>Figure 14: Exchange Metrics</figcaption></figure><p>Notice the Exchange metrics:</p><ul><li><strong>Shuffle records written:</strong> 28,080</li><li><strong>Shuffle records read:</strong> 28,080</li></ul><p>Compare that with the original dataset.</p><p>Spark started by scanning <strong>10 million flight records</strong>, but only <strong>28,080 summarized records</strong> were shuffled across the network.</p><p>That is almost <strong>350× fewer records</strong> than the original input.</p><h4>Why Spark Uses Two Aggregation Phases</h4><p>If Spark skipped the local aggregation step, every one of the <strong>10 million flight records</strong> would need to be shuffled across the network before the counting could even begin.</p><p>Instead, Spark performs as much work as possible where the data already exists.</p><p>By the time the shuffle starts, millions of raw records have already been reduced into a much smaller set of partial aggregates.</p><p>As a result:</p><ul><li>Less data travels across the network.</li><li>Less data is written to shuffle files.</li><li>Less data is read by reducer tasks.</li><li>Less work is required during the final aggregation.</li></ul><p>This two-phase aggregation strategy is one of the key reasons why Spark can efficiently process aggregation queries over datasets containing millions or even billions of records.</p><h3>Conclusion</h3><p>In this article, we explored what happens behind the scenes when Spark performs a shuffle.</p><p>We started by understanding why a shuffle is necessary, then followed the entire lifecycle of a shuffle, from writing shuffle files on the map side, to reading them on the reduce side, to seeing why every shuffle creates a stage boundary. We also explored the different partitioning strategies Spark uses and how map-side aggregation helps reduce the amount of data that needs to be shuffled.</p><p>My goal wasn’t just to explain <strong>what</strong> a shuffle is, but also to build an intuition for <strong>why</strong> Spark performs each of these steps.</p><p>I hope this article helped you develop that intuition and made Spark shuffles feel a little less like a black box.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92f69a06b863" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Code to Cloud: CI/CD for a Flask CRUD App Using GitLab and Docker — Part 2]]></title>
            <link>https://medium.com/@akashchevli888/in-part-1-we-explored-the-fundamentals-of-ci-cd-using-gitlab-421aaa1bd6e5?source=rss-66b1638b797------2</link>
            <guid isPermaLink="false">https://medium.com/p/421aaa1bd6e5</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[gitlab]]></category>
            <dc:creator><![CDATA[Akash Chevli]]></dc:creator>
            <pubDate>Tue, 10 Jun 2025 04:31:52 GMT</pubDate>
            <atom:updated>2025-06-10T04:33:58.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2bAMpkyYdXOkVCYCFaBLQ.png" /></figure><p>In <a href="https://medium.com/@akashchevli888/getting-started-with-gitlab-ci-cd-a-beginner-friendly-guide-to-pipelines-and-automation-part-1-b1d28f857e3a"><strong>Part 1</strong></a><strong>,</strong> we explored the fundamentals of CI/CD using GitLab. We broke down what CI/CD actually means, how GitLab pipelines work, and what goes on inside the .gitlab-ci.yml file.</p><p>If you’re new to CI/CD, I highly recommend checking out <strong>Part 1</strong> first — it’ll give you a solid foundation before diving into this one.</p><h3>What’s the Goal in Part 2?</h3><p>Now that the basics are out of the way, it’s time to move from theory to real-world application.</p><p>In this part, we’ll take a <strong>pre-built Flask CRUD app</strong> and build a complete CI/CD pipeline around it — from creating a Docker image to automatically deploying it on an <strong>AWS EC2 instance</strong> using GitLab CI/CD.</p><p>No need to worry about writing backend code from scratch — the app is already built and ready. Our focus will be on how to automate the build and deployment process using GitLab, and how all the moving parts come together in a real-world workflow.</p><p><strong>Tech Stack We’ll Use</strong></p><ul><li><strong>Flask</strong> — A lightweight Python web framework</li><li><strong>Docker</strong> — To containerize the application</li><li><strong>GitLab CI/CD</strong> — To automate everything from build to deploy</li><li><strong>AWS EC2</strong> — Our deployment target</li></ul><h3>High-Level Architecture Overview</h3><p>Before we dive into the code and config files, let’s take a step back and look at the big picture.</p><p>Here’s a high-level view of how everything will work together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*mLGisgqBdOML7NCQ609azQ.png" /></figure><ol><li><strong>Code is pushed to GitLab.</strong><br>This could be a small bug fix, a new feature, or any change to your app. As soon as you push, GitLab kicks off the CI/CD pipeline.</li><li><strong>GitLab Runner picks up the job.</strong><br>Think of the runner as a worker. It reads.gitlab-ci.yml file and follows the instructions step-by-step — build the app, run tests, deploy, and more.</li><li><strong>Docker builds a container image of the Flask app.</strong><br>Instead of installing Python and dependencies every time, we wrap the whole app into a Docker container so it runs the same way everywhere — locally or on the cloud.</li><li><strong>The built app is deployed to an AWS EC2 instance.</strong><br>Once the image is ready, the runner connects to your EC2 server, transfers what’s needed, and spins up the app there — no manual SSH or copying files.</li><li><strong>A Slack message is sent once the deployment finishes.</strong><br>Whether the deployment was successful or if something went wrong, the pipeline posts a clear notification to team’s Slack channel. This way, everyone stays informed instantly.</li></ol><h3>Source Code on GitLab</h3><p>You can view or clone the full project repository here:</p><p><a href="https://gitlab.com/akash-personal/flask-apis-cicd">GitLab Repo — Flask CI/CD with Docker</a></p><p>To clone the project:</p><pre>git clone https://gitlab.com/akash-personal/flask-apis-cicd.git</pre><h3>Project Structure: Flask Python App Explained</h3><pre>flask-crud-ci-cd-app/<br>├── app/<br>│   ├── models/<br>│   ├── views/<br>│   ├── __init__.py<br>│   └── extensions.py<br>├── docker/<br>│   ├── nginx/<br>│   │   └── nginx.conf<br>│   ├── docker-compose.yml<br>│   ├── docker-compose.test.yml<br>│   └── docker-compose.dev.yml<br>├── migrations/<br>├── scripts/<br>│   └── deploy.sh<br>├── test/<br>├── .dockerignore<br>├── .env<br>├── .env.example<br>├── .env.test<br>├── .gitignore<br>├── .gitlab-ci.yml<br>├── config.py<br>├── main.py<br>├── README.md<br>└── requirements.txt</pre><p>Before diving into the CI/CD pipeline, it’s important to get familiar with the project’s layout. Knowing where things live will help you follow the automation steps smoothly.</p><p>Here’s a breakdown of the key folders and files:</p><p><strong>app/</strong><br>The application containing all the Python code for the Flask app.</p><ul><li>models/ holds database model files defining how data is stored.</li><li>views/ contains route handlers — basically, the logic for each API endpoint.</li><li>__init__.py is where the Flask app is configured and set up, including registering blueprints and loggers.</li><li>extensions.py sets up important Flask extensions like SQLAlchemy for database access and migrations for handling schema changes.</li></ul><p><strong>docker/</strong><br>This folder manages containerization setup.</p><ul><li>nginx/ has the configuration file for the Nginx web server, which acts as a reverse proxy.</li><li>The different docker-compose files handle launching containers in various modes: production, testing, and development.</li></ul><p><strong>migrations/</strong><br>This folder stores all database migration files, helping keep track of schema changes over time.</p><p><strong>scripts/</strong><br>Contains helper scripts like deploy.sh, which will be triggered in the deployment stage of the pipeline to spin up or update Docker containers on the AWS EC2 instance.</p><p><strong>test/</strong><br>This directory holds test cases to verify that the application works as expected.</p><p><strong>Configuration and Environment Files</strong></p><ul><li>.env and .env.test store environment variables for production and testing environments respectively — like database credentials.</li><li>.gitlab-ci.yml is the GitLab pipeline configuration file that orchestrates the CI/CD process (we’ll explore this in detail soon).</li><li>config.py centralizes app configuration, pulling in environment variables and setting up database connections.</li><li>main.py is the entry point — the file that launches the Flask app.</li><li>requirements.txt lists all Python dependencies required for the project.</li></ul><h3>Understanding Our Docker Compose Setup</h3><p>Before we jump into CI/CD, let’s understand how our Docker setup works.</p><p>We use two Docker Compose files:</p><ul><li>docker-compose.test.yml: For running tests in CI.</li><li>docker-compose.yml: For running the app in production (or locally, if needed).</li></ul><ol><li>docker-compose.test.yml — <strong>For Running Tests</strong></li></ol><p>This file is used <strong>only during testing</strong>. It spins up two services:</p><p><strong>app : </strong>Flask app container that:</p><ul><li>Builds the image using the Dockerfile</li><li>Loads environment variables from .env.test</li><li>Waits for the database to be healthy</li><li>Runs migrations and then executes tests using pytest</li><li>Generates a test report inside /tests-reports</li></ul><p><strong>db : </strong>PostgreSQL container:</p><ul><li>Uses the official Postgres image</li><li>Loads test environment variables</li><li>Runs a health check so the app waits until the DB is ready</li></ul><p>2. docker-compose.yml — <strong>For Running the App</strong></p><p>This is our main production (or local run) Docker Compose file. It defines three services:</p><p><strong>backend :</strong></p><ul><li>Uses the Docker image pre-built and pushed to Docker Hub.</li><li>Loads environment variables from .env</li><li>Waits for the database to be ready</li><li>Runs database migrations</li><li>Launches the app using gunicorn</li><li>Includes a health check endpoint at /api/health</li></ul><p><strong>db:</strong></p><ul><li>PostgreSQL container for production</li><li>Persists data using Docker volumes (pgdata)</li><li>Uses .env values for config</li><li>Includes a health check</li></ul><p><strong>nginx :</strong></p><ul><li>Uses the official Nginx image</li><li>Forwards incoming requests (on port 8000) to the backend service</li><li>Uses a custom nginx.conf file for routing setup</li></ul><h3><strong>Use Your Own Docker Image (Recommended)</strong></h3><blockquote>Currently, our docker-compose.yml uses this image. (By the time this blog is published, this repository may no longer be available.)</blockquote><pre>image: akash2501/flask-crud-api</pre><p>If you’re creating your own version of the app, you should <strong>replace it with your own image</strong> hosted on Docker Hub.</p><p><strong>Steps to Create and Push Your Docker Image</strong></p><ol><li><strong>Login to Docker Hub</strong></li></ol><pre>docker login</pre><p><strong>Make sure you have created the repository on Docker Hub first.</strong></p><p>Go to your Docker Hub account → Repositories → Create Repository (e.g., flask-crud-api)</p><p>2. <strong>Build the Image</strong></p><pre>docker build -t your-dockerhub-username/flask-crud-api .</pre><p>3. <strong>(Optional) Tag the Image</strong></p><pre>docker tag your-dockerhub-username/flask-crud-api your-dockerhub-username/flask-crud-api:latest</pre><p>4. <strong>Push the Image to Docker Hub</strong></p><pre>docker push your-dockerhub-username/flask-crud-api</pre><p>Now your image is ready to be used in GitLab CI/CD and in your docker-compose.yml.</p><h3>Setting Up the EC2 Instance on AWS</h3><ol><li><strong>Log in to AWS Console</strong></li></ol><ul><li>Head over to <a href="https://aws.amazon.com/">aws.amazon.com</a> and sign in with your account.</li><li>Go to the EC2 Dashboard by searching for <strong>EC2</strong> in the AWS search bar.</li></ul><p>2. <strong>Launch a New Instance</strong></p><ul><li>You’ll see a big blue button labeled <strong>Launch Instance</strong> — click that.</li></ul><p>3. <strong>Set the Instance Details</strong></p><ul><li><strong>Name</strong>: Use something like flask-app-server. You can name it anything meaningful to you.</li><li><strong>Amazon Machine Image (AMI)</strong>: Select <strong>Amazon Linux</strong></li><li><strong>Instance Type</strong>: Choose <strong>t2.micro</strong> (which is Free Tier eligible).</li><li><strong>Key Pair (login method)</strong>:</li><li>If you already have a key pair, select it.</li><li>If not, click <strong>Create new key pair</strong>, choose .pem format, and download it. you’ll need it to SSH into the machine.</li></ul><p>4. <strong>Configure Network Settings</strong></p><ul><li>Allow <strong>SSH (Port 22)</strong> so you can connect to the server.</li><li>Allow <strong>HTTP (Port 80).</strong></li></ul><p>5. <strong>Finalize and Launch</strong></p><ul><li>You can leave other settings as default. Click <strong>Launch Instance</strong>.</li></ul><p>Once the instance is ready, you’ll get a <strong>Public IPv4 Address</strong>. This is how we’ll SSH into it and where our app will be deployed.</p><h3><strong>Connecting to the EC2 Instance and Setting Up SSH Access</strong></h3><p>Now that EC2 instance is running, let’s connect to it.</p><ol><li><strong>Open Terminal and Set Permissions on the </strong>.pem<strong> File:</strong></li></ol><p>After downloading the .pem file (while launching the instance), make sure it has the correct permissions:</p><pre>chmod 400 your-key.pem</pre><p>Replace your-key.pem with the actual filename.</p><p>2. <strong>Connect to the EC2 Instance via SSH</strong></p><pre>ssh -i your-key.pem ec2-user@&lt;your-ec2-public-ip&gt;</pre><p>Replace &lt;your-ec2-public-ip&gt; with the instance’s public IP address (found in the EC2 dashboard)</p><p>If successful, you’re now inside your EC2 instance.</p><p>3. <strong>Create a New SSH Key Pair Locally (For GitLab)</strong></p><p>On your <strong>local machine</strong>, run:</p><pre>ssh-keygen -t rsa -b 4096 -f deploy_key</pre><ul><li>When prompted, leave the passphrase empty</li><li>This will create two files:</li><li>deploy_key : private key (we’ll use this in GitLab CI/CD)</li><li>deploy_key.pub : public key (we’ll copy this to EC2)</li></ul><p>4. <strong>Copy the Public Key to the EC2 Instance</strong></p><p>Run this command <strong>from your local machine</strong> (the one where you created deploy_key.pub):</p><pre>cat deploy_key.pub | ssh -i your-key.pem ec2-user@&lt;your-ec2-public-ip&gt; &quot;mkdir -p ~/.ssh &amp;&amp; cat &gt;&gt; ~/.ssh/authorized_keys&quot;</pre><p>This adds your new public key to the EC2 instance’s authorized_keys file, allowing GitLab to SSH into it using the private key later.</p><p>5. <strong>Verify Passwordless SSH Works</strong></p><p>Now you can test that new SSH key works:</p><pre>ssh -i deploy_key ec2-user@&lt;your-ec2-public-ip&gt;</pre><h3>Installing Docker and Docker Compose on the EC2 Instance</h3><p>Once you’ve connected to your EC2 instance (using the .pem file or the new SSH key), the next step is to install <strong>Docker</strong> and <strong>Docker Compose</strong> so that your app can run in containers.</p><ol><li><strong>Install Docker</strong></li></ol><pre>sudo yum update -y<br>sudo yum install docker -y</pre><p>Once installed, start the Docker service:</p><pre>sudo service docker start</pre><p>Add the ec2-user to the docker group so you can run Docker without sudo:</p><pre>sudo usermod -aG docker ec2-user</pre><p>Verify the installation by running:</p><pre>docker --version</pre><p>2. <strong>Install Docker Compose</strong></p><p>Run the following commands:</p><pre>sudo curl -L &quot;https://github.com/docker/compose/releases/download/v2.24.1/docker-compose-$(uname -s)-$(uname -m)&quot; -o /usr/local/bin/docker-compose</pre><p>Make it executable:</p><pre>sudo chmod +x /usr/local/bin/docker-compose</pre><p>Verify the installtion by running:</p><pre>docker-compose --version</pre><p>If you see the version printed, you’re all set.</p><h3>Preparing the Deployment Directory on EC2</h3><p>Before we actually deploy anything, let’s set up a clean place on the EC2 instance where all our Docker-related files will live.</p><p>We’ll create an app/ folder in the home directory. This will act as our working directory — GitLab CI/CD will use this path when copying files and running Docker Compose.</p><p>Run this on your EC2 instance:</p><pre>mkdir ~/app</pre><p>This app/ folder will act as the root directory for our application. During deployment, Our GitLab CI/CD will copy the necessary files — like docker-compose.yml and nginx.conf — into this directory using the deploy.sh script.</p><p>Now, inside this app/ folder, make sure to create a .env file. This file is important — docker-compose uses it to load environment variables at runtime.</p><p>To create .env file</p><pre>touch ~/app/.env</pre><p>Then open it in any editor and add the necessary variables. For example:</p><pre>POSTGRES_DB=flask-cicd<br>POSTGRES_HOST=db<br><br>.....<br>&lt;Add other variables as well&gt;</pre><h3>Setting Up GitLab CI/CD Variables</h3><p>Before we connect our project to GitLab CI/CD and start running pipelines, we need to define a few important variables in GitLab. These variables include your Docker Hub credentials, SSH private key, and the .env.test file content.</p><p>This step is <strong>mandatory</strong>. If you skip it, CI/CD pipeline will fail during Docker login or deployment.</p><p><strong>Prerequisite</strong></p><p>If you haven’t already:</p><ul><li><strong>Fork the repository</strong> or <strong>clone and set up your own</strong> GitLab project.</li><li>Once your project is ready, open GitLab and follow the steps below to set up the environment variables.</li></ul><p><strong>Where to Add These Variables</strong></p><ol><li>Go to your GitLab project.</li><li>Click on Settings — &gt; CI/CD.</li><li>Expand the Variables section.</li><li>Click <strong>Add variable</strong> for each key listed below.</li></ol><blockquote><strong>Important:</strong> Do <strong>not</strong> check the <strong>Protected</strong> checkbox.<br>Protected variables only work on protected branches, and our default branch may not be protected in your . This can silently break your pipeline.</blockquote><p><strong>Docker Hub Credentials</strong></p><p>We need these to authenticate with Docker Hub inside our CI pipeline.</p><ul><li><strong>DOCKER_USERNAME</strong>: Your Docker Hub username.</li><li><strong>DOCKER_PASSWORD</strong>: Your Docker Hub password or an access token.</li></ul><blockquote>Make sure to keep them <strong>unprotected</strong> and optionally <strong>masked</strong> for security.</blockquote><p><strong>SSH Access to EC2 (Deployment)</strong></p><p>We’re using a custom SSH key for deployment. You should already have this key pair ready:</p><ul><li>DEPLOY_PRIVATE_KEY: This is the <strong>private key</strong> we created earlier. We’ll use this in GitLab to SSH into the EC2 instance.</li></ul><p>Make sure the <strong>public key</strong> has already been added to your EC2 instance’s ~/.ssh/authorized_keys(We did earlier).</p><p>Also add:</p><ul><li>DEPLOY_USER: ec2-user</li><li>DEPLOY_HOST: Your EC2 instance’s public IP</li><li>DEPLOY_PRIVATE_KEY : Paste the <strong>private key</strong> content here (the one we created earlier and added to EC2’s authorized_keys)</li></ul><blockquote><strong>Use Variable type (not File)</strong> for DEPLOY_PRIVATE_KEY, and <strong>paste the private key directly</strong> into the value field.</blockquote><p><strong>Test Environment File</strong></p><p>We use a .env.test file for running automated tests inside the pipeline.</p><p>You can start by copying the contents from your .env.example file, but <strong>make sure to update the values to match the container names and test configuration</strong>. For example:</p><ul><li>Set the POSTGRES_HOST to db_test (the name of test DB container)</li><li>Use test-specific values for POSTGRES_DB, POSTGRES_USER, and POSTGRES_PASSWORD</li></ul><p>Once ready, add:</p><ul><li>TEST_ENV_FILE: Paste the contents of your .env.test</li></ul><blockquote>Set the <strong>Type</strong> to <strong>File</strong> when adding this variable.</blockquote><p><strong>Docker Image Name</strong></p><p>DOCKER_IMAGE_NAME: e.g., yourdockerhub/flask-crud-api</p><p><strong>Slack Webhook</strong></p><p>To let GitLab send messages to Slack, we need a Slack Incoming Webhook URL. Here’s how to create one:</p><p><strong>Steps to Create a Slack Webhook:</strong></p><ol><li>Create a Slack Account (if you don’t already have one):</li><li>Create a Channel for CI/CD notifications:</li></ol><ul><li>Click the <strong>+</strong> next to Channels on the left.</li><li>Name it something like #cicd-notify.</li></ul><p>3. On the left sidebar, click on <strong>Apps</strong>.</p><p>4. In the search bar, type and select <strong>Incoming WebHooks</strong>.</p><p>5. Click <strong>Add to Slack.</strong></p><p>6. Select the channel (e.g., #cicd-notify) where notifications should go click A<strong>dd Incoming Webhooks Integration</strong>.</p><p>7. Copy the generated <strong>Webhook URL</strong></p><p>8. Add a new variable:</p><ul><li><strong>Key:</strong> SLACK_WEBHOOK_URL</li><li><strong>Value:</strong> <em>(</em>paste your Slack webhook URL<em>)</em></li></ul><h3>Detailed Explanation of the .gitlab-ci.yml File: How the GitLab CI/CD Pipeline Works</h3><p>This .gitlab-ci.yml file defines an automated pipeline that runs three main steps whenever code is merged (PR for main branch) or pushed to the main branch: <strong>testing</strong>, <strong>building the Docker image</strong>, and <strong>deploying to an AWS EC2 instance</strong>.</p><p>Each part of this file configures how GitLab will execute these steps. Below is a breakdown of each section with clear explanations.</p><ol><li><strong>Pipeline Stages</strong></li></ol><pre>stages:<br>  - test<br>  - build<br>  - deploy</pre><p>The pipeline is divided into <strong>stages</strong> — logical steps that run one after another:</p><ul><li><strong>Test:</strong> Run automated tests to verify the application works correctly.</li><li><strong>Build:</strong> Once tests pass, the pipeline proceeds to build a Docker image. This step packages the application into a self-contained environment, making it easier to deploy consistently across different systems.</li><li><strong>Deploy:</strong> Deploy the built Docker image to a remote server (in this case, an AWS EC2 instance).</li></ul><p>GitLab executes all jobs in one stage before moving to the next.</p><p>2. <strong>Workflow Rules</strong></p><pre>workflow:<br>  rules:<br>    - if: &#39;$CI_MERGE_REQUEST_TARGET_BRANCH_NAME == &quot;main&quot;&#39;<br>      when: always<br>    - if: &#39;$CI_COMMIT_BRANCH == &quot;main&quot; &amp;&amp; $CI_PIPELINE_SOURCE == &quot;push&quot;&#39;<br>      when: always<br>    - when: never</pre><p>The workflow section defines <strong>when the entire pipeline should be triggered</strong>. Without this, GitLab run pipelines for every push, even on branches where automation isn&#39;t needed.</p><ul><li><strong>Run on Merge Requests to </strong>main</li></ul><pre>- if: &#39;$CI_MERGE_REQUEST_TARGET_BRANCH_NAME == &quot;main&quot;&#39;<br>  when: always</pre><p>This ensures the pipeline runs <strong>when a merge request targets the </strong>main<strong> branch</strong> — even before the code is actually merged.</p><ul><li><strong>Run on Direct Pushes to</strong> main</li></ul><pre>- if: &#39;$CI_COMMIT_BRANCH == &quot;main&quot; &amp;&amp; $CI_PIPELINE_SOURCE == &quot;push&quot;&#39;<br>  when: always</pre><p>This runs the pipeline <strong>when code is pushed directly to the </strong>main<strong> branch</strong>, such as when a merge request is accepted.</p><ul><li><strong>Disable for All Other Cases</strong></li></ul><pre>- when: never</pre><p>In every other scenario — like feature branches — the pipeline is skipped.</p><p>3. <strong>Docker Setup with Docker-in-Docker (DinD)</strong></p><pre>.default-docker:<br>  Docker Setup with Docker-in-Docker (DinD)image: docker:latest<br>  services:<br>    - docker:dind<br>  before_script:<br>    - echo &quot;$DOCKER_PASSWORD&quot; | docker login -u &quot;$DOCKER_USERNAME&quot; --password-stdin</pre><p>This section configures the environment required to run Docker commands inside GitLab CI/CD pipelines<strong> </strong>— a technique known as <strong>Docker-in-Docker (DinD)</strong>.</p><p><strong>What Is Docker-in-Docker (DinD)?</strong></p><p>CI/CD jobs in GitLab run in containers. But to build or push Docker images inside those jobs, a Docker engine must be available — which isn’t present by default. <strong>DinD solves this by running the Docker daemon as a background service within the CI container.</strong></p><p><strong>Docker-in-Docker (DinD)</strong> means running Docker inside a Docker container. This is necessary because the CI/CD jobs run inside isolated containers but need to build and push Docker images.</p><ul><li>docker:latest is the base image used to run the job. This image includes the Docker CLI.</li><li>The before_script logs in to Docker Hub using credentials stored securely as GitLab variables.</li></ul><p>4. <strong>Test Job</strong></p><pre>test:<br>  extends: .default-docker<br>  stage: test<br>  script:<br>    - cp &quot;$TEST_ENV_FILE&quot; .env.test<br>    - docker-compose -f docker/docker-compose.test.yml build<br>    - docker-compose -f docker/docker-compose.test.yml up --abort-on-container-exit<br>  after_script:<br>    - docker-compose -f docker/docker-compose.test.yml down<br>  artifacts:<br>    when: always<br>    reports:<br>      junit: tests-reports/report.xml<br>    paths:<br>      - tests-reports/report.xml</pre><p>This job runs automated tests using Docker Compose:</p><ul><li>Copies a test environment file (.env.test) which holds environment-specific variables for testing.</li><li>Builds and runs test containers using docker-compose.test.yml. These containers run the tests inside them.</li><li>After tests finish, the containers are stopped.</li><li>Test results are saved as <strong>artifacts</strong>, meaning they are accessible later in the GitLab interface, regardless of success or failure.</li></ul><p>5. <strong>Build Job</strong></p><pre>build:<br>  extends: .default-docker<br>  stage: build<br>  script:<br>    - docker build -f docker/Dockerfile -t $DOCKER_IMAGE_NAME:$CI_COMMIT_SHA .<br>    - docker push $DOCKER_IMAGE_NAME:$CI_COMMIT_SHA<br>    - |<br>      if [ &quot;$CI_COMMIT_BRANCH&quot; == &quot;main&quot; ]; then<br>        docker tag $DOCKER_IMAGE_NAME:$CI_COMMIT_SHA $DOCKER_IMAGE_NAME:prod<br>        docker push $DOCKER_IMAGE_NAME:prod<br>      fi<br>  needs:<br>    - job: test<br>      artifacts: false</pre><p>This job builds and pushes the Docker image:</p><ul><li>Builds the Docker image using the Dockerfile and tags it with the commit SHA — a unique identifier for the code version.</li><li>Pushes the image to Docker Hub (a container registry where Docker images are stored).</li><li>If the commit is on the main branch, the image is also tagged as prod and pushed again. This tag is typically used in production deployment.</li><li>The build job only starts after the test job completes successfully.</li></ul><p>6. <strong>Deploy Job</strong></p><pre>deploy:<br>  stage: deploy<br>  image: alpine:latest<br>  only:<br>    - main<br>  before_script:<br>    - apk add --no-cache openssh curl<br>    - mkdir -p ~/.ssh<br>    - echo &quot;$DEPLOY_PRIVATE_KEY&quot; &gt; ~/.ssh/deploy_key<br>    - chmod 600 ~/.ssh/deploy_key<br>    - ssh-keyscan &quot;$DEPLOY_HOST&quot; &gt;&gt; ~/.ssh/known_hosts<br>  script:<br>    - chmod +x scripts/deploy.sh<br>    - ./scripts/deploy.sh &quot;$DEPLOY_USER&quot; &quot;$DEPLOY_HOST&quot;<br>  after_script:<br>    - |<br>      if [ &quot;$CI_JOB_STATUS&quot; = &quot;success&quot; ]; then<br>        STATUS=&quot;Deployment successful&quot;<br>      else<br>        STATUS=&quot;Deployment failed&quot;<br>      fi<br><br>      MESSAGE=$(cat &lt;&lt;EOF<br>       {<br>          &quot;blocks&quot;: [<br>          {<br>            &quot;type&quot;: &quot;section&quot;,<br>            &quot;text&quot;: {<br>              &quot;type&quot;: &quot;mrkdwn&quot;,<br>              &quot;text&quot;: &quot;*Flask CRUD App - Test Report*\n*Status:* $STATUS\n*Branch:* \`$CI_COMMIT_REF_NAME\`\n*Commit:* \`$CI_COMMIT_SHORT_SHA\`\n&lt;${CI_PROJECT_URL}/-/pipelines/${CI_PIPELINE_ID}|View Pipeline&gt;&quot;<br>            }<br>          }<br>        ]<br>      }<br>      EOF<br>      )<br><br>      curl -X POST &quot;$SLACK_WEBHOOK_URL&quot; \<br>           -H &quot;Content-Type: application/json&quot; \<br>           --data &quot;$MESSAGE&quot;</pre><p>This job deploys the application to an AWS EC2 instance:</p><ul><li>It runs only for changes pushed to the main branch.</li><li>Uses a lightweight Alpine Linux container to execute deployment steps.</li><li>Installs SSH client to connect securely to the EC2 instance.</li><li>Sets up SSH authentication by adding the private SSH key (stored securely in GitLab variables).</li><li>Adds the EC2 server to the list of known hosts to avoid SSH warnings.</li><li>Runs a deployment script (deploy.sh) which connects to the EC2 instance, pulls the new Docker image, and restarts the application containers.</li></ul><p>After the deployment steps, it also:</p><ul><li>Checks if the deploy job succeeded or failed using the special variable CI_JOB_STATUS. CI_JOB_STATUS is a built-in GitLab variable that tells you the current job’s outcome. It can be: success or failed .</li><li>Creates a formatted Slack message including the app name, deployment status (success or failure), branch name, commit ID, and a link to the pipeline for quick access.</li><li>Sends this message to a Slack channel using the webhook URL stored securely in GitLab variables.</li></ul><h3>What Are Artifacts and Why Are They Important?</h3><p>Artifacts are the files saved from a job to be accessed later. In this pipeline, test results are saved as artifacts so developers can see if tests passed or failed right inside GitLab.</p><p>Without artifacts, once the job finishes, all its files would be lost because jobs run in temporary environments. Artifacts make sure important files like logs and reports survive beyond the job.</p><p>Saving test reports as artifacts helps keep the pipeline transparent, speeds up debugging.</p><h3>Step-by-Step Guide to deploy.sh: Deploying Our App to EC2</h3><p>Once our Docker image is built and pushed, it’s time to deploy the updated container to our <strong>EC2 instance (Step 6)</strong>. We’ve written a small shell script — deploy.sh — that handles this process step by step. Let’s walk through what this script does and why each step matters.</p><pre>#!/bin/sh<br><br>set -e<br><br>DEPLOY_USER=$1<br>DEPLOY_HOST=$2<br><br>DEPLOY_PATH=&quot;/home/$DEPLOY_USER/app&quot;<br>COMPOSE_FILE=&quot;$DEPLOY_PATH/docker/docker-compose.yml&quot;<br>NGINX_CONF=&quot;$DEPLOY_PATH/docker/nginx/nginx.conf&quot;<br>KEY_PATH=&quot;$HOME/.ssh/deploy_key&quot;<br><br>echo &quot;Preparing deployment directory on remote host...&quot;<br>ssh -i &quot;$KEY_PATH&quot; &quot;$DEPLOY_USER@$DEPLOY_HOST&quot; &quot;<br>  sudo mkdir -p $DEPLOY_PATH/docker/nginx &amp;&amp;<br>  sudo chown -R $DEPLOY_USER:$DEPLOY_USER $DEPLOY_PATH/docker<br>&quot;<br><br>echo &quot;Copying configuration files...&quot;<br>scp -i &quot;$KEY_PATH&quot; docker/docker-compose.yml &quot;$DEPLOY_USER@$DEPLOY_HOST:$COMPOSE_FILE&quot;<br>scp -i &quot;$KEY_PATH&quot; docker/nginx/nginx.conf &quot;$DEPLOY_USER@$DEPLOY_HOST:$NGINX_CONF&quot;<br><br>echo &quot;Deploying containers on remote host...&quot;<br>ssh -i &quot;$KEY_PATH&quot; &quot;$DEPLOY_USER@$DEPLOY_HOST&quot; &quot;<br>  cd $DEPLOY_PATH &amp;&amp;<br>  docker-compose -f docker/docker-compose.yml pull &amp;&amp;<br>  docker-compose -f docker/docker-compose.yml down &amp;&amp;<br>  docker-compose -f docker/docker-compose.yml up -d --build<br>&quot;<br><br>echo &quot;Deployment completed successfully.&quot;</pre><ol><li><strong>Accepting Parameters</strong></li></ol><pre>DEPLOY_USER=$1<br>DEPLOY_HOST=$2</pre><p>These are values passed into the script. We use them to connect to the remote EC2 instance:</p><ul><li>DEPLOY_USER: SSH username (In our caseec2-user)</li><li>DEPLOY_HOST: EC2 public IP or hostname</li></ul><p>2. <strong>Define Paths</strong></p><pre>DEPLOY_PATH=&quot;/home/$DEPLOY_USER/app&quot;<br>COMPOSE_FILE=&quot;$DEPLOY_PATH/docker/docker-compose.yml&quot;<br>NGINX_CONF=&quot;$DEPLOY_PATH/docker/nginx/nginx.conf&quot;<br>KEY_PATH=&quot;$HOME/.ssh/deploy_key&quot;</pre><p>These variables define:</p><ul><li>Where to place the app on the server</li><li>Where to copy config files</li><li>Where the SSH private key is stored (used to connect securely)</li></ul><p>3. <strong>Prepare Remote Directory</strong></p><pre>ssh -i &quot;$KEY_PATH&quot; &quot;$DEPLOY_USER@$DEPLOY_HOST&quot; &quot;<br>  sudo mkdir -p $DEPLOY_PATH/docker/nginx &amp;&amp;<br>  sudo chown -R $DEPLOY_USER:$DEPLOY_USER $DEPLOY_PATH/docker<br>&quot;</pre><p>This connects to the EC2 instance and:</p><ul><li>Creates necessary directories (if not already present)</li><li>Ensures that the current user owns those directories (needed to copy files without permission issues)</li></ul><p>4. <strong>Copy Configuration Files</strong></p><pre>scp -i &quot;$KEY_PATH&quot; docker/docker-compose.yml &quot;$DEPLOY_USER@$DEPLOY_HOST:$COMPOSE_FILE&quot;<br>scp -i &quot;$KEY_PATH&quot; docker/nginx/nginx.conf &quot;$DEPLOY_USER@$DEPLOY_HOST:$NGINX_CONF&quot;</pre><p>This securely copies two important files to the EC2 instance:</p><ul><li>docker-compose.yml – defines how to run the app in containers</li><li>nginx.conf – handles reverse proxy.</li></ul><p>6. <strong>Deploy the Containers</strong></p><pre>ssh -i &quot;$KEY_PATH&quot; &quot;$DEPLOY_USER@$DEPLOY_HOST&quot; &quot;<br>  cd $DEPLOY_PATH &amp;&amp;<br>  docker-compose -f docker/docker-compose.yml pull &amp;&amp;<br>  docker-compose -f docker/docker-compose.yml down &amp;&amp;<br>  docker-compose -f docker/docker-compose.yml up -d --build<br>&quot;</pre><p>This block runs on the remote server:</p><ul><li><strong>Pulls</strong> the latest image from Docker Hub</li><li><strong>Stops</strong> any running containers</li><li><strong>Starts</strong> containers in the background (-d) and <strong>rebuilds</strong></li></ul><h3>Verify Deployment: Quick API Checks to Confirm Everything’s Up and Running!</h3><p>After the CI/CD pipeline completes successfully and the app is live on the EC2 instance, test these API endpoints to ensure everything works smoothly:</p><ul><li><strong>Health Check:</strong> GET http://&lt;ec2_public_ip&gt;/api/health/<br> Confirms the app is online and responsive.</li><li><strong>Create Post:</strong> POST http://&lt;ec2_public_ip&gt;/api/posts<br> Adds a new post to the app.</li><li><strong>Update Post:</strong> PATCH http://&lt;ec2_public_ip&gt;/api/posts/1<br> Modifies the post with ID 1.</li><li><strong>Delete Post:</strong> DELETE http://&lt;ec2_public_ip&gt;/api/posts/1<br> Removes the post with ID 1.</li><li><strong>Get Post:</strong> GET http://&lt;ec2_public_ip&gt;/api/posts/1<br> Retrieves details of a specific post.</li><li><strong>List Posts:</strong> GET http://&lt;ec2_public_ip&gt;/api/posts<br> Displays all available posts.</li></ul><p>Also, to confirm the app containers are running properly on the EC2 instance, use these Docker commands:</p><ul><li>docker ps — Shows currently running containers.</li><li>docker ps -a — Lists all containers, including stopped ones.</li></ul><h3>Summary</h3><p>In this guide, we walked through creating a full CI/CD pipeline for a Flask CRUD application using GitLab. We started by Dockerizing the Flask app to ensure consistent environments. Then, we set up GitLab CI/CD stages to build the Docker image, run tests, and deploy the application automatically to an AWS EC2 instance. Along the way, we handled environment variables securely, managed file permissions to avoid deployment errors. Finally, we integrated Slack notifications to keep the team informed about the build and deployment status in real-time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=421aaa1bd6e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with GitLab CI/CD: A Beginner-Friendly Guide to Pipelines and Automation — Part 1]]></title>
            <link>https://medium.com/@akashchevli888/getting-started-with-gitlab-ci-cd-a-beginner-friendly-guide-to-pipelines-and-automation-part-1-b1d28f857e3a?source=rss-66b1638b797------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1d28f857e3a</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[gitlab]]></category>
            <dc:creator><![CDATA[Akash Chevli]]></dc:creator>
            <pubDate>Wed, 07 May 2025 04:56:48 GMT</pubDate>
            <atom:updated>2025-05-07T04:56:48.849Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-3Rnt-fa6d7L0rNAJuaVPA.png" /></figure><h3><strong>Table of Contents</strong></h3><p>· <a href="#10bc">Introduction to CI/CD</a><br>· <a href="#66cd">Why do we need CI/CD?</a><br>· <a href="#6a1b">What is CI/CD?</a><br>· <a href="#2bef">Overview of GitLab CI/CD</a><br>· <a href="#cadd">Understanding the .gitlab-ci.yml File</a><br>· <a href="#0879">Setting Up a New GitLab Project and Creating .gitlab-ci.yml</a><br>· <a href="#1704">Understanding and Breaking Down the .gitlab-ci.yml File</a><br>· <a href="#a87d">Viewing and Understanding GitLab Pipeline</a><br>· <a href="#c7da">But Wait… What Are All These Logs?</a><br>· <a href="#9aa6">GitLab CI/CD Architecture: Server and Runner</a><br>· <a href="#5728">How a GitLab Job Actually Runs</a><br>· <a href="#f7cf">Wrapping Up the Basics</a><br>· <a href="#ef5f">What’s Next?</a></p><h3>Introduction to CI/CD</h3><p>In today’s fast-paced software world, simply writing code isn’t enough. We need a way to get code from developer’s laptop to live application — quickly, reliable, and safely. That’s exactly where <strong>CI/CD</strong> comes in.</p><p>Before we dive deeper, let’s first understand <strong>why we even need CI/CD</strong> in the first place.</p><h3>Why do we need CI/CD?</h3><p>Imagine you’re developing a web application. You write some code, test it on your local machine, and the push the changes to a version control system like GitLab.</p><p>Now, to make your changes live, you log into your server (maybe an AWS EC2 instance), pull the latest code, install dependencies, and restart services.</p><p>When you’re the only developer, this manual process is still manageable. But as your team grows and your application becomes more complex, this way of working starts causing problems:</p><ul><li><strong>Inconsistencies</strong>: Different people might follow different steps while deploying, leading to unpredictable environments.</li><li><strong>Delays</strong>: Manually deploying code every time a change happens slows down the release process.</li><li><strong>Errors</strong>: Manual steps increase the chances of mistakes — like forgetting to install dependency or forgetting to restart any service.</li></ul><p>This is exactly where <strong>CI/CD</strong> comes into the picture:<br>It automates the entire cycle — from pushing the code, testing it, and finally deploying it — so that teams can move faster and make fewer mistakes.</p><h3>What is CI/CD?</h3><p>Now that we understand the “why”, let’s talk about the CI/CD actually means.</p><p><strong>CI/CD</strong> stands for:</p><ul><li><strong>Continuous Integration (CI)</strong></li><li><strong>Continuous Deployment (CD)</strong></li></ul><p>Let’s break it down:</p><p><strong>Continuous Integration (CI)</strong></p><p>Continuous Integration is the practice of automatically merging small code changes from multiple developers into a shared repository.</p><p>Every time someone pushes code:</p><ul><li>Automated tests and checks run automatically.</li><li>If any problem is detected, developers are alerted immediately.</li><li>If everything looks good, the code safely becomes part of the project.</li></ul><p><strong>Continues Deployment (CD)</strong></p><p>Continues Deployment takes it one step further.</p><p>Once code has passed all the tests during Continues Integration, it is automatically deployed to production — no manual work needed.</p><p>The flow becomes:</p><p><strong>Push code → Run tests → If tests pass → Automatically deploy to live server</strong></p><p>This means:</p><ul><li>New features reach users faster.</li><li>Developers don’t have to worry about logging into servers or manually updating anything.</li></ul><p><strong>Note:</strong></p><p>Sometimes you might hear about <strong>Continuous Delivery</strong> instead of Deployment. In Continuous Delivery, code is <strong>ready</strong> to go live automatically, but the final release still needs a manual approval. In Continuous Deployment, even that approval step is automated — code goes live as soon as it passes tests.</p><h3>Overview of GitLab CI/CD</h3><p>Now that we know why CI/CD is important, let’s talk about how GitLab helps us set it up easily.</p><p><strong>GitLab CI/CD</strong> allows you to:</p><ul><li>Automatically test your code when you push changes.</li><li>Build and package your application.</li><li>Deploy your application to servers.</li><li>Monitor the results, errors and deployment history.</li></ul><h3>Understanding the .gitlab-ci.yml File</h3><p>Now, how does GitLab know what steps it should run for your project? The answer is: You define all the pipeline instructions inside a special file called .gitlab-ci.yml.</p><p>You place this file in the <strong>root folder</strong> of your project.</p><p>In this file, you tell GitLab things like:</p><ul><li>When should the pipeline run? (e.g., on every push)</li><li>What jobs should be performed? (e.g., run tests, build the app, deploy)</li><li>In what order should those jobs run?</li></ul><h3>Setting Up a New GitLab Project and Creating .gitlab-ci.yml</h3><p>Before we run a simple pipeline, let’s first create a fresh project and repository where we can experiment.</p><p>Here’s what you need to do:</p><ol><li><strong>Create a New GitLab Project</strong></li></ol><ul><li>Log in to your GitLab account.</li><li>Click on <strong>New Project</strong>.</li><li>Choose <strong>Create Blank Project</strong>.</li><li>Give your project any name you like (for example: ci-cd-demo).</li><li>Set visibility to <strong>Private</strong> or <strong>Public</strong> depending on your preference.</li><li>Click <strong>Create Project</strong>.</li></ul><p>2.<strong> Open the Project in GitLab Web IDE</strong></p><ul><li>After the project is created, press the . (dot) key on your keyboard.</li><li>This shortcut instantly opens the project in the <strong>GitLab Web IDE</strong> (browser-based editor).</li></ul><p>3.<strong> Create the </strong>.gitlab-ci.yml<strong> file</strong></p><ul><li>In the Web IDE, click on New File.</li><li>Name the file exactly .gitlab-ci.yml (note: the filename must start with a dot .).</li><li>Add a very simple pipeline configuration like this</li></ul><pre>stages:<br>  - build<br>  - test<br>  - deploy<br><br>build-job:<br>  stage: build<br>  script:<br>    - echo &quot;Building the application...&quot;<br><br>test-job:<br>  stage: test<br>  script:<br>    - echo &quot;Running tests...&quot;<br><br>deploy-job:<br>  stage: deploy<br>  script:<br>    - echo &quot;Deploying the application...&quot;</pre><p>4.<strong> Commit the Changes.</strong></p><ul><li>After adding the file, make sure to <strong>commit</strong> your changes (Ctrl+Shift+G).</li></ul><h3>Understanding and Breaking Down the .gitlab-ci.yml File</h3><p>Let’s break this down step by step.</p><ol><li><strong>Defining the Pipeline Stages</strong></li></ol><pre>stages:<br>  - build<br>  - test<br>  - deploy</pre><p>This section defines the sequence of stages in pipeline. Each stage represents a phase in development process:​</p><ol><li><strong>Build</strong>: Compiling the application.</li><li><strong>Test</strong>: Running tests to ensure everything works as expected.</li><li><strong>Deploy</strong>: Releasing application to a server or environment.​</li></ol><p>These stages run in the order listed. GitLab ensures that all jobs in the build stage complete successfully before moving on to test, and so on.</p><p>2. <strong>Defining Jobs Within Each Stage</strong></p><p>Jobs are the specific tasks that run within each stage. Each job has a name, is assigned to a stage, and contains a script of commands to execute.</p><p><strong>Build Job</strong></p><pre>build-job:<br>  stage: build<br>  script:<br>    - echo &quot;Building the application...&quot;</pre><ul><li><strong>build-job</strong>: The name of the job.</li><li><strong>stage: build</strong>: Indicates this job runs during the ‘build’ stage.</li><li><strong>script</strong>: Lists the commands to execute; here, it simply prints a message.</li></ul><p><strong>Test Job</strong></p><pre>test-job:<br>  stage: test<br>  script:<br>    - echo &quot;Running tests...&quot;</pre><ul><li><strong>test-job</strong>: The name of the job.</li><li><strong>stage: test</strong>: Indicates this job runs during the ‘test’ stage.</li><li><strong>script</strong>: Prints a message indicating tests are running.</li></ul><p><strong>Deploy Job</strong></p><pre>deploy-job:<br>  stage: deploy<br>  script:<br>    - echo &quot;Deploying the application...&quot;</pre><ul><li><strong>deploy-job</strong>: The name of the job.</li><li><strong>stage: deploy</strong>: Indicates this job runs during the ‘deploy’ stage.</li><li><strong>script</strong>: Prints a message indicating deployment is happening.</li></ul><p><strong>Execution Flow</strong></p><p>When you push changes to your repository:​</p><ol><li><strong>Build Stage</strong>: The build-job runs. If it succeeds, the pipeline proceeds to the next stage.</li><li><strong>Test Stage</strong>: The test-job runs. If it succeeds, the pipeline proceeds to the next stage.</li><li><strong>Deploy Stage</strong>: The deploy-job runs.​</li></ol><p>If any job fails, the pipeline stops, preventing subsequent stages from executing.</p><h3>Viewing and Understanding GitLab Pipeline</h3><ul><li>Once you commit the .gitlab-ci.yml file, it’s time to see pipeline in action!</li><li>Here’s what you need to do:</li></ul><ol><li><strong>Navigate to Pipelines</strong></li></ol><ul><li>Go to your GitLab Project.</li><li>From the sidebar, click <strong>Build → Pipelines</strong>.</li><li>You’ll notice that a pipeline has already been triggered automatically based on your .gitlab-ci.yml file.</li></ul><p>2. <strong>Check the Pipeline Status</strong></p><ul><li>Click on the <strong>pipeline status</strong> (like running or passed) to open the detailed view.</li><li>Here, you’ll see three jobs listed:</li><li><strong>build-job</strong></li><li><strong>test-job</strong></li><li><strong>deploy-job</strong></li><li>Click on the <strong>build-job</strong> first. Inside, you’ll see a lot of logs being printed on the screen. But don’t get overwhelmed — for now, the most important thing to look for is the echo statement we wrote earlier inside the script: Building the application…</li><li>If you see this printed successfully and the job status shows <strong>Job succeeded</strong>, congratulations! Your job ran exactly as we instructed. You can repeat the same by clicking into the test-job and deploy-job as well — each will show their own echo outputs.</li></ul><h3>But Wait… What Are All These Logs?</h3><p>You might notice that apart from echo command, there are a lot of other logs being printed in every job.</p><p>You might wonder:</p><ul><li>Why so many logs?</li><li>What’s actually happening behind the scenes?</li><li>How does GitLab know the pipeline should be executed?</li><li>Who is running all these steps?</li></ul><p>And that’s where <strong>understanding GitLab Architecture</strong> becomes super important. To truly understand how pipelines are executed, and how jobs are handled under the hood, we need to explore the main components of GitLab CI/CD (like GitLab Server and GitLab Runner).</p><h3>GitLab CI/CD Architecture: Server and Runner</h3><ol><li><strong>GitLab Server (The Manager)</strong></li></ol><ul><li>This is the main GitLab platform where our code lives.</li><li>When you push changes, the GitLab server manages the pipeline.</li><li>It decides which jobs need to run, tracks the pipeline progress, and stores the results (like test reports, artifacts, logs, etc).</li><li>Think of the GitLab Server like the project manager — it gives instructions but doesn’t do the work itself.</li></ul><p>2. <strong>GitLab Runner (The Worker)</strong></p><ul><li>The Runner is the real worker that executes the jobs.</li><li>It listens to the GitLab Server, picks up jobs, and actually runs the scripts mentioned in .gitlab-ci.yml.</li><li>It can run on the same machine as GitLab or a separate server.</li><li>Think of the GitLab Runner like the employee who takes the project manager’s instructions and gets the job done.</li></ul><h3>How a GitLab Job Actually Runs</h3><p>So now we know about GitLab Architecture, let’s break it down slowly and step by step.</p><ol><li><strong>Runner is Assigned and Docker Image is Pulled</strong></li></ol><p>When the GitLab server decides that a job needs to be run, it assigns the job to an available Runner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uyXdih1wU7Gp1ChAKy7cjA.png" /></figure><ul><li>In the above screenshot, you can see the runner ID (J2nyww-s) and other system information.</li><li>Then, GitLab Runner uses the Docker Executor (because GitLab Runners use Docker by default).</li><li>Since we didn’t specify any custom image in our .gitlab-ci.yml, GitLab automatically used a default Docker image — in this case, <strong>ruby:3.1</strong>.</li><li>The runner downloads (pulls) this Docker image to prepare the execution environment.</li></ul><p>2. <strong>Fetching the Code from git Repository</strong></p><p>Next, the runner prepares the environment by <strong>fetching the source code</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ko-LzupfJiJlo9Dy95ehxA.png" /></figure><ul><li>It pulls the Git repository.</li><li>Creates a fresh Git repository inside the runner’s file system.</li><li>Checks out the specific commit (in my case, 8824638d) that triggered the pipeline.</li><li>Prepares everything so that the next step can work with the project files.</li></ul><p>3. <strong>Executing the Job Script</strong></p><p>Finally, it’s time to <strong>run the actual instructions</strong> we wrote inside .gitlab-ci.yml:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*loN02rnFpiwwMyaTj9ssQg.png" /></figure><ul><li>The runner uses the Docker image (ruby:3.1).</li><li>Executes the script mentioned in the job — in our case, a simple echo &quot;Building the application...&quot;.</li><li>You can see the echo output, followed by <strong>Job succeeded</strong> if everything goes fine.</li></ul><h3>Wrapping Up the Basics</h3><p>By now, you’ve taken your first real steps into the world of CI/CD using GitLab.</p><p>We explored what CI/CD is, why it’s important, and how it simplifies the development and deployment process. You wrote a basic .gitlab-ci.yml file, triggered pipeline, and even peeked behind the curtain to understand how GitLab&#39;s architecture (Server and Runner) makes everything work.</p><p>You also got to see how logs are generated, how jobs are executed, and how all of this connects together to form an automated development workflow.</p><p>If you’re still processing a few concepts — that’s totally okay! This part was all about building intuition and getting hands-on with the basics.</p><h3>What’s Next?</h3><p>In <strong>Part 2</strong>, we’ll go one step further by:</p><ul><li>Creating a <strong>basic CRUD Flask application</strong></li><li><strong>Dockerizing</strong> the app for consistent deployment</li><li>Building a <strong>complete GitLab CI/CD pipeline</strong> for the app</li><li>Deploying it automatically to an <strong>AWS EC2 instance</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1d28f857e3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Docker Volumes: How to Persist Data in Containers]]></title>
            <link>https://medium.com/@akashchevli888/understanding-docker-volumes-how-to-persist-data-in-containers-6e40494dc171?source=rss-66b1638b797------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e40494dc171</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker-volume]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Akash Chevli]]></dc:creator>
            <pubDate>Wed, 22 Jan 2025 16:52:00 GMT</pubDate>
            <atom:updated>2025-01-22T16:52:00.970Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Why Do We Need Docker Volumes?</strong></p><p>When you first start using Docker, it’s exciting to build applications that run smoothly inside containers. But there’s one important question you need to think about: <strong>What happens to your data when the container removed?</strong></p><p><strong>The Temporary Nature of Containers</strong></p><p>By default, Docker containers are temporary. They are designed to run an application for a short time and then be removed or replaced. When a container is removed, or deleted, all the data inside it is lost.</p><p>This is fine if you’re running a quick process or short-lived tasks, but it’s a problem if your application needs to store data that should remain even if the container is restarted or removed.</p><p><strong>Understanding the Problem: An Example</strong></p><p>Imagine a whiteboard:</p><ul><li>While the whiteboard is in use, you can write and erase as much as you want.</li><li>But when the whiteboard is wiped clean or removed, everything you wrote is gone forever.</li></ul><p>A Docker container works similarly. By default, any data you create or save inside a container will disappear as soon as the container is removed.</p><p>Now, let’s say you’re building an app that saves feedback from users. If the container is restarted, all the feedback users entered would be lost! That’s not ideal, right?</p><p><strong>This is Where Docker Volumes Come Into Play</strong></p><p>Docker Volumes provide a way to store data outside the container, so it doesn’t disappear when the container is removed. Think of volumes as a <strong>notepad</strong> next to the whiteboard. Even if the whiteboard is erased or replaced, the notes you wrote down in your notepad are safe.</p><p><strong>When Do We Need Docker Volumes?</strong></p><p>Before we dive into the different types of Docker volumes, let’s first understand <strong>when</strong> and <strong>why</strong> Docker volumes are essential. Here are a few common scenarios where Docker volumes are crucial:</p><ul><li><strong>Databases</strong>: Applications like <strong>MySQL</strong>, <strong>MongoDB</strong>, or any other database service store important data that must <strong>persist</strong>. Without Docker Volumes, this data would be lost every time the container is restarted or removed. Volumes ensure that database data is safely stored and available even after container changes.</li><li><strong>File Storage</strong>: Many applications, such as content management systems or file-sharing services, allow users to <strong>upload files</strong> (e.g., images, documents, videos). These files need to be stored securely and remain accessible even if the application container is stopped or replaced. Docker Volumes provide a reliable place to store such files, ensuring they aren’t lost when containers are updated or deleted.</li></ul><p><strong>Understand the Problem Without Docker Volumes</strong></p><p>Clone the repository from the GitHub <a href="https://github.com/akashchevli/docker-volumes">repository</a> and follow the blog steps to proceed with the demonstrations and hands-on examples.</p><p>Once you’ve cloned the repository, create two folders at the root directory: feedback and temp. These folders will be used in the upcoming examples. Please ensure they are created before proceeding with the demo.</p><p>Let’s build a simple application where users can create a file with a title and text. When the application runs, it will show two textboxes: one for the title and one for the description. The <strong>title</strong> will be the <strong>filename</strong>, and the <strong>text</strong> will be the content inside that file.</p><p>Now, let’s <strong>Dockerize</strong> this application and understand the issue that Docker Volumes can solve.</p><p><strong>Step 1: Create a Dockerfile</strong></p><p>A <strong>Dockerfile</strong> is a blueprint that tells Docker how to create an image of your application. We’ll start by creating a new Dockerfile in the <strong>root directory</strong> of the project.</p><pre>FROM node:14<br><br>WORKDIR /app<br><br>COPY package.json .<br><br>RUN npm install<br><br>COPY . .<br><br>CMD [&quot;npm&quot;, &quot;start&quot;]</pre><p><strong>What does each line do?</strong></p><ul><li>FROM node:14: This tells Docker to use the <strong>Node.js 14</strong> image as a base for our application.</li><li>WORKDIR /app: This sets the working directory inside the container to /app. This is where our application files will live.</li><li>COPY package.json .: This copies the package.json file from our local machine to the container. This file contains the dependencies for the application.</li><li>RUN npm install: This installs the dependencies listed in the package.json file.</li><li>COPY . .: This copies all files from our local directory into the container’s working directory.</li><li>CMD [&quot;npm&quot;, &quot;start&quot;]: This tells Docker to run npm start to start the application once the container is up and running.</li></ul><p><strong>Step 2: Build the Docker Image</strong></p><p>Now that we’ve created our Dockerfile, we need to <strong>build</strong> the Docker image from it. To do this, run the following command in your terminal:</p><pre>docker build -t feedback-node:volumes .</pre><p><strong>What’s happening here?</strong></p><ul><li>docker build: This command tells Docker to build an image.</li><li>-t feedback-node:volumes: The -t flag tags the image with a name, in this case, feedback-node:volumes. The volumes part is the version or variant of the image.</li><li>.: This tells Docker to look for the Dockerfile in the current directory.</li></ul><p>Once the image is built, Docker will be ready to create a container from it.</p><p><strong>Step 3: Run the Docker Container</strong></p><p>Now that we have our image, let’s run the application inside a container. Use this command to create and start the container:</p><pre>docker run -p 3000:3000 -d --rm --name feedback-app feedback-node:volumes</pre><p><strong>Explanation of the command:</strong></p><ul><li>docker run: This starts a new container from an image.</li><li>-p 3000:3000: This maps <strong>port 3000</strong> on your local machine to <strong>port 3000</strong> inside the container. So, if your application runs on port 3000, you can access it through <a href="http://localhost:3000.">http://localhost:3000.</a></li><li>-d: This runs the container <strong>in the background</strong> (detached mode).</li><li>--rm: This flag ensures the container will be <strong>removed automatically</strong> when stopped, so you don&#39;t have leftover containers cluttering your system.</li><li>--name feedback-app: This gives the container a name — in this case, feedback-app.</li><li>feedback-node:volumes: This specifies the image we just built and named.</li></ul><p>Once the container is running, open your browser and visit http://localhost:3000, where the application will be accessible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*jWb2fzxVlicNB0z-YajOAQ.png" /></figure><p>The webpage will look like the screenshot above. You’ll see two fields: one for the title and one for the text. After filling them in, click the <strong>Save</strong> button.</p><p>To view the text you just saved, you need to manually visit a specific URL.</p><p>The URL will look something like this: http://localhost:3000/feedback/&lt;your-title&gt;</p><ul><li>Replace &lt;your-title&gt; with the title you entered earlier, but make sure it’s all in lowercase.</li><li>Don’t forget to add .txt at the end of the title, like this: <a href="http://localhost:3000/feedback/javascript.txt.">http://localhost:3000/feedback/javascript.txt.</a></li></ul><p>Once you type this into your browser and hit Enter, you’ll see the text you saved earlier. This means the system successfully created a new file with your input. For example, if you entered “JavaScript” as the title and some text, a file named javascript.txt is created, and it contains your text.</p><p>The file you created is stored in the <strong>feedback</strong> directory inside your container’s project structure. That’s why you can see the text when you enter the correct filename in the URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*97YRyaH6DIN6kfe0iHzeqg.png" /></figure><p><strong>Step 4: Stop the Container</strong></p><p>Now, go back to your terminal and stop the container using the following command:</p><pre>docker stop feedback-app</pre><p>When you run this command, the container will stop and also be removed. Why? Because when we started the container earlier, we used the --rm flag, which automatically removes the container when it&#39;s stopped.</p><p>Next, start the container again using the same command you used before to start it. Then, try visiting the same page where you viewed your text earlier.</p><p>This time, you’ll see an error like this: Cannot GET /feedback/&lt;your-title-previously-added&gt;</p><p>What does this mean? It means that when the container was removed, all the data inside it was also lost. So, the file you saved earlier is gone.</p><p>This is a problem because containers are temporary by nature. When they stop, everything inside them disappears. To solve this, Docker provides a solution called <strong>volumes</strong>. Volumes allow you to save your data outside the container, so it doesn’t get lost when the container is removed. <em>This is where Docker Volumes come in.</em></p><p><strong>Understanding Docker Volumes</strong></p><p><strong>Docker Volumes</strong> are like shared folders between your computer (host machine) and Docker containers. These folders are stored on your computer’s hard drive, not inside the container itself.</p><p>Because volumes are stored on the host machine, the data stays safe even if the container is removed or restarted. In other words, the data doesn’t disappear because it’s saved outside the container.</p><p>Containers can use volumes to save data (write) or access existing data (read) as needed. This makes volumes a reliable way to keep your data intact and accessible, no matter what happens to the container.</p><p><strong>Types of Docker Volumes</strong></p><ol><li><strong>Anonymous volumes:</strong> These volumes managed by Docker automatically. As the name suggests, these volumes don’t have a specific name. Instead, Docker gives them a random hash value. These volumes are useful for storing temporary data that doesn’t need to be saved permanently. For example, you might use them for data that can be safely discarded once the container is removed. One important thing to note is that anonymous volumes are not shared between containers. When you remove the container, the volume created for it is also removed from your host machine, meaning the data is lost.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*tA1hmL3aphvuZ9mycYHAiQ.png" /></figure><pre>docker run -p 3000:3000 -v /app/feedback -d --rm --name feedback-app feedback-node:volumes</pre><ul><li>To create an anonymous volume, you simply run a container and specify a volume path inside the container using the -v flag without linking it to a named or host path. Docker will automatically generate a random path for the volume on your host system.</li></ul><p>In the image:</p><ul><li>The <strong>container</strong> stores feedback data at /app/feedback.</li><li>Docker links this to an anonymous volume on your machine.</li><li>Once the container is deleted, the volume and the data inside are also erased.</li></ul><p>2. <strong>Named volumes:</strong> These volumes managed by Docker automatically. Named volumes are a type of storage in Docker that is easy to manage and reuse. Unlike anonymous volumes, named volumes have user-friendly names that you can specify yourself. These volumes are perfect for situations where you need to share data between multiple containers or keep the data even after a container is removed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*YWQF9dyDz2wvS6G4UIquzw.png" /></figure><p>Command to create the named volume:</p><pre>docker run -p 3000:3000 -v feedback:/app/feedback -d --rm --name feedback-app feedback-node:volumes</pre><p>The <strong>-v</strong> option is used to specify a volume for the container. In this case:</p><ul><li>feedback: This is the name of the volume on the host system. If the volume doesn’t exist, Docker will create it automatically.</li><li>/app/feedback: This is the directory inside the container where the volume is mounted.</li></ul><p>In the diagram, the container saves its data in the /app/feedback directory. This directory inside the container is connected to a named volume on the host system, which is specified as feedback in the command. Unlike anonymous volumes, the host system path for named volumes is easy to manage and recognizable, such as /var/lib/docker/volumes/feedback/_data. Here, the volume name feedback ensures the data is persistent and remains available even after the container is removed. You can reuse this volume with other containers, allowing seamless access to previously stored data.</p><p><strong>Viewing the Host Path of a Named Volume</strong></p><p>To locate and confirm the host system path of a named volume, you can use the docker volume inspect command. For example:</p><pre>docker volume inspect feedback</pre><p>This command will display detailed information about the volume, including the host system mount point, like this:</p><pre>[<br>  {<br>    &quot;Name&quot;: &quot;feedback&quot;,<br>    &quot;Driver&quot;: &quot;local&quot;,<br>    &quot;Mountpoint&quot;: &quot;/var/lib/docker/volumes/feedback/_data&quot;,<br>    &quot;Scope&quot;: &quot;local&quot;<br>  }<br>]</pre><p>3. <strong>Bind Mount:</strong> These volumes are managed by the user. A bind mount maps a directory or file from the host machine into a container. Any changes made to the files or directories on the host machine are immediately visible in the running container, and changes made inside the container are reflected back on the host machine. Bind mounts are particularly useful during the development phase, as they allow live changes to reflect inside the container without the need to rebuild the image.</p><p>Let’s use a <strong>Bind Mount</strong> for live updates. If you have a container already running, you can stop or remove it before proceeding with the new setup.</p><p>Here’s the command:</p><pre>docker run -d -p 3000:3000 --name feedback-app -v feedback:/app/feedback -v &quot;&lt;your/project/folder/path&gt;:/app&quot; feedback-node:volumes</pre><p>Explanation of the -v Options:</p><ol><li>-v feedback:/app/feedback: This is a named volume that ensures data persistence.</li><li>-v &quot;&lt;your/project/folder/path&gt;:/app&quot;: This is a bind mount. It maps the specified folder on your host machine (&lt;your/project/folder/path&gt;) to the /app directory inside the container. This bind mount enables live updates during development, as any changes you make to your project files on the host will instantly reflect inside the container. Replace &lt;your/project/folder/path&gt; with the actual path to your project folder to ensure the mapping works correctly.</li></ol><p>If you open your browser and visit the localhost URL, you might notice that nothing loads. This usually happens because your container has stopped unexpectedly. To investigate, check the logs of the container using the command:</p><pre>docker logs feedback-app</pre><p>In the logs, you may find an error message like:<br><strong>“Local package.json exists, but node_modules missing. Did you mean to install?”</strong></p><p>This error occurs only if your host system doesn’t have the node_modules directory. If node_modules exists on your host machine, the container would work fine because the bind mount shares the existing dependencies with the container.</p><p>The issue arises because the bind mount (-v &lt;your/project/folder/path&gt;:/app) replaces the container&#39;s /app directory with the project folder from your host machine. When this happens, the node_modules folder that was originally copied into the container (via the COPY command in the Dockerfile) is no longer accessible, as it gets overridden by the host&#39;s directory.</p><p>To fix this issue, we need to ensure that Docker doesn’t override certain directories in the container when changes occur on the host system. In our case, this applies to the node_modules directory. The solution typically involves creating a separate volume or an anonymous volume specifically for node_modules.</p><p>Here’s the command:</p><pre>docker run -d -p 3000:3000 --name feedback-app -v feedback:/app/feedback -v &quot;&lt;your/project/folder/path&gt;:/app&quot; -v /app/node_modules feedback-node:volumes</pre><p>In the docker run command, the last -v option:</p><p>This creates an <strong>anonymous volume</strong> for the node_modules directory inside the container. Here&#39;s how it works:</p><ul><li><strong>Anonymous Volume:</strong> This means Docker automatically creates and manages a volume for /app/node_modules. It ensures that the dependencies inside the container are isolated and not overwritten by anything from the host system.</li><li><strong>Why Docker Picks This</strong>: Docker will always choose the <strong>longest path</strong> when there are multiple volume mounts. In this case, /app/node_modules is the longest path, so Docker treats it as a specific volume mount and creates the anonymous volume there. This ensures that the container’s node_modules directory is handled separately and remains consistent.</li></ul><p>Now, any changes you make inside the container will reflect in the app, but the node_modules directory remains persistent and unaffected by the host system.</p><p><strong>Volumes &amp; Bind Mounts — Quick Overview</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0df4b88df9cf93f3551636ef78e53146/href">https://medium.com/media/0df4b88df9cf93f3551636ef78e53146/href</a></iframe><p><strong>Advantages of Using Docker Volumes</strong></p><p><strong>1. Keep Your Data Safe and Persistent</strong><br>Docker volumes ensure your data doesn’t vanish when containers are stopped or removed. Whether it’s user uploads or a database, your data is stored securely and remains accessible.</p><p><strong>2. Share Data Between Containers</strong><br>Named volumes make it easy to share data across multiple containers. For example, two containers can access the same database or shared files effortlessly.</p><p><strong>3. Faster Development with Live Updates</strong><br>Bind mounts let you see changes in real-time during development without rebuilding the image. This speeds up testing and debugging significantly.</p><p><strong>4. Simplified Management</strong><br>Named volumes are managed by Docker, making them easy to set up, inspect, and maintain without worrying about manual configuration.</p><h3>Conclusion</h3><p>Docker volumes help keep your data safe and accessible, even if you stop or remove containers. They make it easier to share data between containers and speed up development, so you don’t have to worry about losing important information. Volumes are a simple and reliable way to manage your app’s data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e40494dc171" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Essentials: Building and Managing Containers]]></title>
            <link>https://medium.com/@akashchevli888/docker-essentials-building-and-managing-containers-396ab603b1a5?source=rss-66b1638b797------2</link>
            <guid isPermaLink="false">https://medium.com/p/396ab603b1a5</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Akash Chevli]]></dc:creator>
            <pubDate>Thu, 31 Oct 2024 16:47:49 GMT</pubDate>
            <atom:updated>2024-10-31T16:50:59.665Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is Docker?</strong></p><p>Docker is a containerization tool that allows developers to build, test, and deploy applications quickly. With Docker, you define the application and its dependencies in a <strong>Dockerfile</strong>, which is then used to build a <strong>Docker image</strong>. This image defines a <strong>Docker container</strong>. By using containers, you can ensure that your application will run consistently in any environment.</p><h4>An analogy:</h4><p>Imagine you’re a foodie who prefers homemade meals. If you plan to travel to a new city, you might pack all your food in a box to carry with you. Whenever you’re hungry, you simply unpack the food and eat.</p><ul><li><strong>Food</strong> = Dependencies (libraries, environment configurations, etc.)</li><li><strong>Box</strong> = Container</li><li><strong>Eating Anywhere</strong> = Running your app on any platform without having to worry about setting up the environment.</li></ul><p>Just as the box allows you to carry your homemade food wherever you go and enjoy it without worrying about local cuisine, Docker containers let you carry your application and its dependencies wherever it runs, ensuring everything works smoothly.</p><p><strong>Why use Docker and these so called “containers”?</strong></p><p>Containers are incredibly useful because they are lightweight and require minimal setup. You can package your application along with all its dependencies and isolate it within a container. These containers can then be run on any platform that has the Docker engine installed.</p><p><strong>Containers have some great benefits:</strong></p><ul><li>They don’t take up much space.</li><li>They keep everything organized, so your app doesn’t interfere with other things on the computer.</li><li>They make sure your app is safe and protected from other apps.</li><li>They allow you to easily move your app from one machine to another without having to set it up all over again.</li></ul><p>The boxes (containers) you create and send around are called <strong>Docker images. </strong>More accurately, an image is a snapshot of a file system along with a command to start the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*ucjny3kt7v8FK4c7v5qKvg.png" /></figure><p>Here, A <strong>Docker Image</strong> is like a snapshot of a tiny computer that has everything it needs to run your app.</p><p>It includes:</p><ol><li><strong>File Systsem:</strong> This is where the important folders and files are kept, kind of like organized folders that hold everything your app needs, like packages and settings.</li><li><strong>Applications:</strong> Inside this system, there’s a Python environment set up, so your app can run easily. Think of it as having Python already installed and ready to go.</li><li><strong>Startup Command:</strong> This is the action that happens when the container (your tiny computer) starts. In this case, it’s like typing python app.pyin a terminal to launch your Python application. When you run this command, the app inside the image gets activated.</li></ol><p><strong>What are the “containers” and “VMs”?</strong></p><p>Containers and Virtual Machines (VMs) both do the same thing: they package up an app and everything it needs so it can run anywhere, without worrying about what’s on the computer.</p><p>Containers and VMs remove the need for physical hardware, allowing for more effcient use of computing resource.</p><p>The main difference between containers and VMs is in their architectural approach.</p><p><strong>Here’s the big difference:</strong></p><p><strong>VMs (Virtual Machines):</strong> Think of a VM as a complete computer nestled within your computer. It has its own operating system, like Windows or Linux, and it runs the app. This makes it big and heavy because it needs its own OS, but it’s like having a fully separate computer.</p><p><strong>Containers:</strong> A container is much lighter. Instead of having its own full operating system, it shares the one your computer already has. It still keeps the app and its stuff separate, but it’s smaller and faster because it doesn’t need an entire OS.</p><p>Let’s look at this diagrammatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*CtdHHakNJMNzExxMsNNSZA.png" /></figure><p>As we can see here, in the case of a docker container, only the required application along with it’s dependencies are bundled up into an image. While in the case of a VM, we have the heavy overhead of an entire Operating System associated with every image!</p><p><strong>What are containers?</strong></p><p>A <strong>container</strong> is like a <strong>mini-computer</strong> inside your computer.</p><ul><li>It has its own little <strong>CPU</strong>, <strong>storage</strong>, <strong>RAM</strong>, n<strong>etwork, etc</strong>.</li><li>It runs completely by itself, without needing to affect the rest of your computer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*dXHW6A7TQJ_MHPMziNCqwQ.png" /></figure><p>Portion/Box; When you put your app and everything it needs (like libraries and tools) into a container, it can run <strong>anywhere</strong>. Whether on your laptop, a server, or in the cloud, it works exactly the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*iIJzH8qzH4GusrxIEimjLQ.png" /></figure><p><strong>Docker Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*zYXCni1RBsERchHKYNjOBA.png" /></figure><p>Docker uses a client-server setup, meaning it has two main parts: the Docker client and the Docker daemon.</p><p><strong>Docker Deamon</strong></p><p>The daemon is like the “engine” behind Docker. It listens for commands sent by the Docker client and does the actual work of building, running, and managing Docker objects like images (templates for containers), containers (instances of images), networks, and storage volumes.</p><p><strong>Docker Client</strong></p><p>The client is the main tool you use to talk to Docker. When you type a Docker command in your terminal (like docker run), the client sends that command to the daemon, which then makes it happen. One cool thing about the client is that it can connect to multiple daemons, meaning it can manage Docker setups on different servers.</p><p><strong>Docker Registries</strong></p><p>Docker registries are like online libraries where Docker images are stored. Docker Hub, a popular public registry, is the default place where Docker looks for images. When you pull an image (download it), Docker automatically checks Docker Hub unless you specify a different source. You can save these images locally on your machine or share (push) them to a registry for others to use.</p><p><strong>Dockerfile</strong></p><p>Dockerfile is a file where you provide steps to build your Docker Image.</p><p><strong>Docker Image</strong></p><p>A Docker image is like a blueprint or a template for creating Docker containers. Think of it as a recipe for the software you want to run. Often, you start by building an image based on an existing one, which comes with the necessary software and system libraries to support your application. Then, you add your own instructions in a file called a Dockerfile to set up and run the full application.</p><p>Docker images are built in <strong>layers</strong>, where each command in the Dockerfile (like FROM, COPY, or RUN) adds a new layer on top of the previous one. This layering brings efficiency: if you make a change to the Dockerfile, Docker only rebuilds the changed layers, not the entire image. It also means common base layers (such as python:3.10) can be reused across different images, saving time and storage space.</p><p>When you run the Dockerfile, Docker follows the instructions to build these layers into a complete image. This image can then be used by one or more containers to launch the app. In other words, a Docker image is like a reusable template made of layers, while a container is the “working unit” or active instance of that image, where the app actually runs. This layered structure makes Docker images efficient, reusable, and easy to maintain.</p><p><strong>Understanding the Read-Only Nature of Docker Images</strong></p><p>Docker images are like finished blueprints that you can’t change once they’re made. When you build a Docker image, it gets locked in, meaning it can’t be altered directly. This is great because it ensures that every time you use the image, it stays the same. So, whether you run one container or many from the same image, you can always expect it to behave consistently and securely.</p><p>When you start a container from an image, Docker creates a special top layer called a <em>writable layer</em>. This writable layer is where any changes happen while the container is running. For example, if you add a file or change some settings, those changes are saved in this top layer, but the original image remains unchanged underneath.</p><p>This setup means that even if several containers are running from the same image, they won’t interfere with each other. Each one can make its own changes in its writable layer without affecting the others or the original image. It keeps everything organized and reliable!</p><p><strong>Read-Only Image and Read-Write Container Layout Diagram</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ehIIlmsAjzwG2ftddpvWw.png" /></figure><p>Let’s dockerize the NodeJs Application.</p><p>For download and installation refer: <a href="https://docs.docker.com/">https://docs.docker.com</a></p><ul><li>Clone the repository from <a href="https://github.com/akashchevli/nodejs-app-dockerize">here</a>.</li></ul><p>If you wish to run an application in your local environment, then follow the instructions below.</p><ul><li>Ensure Node.js version 14 or above is installed.</li><li>Run npm install to install the required packages.</li><li>Start the application using the node server.jscommand.</li><li>Open your browser and type http://localhost:3000 to view the web page.</li></ul><p>Now, create a new file named Dockerfile in the project root directory. Add the lines below to the Dockerfile. I&#39;ll explain the purpose of each line in detail.</p><pre>FROM node<br><br>WORKDIR /app<br><br>COPY package.json /app<br><br>RUN npm install<br><br>COPY . /app <br><br>CMD [&quot;node&quot;, &quot;server.js&quot;]</pre><p><strong>Explanation of the Dockerfile</strong></p><ol><li><strong>FROM node</strong>: This line tells Docker to use the official Node.js image as the starting point. Think of it as starting your recipe with a pre-made base that already has Node.js installed.</li><li><strong>WORKDIR /app</strong>: This line sets the working directory inside the container to /app. It’s like telling Docker, “All my work will happen in this folder.”</li><li><strong>COPY package.json /app</strong>: This command copies only the package.json file from your current directory on your computer (host machine) into the /app folder inside the container. This is important because it allows Docker to install the necessary dependencies specified in package.json before copying the rest of your application files.</li><li><strong>RUN npm install</strong>: This line runs the command npm install, which installs all the necessary packages and dependencies defined in your package.json file. Since the package.json has already been copied, Docker can install the required packages at this stage.</li><li><strong>COPY . /app</strong>: This command copies all the remaining files from your current directory on your computer (host machine) into the /app folder inside the container. This ensures that your application code and any other necessary files are included after the dependencies are installed.</li><li><strong>CMD [“node”, “server.js”]</strong>: This line tells Docker what command to run when the container starts. In this case, it runs node server.js, which starts your Node.js application.</li></ol><p>We’re ready with our Dockerfile, Now let’s create a docker image.</p><p><strong>Building the Docker Image</strong></p><p>To create your Docker image from the Dockerfile, you use the following command:</p><pre>docker build -t my-node-app .</pre><p><strong>docker build</strong>: This command tells Docker to create an image based on the instructions found in the Dockerfile.</p><p><strong>-t my-node-app</strong>: This option tags the image with a name, “my-node-app.” This makes it easier to reference your image later when you want to run it or manage it. The -t stands for &quot;tag.&quot;</p><p><strong>.</strong>: The dot at the end specifies the current directory as the context for the build. This means Docker will look for the Dockerfile in the current folder.</p><p><strong>Listing Docker Images</strong></p><p>To see all the Docker images that you have on your system, use the following command:</p><pre>docker images</pre><p><strong>docker images</strong>: This command lists all the Docker images available on your local machine. The output includes details such as the repository name, tag, image ID, and the size of each image. This helps you verify which images you have built or pulled from a registry.</p><p><strong>Running the Docker Image</strong></p><p>Once the image is built, you can start a container from that image using this command:</p><pre>docker run -p 3000:3000 my-node-app</pre><p><strong>docker run</strong>: This command tells Docker to create a new container from the specified image and start it.</p><p><strong>-p 3000:3000</strong>:</p><ul><li>This option maps port 3000 on your computer (the host machine) to port 3000 inside the Docker container. This means that any requests made to http://localhost:3000 on your computer will be forwarded to the container, allowing you to access your Node.js application running inside it. In this mapping, the first 3000 refers to the port on your host, while the second 3000 corresponds to the port within the container.</li><li>Why is this important? By default, Docker containers are isolated and do not listen to incoming requests from the outside world. They only handle internal communication. Therefore, without this port mapping, your application running inside the container would be unreachable from your computer. Mapping the ports ensures that requests sent to your computer’s port 3000 are directed to the correct port in the container, making your application accessible and allowing you to interact with it as if it were running directly on your machine.</li></ul><p><strong>my-node-app</strong>: This is the name of the image you just built. Docker uses this name to find the correct image to run.</p><p>Your application is running on port 3000. Now, if you navigate to the URL http://localhost:3000, you will see that the application is up and running.</p><p><strong>Listing Docker Containers</strong></p><p>To see all the containers running on your system, use this command:</p><pre>docker ps</pre><p><strong>docker ps</strong>: This command displays a list of currently running containers. The output includes information like the container ID, image name, command being run, creation time, status, ports, and names of the containers.</p><p>If you want to see all containers, including those that are stopped, you can use the -a (or --all) option:</p><pre>docker ps -a</pre><ul><li><strong>docker ps -a</strong>: This command lists all containers, regardless of their status (running or stopped). This is useful for checking the status of all containers you’ve created, not just the ones currently active.</li></ul><p><strong>Key Docker Commands</strong></p><p>For a full list of all commands, add — help after a command — e.g. docker — help , docker run — help etc.</p><ul><li><strong>docker build .</strong>: Build a Dockerfile and create your own image based on the file.<br>1. <strong>-t NAME:TAG</strong>: Assign a NAME and a TAG to the image.</li><li><strong>docker run IMAGE_NAME</strong> : Create and start a new container based on image IMAGENAME (or use the image id).<br>1. <strong>— name NAME</strong> : Assign a NAME to the container. The name can be used for stopping and removing etc.<br>2. <strong>-d</strong> : Run the container in <strong>detached</strong> mode — i.e. output printed by the container is not visible, the command prompt / terminal does NOT wait for the container to stop.<br>3. -it : Run the container in “<strong>interactive</strong>” mode — the container / application is then prepared to receive input via the command prompt / terminal. You can stop the container with CTRL + C when using the -it flag.<br>4. — rm : Automatically <strong>remove</strong> the container when it’s stopped.</li><li><strong>docker ps</strong> : List all running containers.<br>1. <strong>-a</strong> : <strong>List</strong> all <strong>containers</strong> — including <strong>stopped</strong> ones.</li><li><strong>docker images</strong> : <strong>List</strong> all <strong>locally</strong> <strong>stored</strong> <strong>images.</strong></li><li><strong>docker rm CONTAINER</strong> : <strong>Remove</strong> a container with name CONTAINER (you can also use the container id).</li><li><strong>docker rmi IMAGE</strong> : <strong>Remove</strong> an image by name / id.</li><li><strong>docker container prune</strong> : <strong>Remove</strong> all <strong>stopped</strong> containers.</li><li><strong>docker image prune</strong> : <strong>Remove</strong> all <strong>dangling</strong> images (untagged images).<br>1. <strong>-a</strong> : <strong>Remove</strong> all <strong>locally</strong> <strong>stored</strong> images.</li></ul><p><strong>Conclusion</strong></p><p>In this blog, we covered the basics of Docker, including its architecture, the role of images and containers, and how to build and tag your own images. Docker simplifies application deployment and ensures consistency across different environments. As you explore Docker further, you’ll discover how it can streamline your development process and enhance collaboration. Happy Dockering!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=396ab603b1a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CORS Errors: Preventing and Troubleshooting]]></title>
            <link>https://medium.com/@akashchevli888/cors-errors-preventing-and-troubleshooting-6acca5d56bc6?source=rss-66b1638b797------2</link>
            <guid isPermaLink="false">https://medium.com/p/6acca5d56bc6</guid>
            <category><![CDATA[cors]]></category>
            <category><![CDATA[domains]]></category>
            <category><![CDATA[nginx]]></category>
            <dc:creator><![CDATA[Akash Chevli]]></dc:creator>
            <pubDate>Sat, 08 Jun 2024 07:21:20 GMT</pubDate>
            <atom:updated>2024-07-05T10:31:44.899Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is CORS?</strong></p><p>Cross-Origin Resource Sharing (CORS) is a security feature that restricts web pages from making requests to a different domain than the one that served the web page. This helps prevent unauthorized access and cross-site scripting (XSS) attacks.</p><p>Before CORS, the “same-origin-policy” allowed web pages to request resource only from the same domain. This policy protected against malicious websites making unauthorized requests to other domains, which could expose sensitive data or compromise security.</p><p>But, modern web applications often need to access resources from different domains, such as APIs, images, or stylesheets. CORS allows this by letting developers specify which domains can access their resource and what types of requests are allowed.</p><p>Properly configuring CORS lets developers securely allow cross-origin requests, ensuring only authorized domains can access sensitive data while maintaining web security.</p><p><strong>What are CORS Errors?</strong></p><p>A CORS error occurs when a web application running on one domain tries to make a request for a resource to another domain, and the server hosting the resource does not permit such cross-origin request.</p><p><strong>Example of CORS for Simplification</strong></p><p>Imagine you have a web application hosted at https://web.myapp.com . This application needs to fetch data from an API hosted at https://api.example.com .</p><p>Without CORS, it’s like trying to enter a secure office building without proper identification. The security guard (the browser) would block the entry because the office building (https://api.example.com) is different from your home (https://web.myapp.com). The response of the request will be the CORS error, hence response is failed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*KOJIgAIID-f9_si3IDreyQ.png" /></figure><p>To solve this issue, CORS allows the server at https://api.example.com to grant permission by sending a response header like this:</p><blockquote>Access-Control-Allow-Origin: https://web.myapp.com</blockquote><p>So, when you request https://api.example.com again, the domain will send the headers in the response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*xcKKxnkFBkx1VdshMSbaVQ.png" /></figure><p>This way, CORS ensures that only trusted domains can access resources, similar to how only individuals with the correct access badge can enter a secure office building, thereby enhancing security.</p><p><strong>How to Solve CORS Errors</strong></p><p>If your website is having trouble with CORS errors, there are a few ways to solve them. It depends on why the error is happening and what your website needs.</p><p><strong>Allow Cross-Origin Requests on Server:</strong></p><ul><li>Determine if the server (Nginx or Apache) is blocking requests due to CORS configurations not allowing the Origin header.</li><li>Adjust the server’s (Nginx or Apache) CORS settings to enable cross-origin requests.</li><li>Add the Access-Control-Allow-Origin header in the server’s (Nginx or Apache) configuration to specify which domains can access the resource. You can set it to the specific requesting domain (e.g., https://web.myapp.com`) or use “*” (which is not good for security reasons, as it allows access from any domain).</li><li>For our previous example, where our website https://web.myapp.com requests access to API response, the server at https://api.example.com could send the following response:</li><li><strong>Access-Control-Allow-Origin: https://web.myapp.com</strong></li></ul><p><strong>Allow HTTP Methods:</strong></p><ul><li>Use the Access-Control-Allow-Methods header to specify which HTTP methods are permitted in cross-origin requests. For example, to allow GET and POST methods:</li><li><strong>Access-Control-Allow-Methods: GET,POST always;</strong></li><li>You can also use “*” to allow all methods, but it can make your server less secure.</li></ul><p><strong>Allow Necessary HTTP Headers</strong>:</p><ul><li>Use the Access-Control-Allow-Headers header to specify which HTTP headers are allowed in cross-origin requests. For example:</li><li><strong>Access-Control-Allow-Headers: Content-Type,Authorization,Cache-Control always;</strong></li></ul><p>By following these steps, you can successfully resolve CORS errors and ensure seamless communication between your web application and external domains.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6acca5d56bc6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>