<?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 shivatech on Medium]]></title>
        <description><![CDATA[Stories by shivatech on Medium]]></description>
        <link>https://medium.com/@shivasingh.1dev?source=rss-ae6be363234d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JJCVpPt8sLTAH9_A</url>
            <title>Stories by shivatech on Medium</title>
            <link>https://medium.com/@shivasingh.1dev?source=rss-ae6be363234d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:18:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shivasingh.1dev/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[From Laptop to Production Understanding Kubernetes, Kind, Minikube, EKS, and Karpenter]]></title>
            <link>https://medium.com/@shivasingh.1dev/from-laptop-to-production-understanding-kubernetes-kind-minikube-eks-and-karpenter-eceeb78c0880?source=rss-ae6be363234d------2</link>
            <guid isPermaLink="false">https://medium.com/p/eceeb78c0880</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[shivatech]]></dc:creator>
            <pubDate>Sun, 29 Nov 2026 12:27:51 GMT</pubDate>
            <atom:updated>2026-11-29T12:27:51.631Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve started learning Kubernetes, you’ve probably come across names like Kind, Minikube, Kubeadm, Amazon EKS and Karpenter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTBw11-WeEt10IQ3381SEQ.jpeg" /></figure><p>At first, all of them can feel like different versions of Kubernetes. You might even wonder:</p><ul><li>If Kubernetes is already available, why do we need Kind or Minikube?</li><li>What exactly is Kubeadm?</li><li>Why do companies use Amazon EKS instead of setting up Kubernetes themselves?</li><li>What is Karpenter, and how is it different from Kubernetes autoscaling?</li><li>Which approach should I use for learning, development, testing or production?</li><li>And most importantly, how much does all of this cost?</li></ul><p>These are questions I had while learning Kubernetes, and I think understanding the differences between these tools makes Kubernetes much easier to work with.</p><p>So, instead of learning each tool in isolation, let’s understand how they fit into the bigger picture.</p><p>We’ll start with Kubernetes fundamentals, explore the different ways to run a Kubernetes cluster, understand how AWS EKS works, and finally see how Karpenter helps Kubernetes scale its infrastructure.</p><h3>1. What Is Kubernetes?</h3><p>Imagine you’re running an online shopping platform.</p><p>Initially, your application might consist of a frontend, a backend API and a database. You deploy everything on a single server, and things work perfectly. But eventually, more users start visiting your application.</p><p>Your backend starts receiving more requests. Some services become slow. A server might crash. You may need additional servers to handle the traffic.</p><p>Now you have to manage multiple servers, deploy applications across them, monitor their health, replace failed applications, handle networking and make sure everything works together.</p><p>Doing all of this manually quickly becomes difficult.</p><p>That’s where Kubernetes comes in.</p><p><strong>Kubernetes is an open-source container orchestration platform that helps you deploy, manage, scale and maintain containerized applications across a cluster of machines.</strong></p><p>Instead of manually managing every container and server, Kubernetes allows you to describe what you want your infrastructure and applications to look like.</p><p>Kubernetes continuously tries to make the actual state of your cluster match the desired state you’ve defined.</p><p>For example, you might tell Kubernetes:</p><ul><li>I want 3 replicas of my backend application.</li><li>My application should be accessible through a Service.</li><li>If a container crashes, it should be restarted.</li><li>If a machine becomes unavailable, workloads should be rescheduled where possible.</li></ul><p>Kubernetes takes care of continuously working toward that desired state.</p><h3>A simple real-world analogy</h3><p>Imagine a restaurant with multiple kitchens, chefs, orders and staff.</p><p>You don’t want to manually assign every order, monitor every chef and figure out what happens when someone is unavailable.</p><p>Instead, you have a restaurant manager who:</p><ul><li>Assigns work.</li><li>Makes sure enough staff are available.</li><li>Reassigns work when someone is unavailable.</li><li>Coordinates different teams.</li><li>Ensures the restaurant continues operating.</li></ul><p>Kubernetes works somewhat like that manager, but for containerized workloads and infrastructure.</p><p>It’s not just a container runner. It’s an orchestration system.</p><h3>2. Kubernetes Architecture — A Quick Overview</h3><p>Before we discuss Kind, Minikube, Kubeadm, EKS and Karpenter, let’s understand what a Kubernetes cluster actually consists of.</p><p>A Kubernetes cluster generally has two major components:</p><ul><li>Control Plane</li><li>Worker Nodes</li></ul><p>The Control Plane manages and coordinates the cluster, while Worker Nodes run our application workloads.</p><h3>Kubernetes Architecture</h3><p>Note: This is a simplified conceptual diagram. Components communicate through the API Server, and the diagram doesn’t represent every internal communication path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-fDO2st7ROzhCrhzXB3xA.png" /></figure><h3>What does each component do?</h3><h4>— API Server</h4><p>The API Server is the entry point for Kubernetes.</p><p>When you run commands such as:</p><pre>kubectl get pods<br>kubectl apply -f deployment.yaml<br>kubectl get nodes</pre><p>kubectl communicates with the Kubernetes API Server.</p><h4>— Etcd</h4><p>etcd is a distributed key-value store that stores Kubernetes cluster state and configuration data.</p><p>Think of it as the cluster’s state store. It holds information Kubernetes needs to understand what has been configured and recorded about the cluster.</p><h4>— Scheduler</h4><p>The Scheduler decides which Worker Node should run a newly created Pod.</p><p>It considers things such as available resources, constraints, scheduling rules and other relevant conditions.</p><h4>— Controller Manager</h4><p>Controllers continuously observe the cluster and try to make the actual state match the desired state.</p><p>For example, if a Deployment requires three Pods but only two are available, the relevant controllers work toward restoring the desired number.</p><h4>— Worker Nodes</h4><p>Worker Nodes are the machines where your application workloads run.</p><p>These can be virtual machines, cloud instances or other supported compute environments.</p><h4>— Kubelet</h4><p>Kubelet is the node agent that communicates with the Kubernetes API and helps ensure the Pods assigned to that node are running as expected.</p><h4>— Container Runtime</h4><p>The container runtime is responsible for running containers. Containerd is a common example.</p><h4>— Pods</h4><p>Pods are the smallest deployable units in Kubernetes. They contain one or more containers that share certain resources, such as networking.</p><p>For most application workloads, we don’t directly manage individual Pods. We use Deployments, StatefulSets, Jobs and other Kubernetes objects to manage them.</p><h3>3. But How Do We Actually Run Kubernetes?</h3><p>Now that we understand the basic architecture, let’s get to the interesting part.</p><p>Kubernetes itself doesn’t require you to use AWS, Docker Desktop, Minikube or any particular cloud provider.</p><p>However, you need an environment where its components can run.</p><p>Depending on your requirements, you can:</p><ul><li>Run Kubernetes locally on your laptop.</li><li>Create a local cluster using Kind.</li><li>Use Minikube for local development.</li><li>Build your own cluster using Kubeadm on virtual machines.</li><li>Use a managed Kubernetes service such as Amazon EKS.</li></ul><p>These options aren’t competing Kubernetes versions. They are different ways of creating, running or managing Kubernetes clusters.</p><p>Let’s understand each of them.</p><h3>4. Kind — Kubernetes in Docker</h3><p>Kind stands for Kubernetes IN Docker.</p><p>Kind allows you to run Kubernetes clusters using Docker containers as the cluster nodes.</p><p>Instead of provisioning actual virtual machines or cloud servers, Kind creates containers that behave as Kubernetes nodes.</p><p>It’s primarily designed for local development, testing and CI workflows.</p><h3>How does Kind work?</h3><p>Suppose you want to experiment with Kubernetes on your laptop.</p><p>You don’t want to create multiple EC2 instances, configure networking, install Kubernetes components and pay for cloud infrastructure just to test a Deployment.</p><p>Kind makes this easier.</p><p>It creates Kubernetes nodes inside Docker containers, allowing you to run a cluster locally.</p><h3>Kind Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kATlaOoaCRDS57YaKTdpQw.png" /></figure><p>In this simplified diagram, each container represents a Kubernetes node. The Control Plane node also runs the control-plane components.</p><p>The interesting thing is that these node containers themselves run Kubernetes components.</p><p>So, you are running a Kubernetes cluster inside Docker-managed containers, not simply running your application inside a single Docker container.</p><h3>Installing Kind</h3><p>You’ll generally need:</p><ul><li>Docker</li><li>kubectl</li><li>Kind</li></ul><p>For example, on Windows, you can use WSL2 with Docker Desktop or another supported Docker setup.</p><p>On Linux, install Docker, kubectl and Kind using their official installation instructions.</p><p>Once installed, creating a cluster is very simple.</p><h3>Create a Kind cluster</h3><p>If you want to create a kind cluster. Then go to my github repo where you get to know everything how do we create Kind cluster and. I have also setup a Automation file for you. If you’re automation guy jss like me hahhaha thank me later….</p><p>🏴‍☠️ <a href="https://github.com/LondheShubham153/kubestarter/tree/main/kind-cluster">Github Repo</a></p><p>Automation file&gt;&gt;</p><pre>#!/bin/bash</pre><pre>set -e  # Exit immediately if a command exits with a non-zero status<br>set -o pipefail</pre><pre>echo &quot;🚀 Starting installation of Docker, Kind, and kubectl...&quot;</pre><pre># ----------------------------<br># 1. Install Docker<br># ----------------------------<br>if ! command -v docker &amp;&gt;/dev/null; then<br>  echo &quot;📦 Installing Docker...&quot;<br>  sudo apt-get update -y<br>  sudo apt-get install -y docker.io</pre><pre>  echo &quot;👤 Adding current user to docker group...&quot;<br>  sudo usermod -aG docker &quot;$USER&quot;</pre><pre>  echo &quot;✅ Docker installed and user added to docker group.&quot;<br>else<br>  echo &quot;✅ Docker is already installed.&quot;<br>fi</pre><pre># ----------------------------<br># 2. Install Kind (based on architecture)<br># ----------------------------<br>if ! command -v kind &amp;&gt;/dev/null; then<br>  echo &quot;📦 Installing Kind...&quot;</pre><pre>  ARCH=$(uname -m)<br>  if [ &quot;$ARCH&quot; = &quot;x86_64&quot; ]; then<br>    curl -Lo ./kind <a href="https://kind.sigs.k8s.io/dl/v0.29.0/kind-linux-amd64">https://kind.sigs.k8s.io/dl/v0.29.0/kind-linux-amd64</a><br>  elif [ &quot;$ARCH&quot; = &quot;aarch64&quot; ]; then<br>    curl -Lo ./kind <a href="https://kind.sigs.k8s.io/dl/v0.29.0/kind-linux-arm64">https://kind.sigs.k8s.io/dl/v0.29.0/kind-linux-arm64</a><br>  else<br>    echo &quot;❌ Unsupported architecture: $ARCH&quot;<br>    exit 1<br>  fi</pre><pre>  chmod +x ./kind<br>  sudo mv ./kind /usr/local/bin/kind<br>  echo &quot;✅ Kind installed successfully.&quot;<br>else<br>  echo &quot;✅ Kind is already installed.&quot;<br>fi</pre><pre># ----------------------------<br># 3. Install kubectl (based on architecture)<br># ----------------------------<br>if ! command -v kubectl &amp;&gt;/dev/null; then<br>  echo &quot;📦 Installing kubectl (latest stable version)...&quot;</pre><pre>  ARCH=$(uname -m)<br>  VERSION=$(curl -Ls <a href="https://dl.k8s.io/release/stable.txt)">https://dl.k8s.io/release/stable.txt)</a></pre><pre>  if [ &quot;$ARCH&quot; = &quot;x86_64&quot; ]; then<br>    curl -Lo ./kubectl &quot;https://dl.k8s.io/release/${VERSION}/bin/linux/amd64/kubectl&quot;<br>  elif [ &quot;$ARCH&quot; = &quot;aarch64&quot; ] || [ &quot;$ARCH&quot; = &quot;arm64&quot; ]; then<br>    curl -Lo ./kubectl &quot;https://dl.k8s.io/release/${VERSION}/bin/linux/arm64/kubectl&quot;<br>  else<br>    echo &quot;❌ Unsupported architecture: $ARCH&quot;<br>    exit 1<br>  fi</pre><pre>  chmod +x ./kubectl<br>  sudo mv ./kubectl /usr/local/bin/kubectl<br>  echo &quot;✅ kubectl installed successfully.&quot;<br>else<br>  echo &quot;✅ kubectl is already installed.&quot;<br>fi</pre><pre># ----------------------------<br># 4. Confirm Versions<br># ----------------------------<br>echo<br>echo &quot;🔍 Installed Versions:&quot;<br>docker --version<br>kind --version<br>kubectl version --client --output=yaml</pre><pre>echo<br>echo &quot;🎉 Docker, Kind, and kubectl installation complete!&quot;</pre><h3>Why do developers use Kind?</h3><p>Kind is useful when you want to:</p><ul><li>Learn Kubernetes.</li><li>Test Kubernetes manifests.</li><li>Test Helm charts.</li><li>Test networking and Kubernetes configurations.</li><li>Test multi-node scheduling scenarios.</li><li>Run Kubernetes integration tests.</li><li>Build CI pipelines that require Kubernetes.</li><li>Experiment with GitOps tools such as Argo CD.</li></ul><p>For example, you can create a GitHub Actions workflow that spins up a Kind cluster, deploys your application, runs integration tests and destroys the environment when the workflow finishes.</p><p>This is particularly useful because you don’t need a permanent cloud cluster for every test.</p><h3>Where does Kind fall short?</h3><p>Kind is a local testing tool, not a production infrastructure solution by itself.</p><p>It doesn’t automatically provide:</p><ul><li>Production-grade cloud networking.</li><li>Managed persistent storage.</li><li>Production load balancers.</li><li>Cloud infrastructure provisioning.</li><li>A highly available managed Control Plane.</li></ul><p>You can configure and simulate certain capabilities, but the environment is fundamentally designed around local Kubernetes clusters.</p><h3>5. Minikube — Local Kubernetes for Development</h3><p>Minikube is another popular tool for running Kubernetes locally.</p><p>Unlike Kind, which primarily uses Docker containers as Kubernetes nodes, Minikube supports different drivers and environments to create a local Kubernetes cluster.</p><p>Depending on your operating system and configuration, it can use Docker, virtual machines or other supported drivers.</p><p>Minikube is commonly used for learning Kubernetes, local development and experimentation.</p><h3>How does Minikube work?</h3><p>Imagine you’re learning Kubernetes and want to deploy:</p><ul><li>A frontend application.</li><li>A backend API.</li><li>A Redis instance.</li><li>A PostgreSQL database.</li></ul><p>You need a Kubernetes environment to deploy and test everything. Minikube gives you a local cluster without requiring a cloud account.</p><p>Its cluster can run on your laptop using a supported driver.</p><h3>Minikube Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tix8ws3TTTETRNWJz1U3rA.png" /></figure><p>This represents a simplified single-node Minikube setup. Minikube also supports multi-node clusters.</p><h3>Installing Minikube</h3><p>You’ll generally need:</p><ul><li>kubectl</li><li>Minikube</li><li>A supported driver such as Docker</li></ul><p>After installing the required tools, start your cluster:</p><pre>minikube start</pre><p>Check your cluster:</p><pre>kubectl get nodes</pre><p>You can also check the cluster status:</p><pre>minikube status</pre><h3>Running a multi-node Minikube cluster</h3><p>Minikube supports multi-node clusters.</p><p>For example:</p><pre>minikube start --nodes 3</pre><p>Depending on the driver and configuration, Minikube creates a cluster with multiple local nodes.</p><p>Check them:</p><pre>kubectl get nodes</pre><h3>Minikube Addons</h3><p>One of the useful features of Minikube is its addon system.</p><p>Addons allow you to enable certain capabilities in your local cluster.</p><p>For example:</p><pre>minikube addons list</pre><p>You can enable an addon where supported:</p><pre>minikube addons enable metrics-server</pre><p>Other addons may include dashboard, ingress and additional components, depending on Minikube’s available addon support and your environment.</p><h3>When should you use Minikube?</h3><p>Use Minikube when:</p><ul><li>You’re learning Kubernetes from scratch.</li><li>You want a convenient local development environment.</li><li>You want to experiment with Kubernetes addons.</li><li>You want to deploy multiple applications locally.</li><li>You want to understand how Kubernetes workloads behave.</li></ul><p>Kind and Minikube are both good choices. You don’t need to master both immediately.</p><p>Pick one, build projects, understand Kubernetes objects and move on to infrastructure-level Kubernetes when you’re ready.</p><h3>6. Kubeadm — Building Your Own Kubernetes Cluster</h3><p>Now let’s move beyond local Kubernetes.</p><p>So far, we’ve used tools that make running Kubernetes locally easier. But what happens when you want to run Kubernetes on actual servers or cloud virtual machines?</p><p>What if you want to understand how a Kubernetes cluster is installed and configured on multiple machines?</p><p>This is where Kubeadm comes in.</p><p>Kubeadm is a Kubernetes tool that helps bootstrap a Kubernetes cluster. It helps initialize a Control Plane and join additional nodes to a cluster.</p><p>It isn’t Kubernetes itself, and it isn’t a managed Kubernetes service.</p><p>It helps you set up a Kubernetes cluster using the Kubernetes components and configuration required for the cluster to operate.</p><h3>Imagine building your own restaurant</h3><p>Instead of renting a fully managed restaurant, you decide to build and operate everything yourself.</p><p>You need to:</p><ul><li>Set up the building.</li><li>Install equipment.</li><li>Configure electricity and water.</li><li>Hire staff.</li><li>Manage maintenance.</li><li>Handle failures.</li></ul><p>Kubeadm is somewhat like a setup assistant for the Kubernetes cluster. It helps you initialize and join the machines, but you remain responsible for the broader infrastructure and operational management.</p><h3>Kubeadm Architecture on AWS EC2</h3><p>Imagine you provision three EC2 instances.</p><ul><li>One instance acts as the Control Plane.</li><li>Two instances act as Worker Nodes.</li></ul><p>You install the required dependencies, configure the machines and initialize Kubernetes using Kubeadm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0gOok_dFdMl_wG0fx2GkTA.png" /></figure><p>This is a simplified deployment. A production cluster would require additional infrastructure and operational considerations.</p><h3>How do we build this cluster?</h3><h4>Step 1: Provision EC2 instances</h4><p>Create your EC2 instances.</p><p>For a learning environment, you could start with:</p><ul><li>One Control Plane instance.</li><li>Two Worker Node instances.</li></ul><p>Choose instance sizes based on the workload, Kubernetes components and available memory.</p><p>For a lab, smaller instances might be sufficient for lightweight workloads, but resource requirements can vary.</p><p>I got a github repo how to setup. Kubeadm on EC2 Aws go to this repo and setup Kubeadm and also you can use ai for that…</p><p>🏴‍☠️ <a href="https://github.com/Cloud-Automation-Partner/Kubernetes-Cluster-Installation-In-AWS-Using-Kubeadm">Kubeadm-Setup-Github-Repo</a></p><h3>What do you actually learn using Kubeadm?</h3><p>This is one of the most valuable ways to understand Kubernetes infrastructure.</p><p>You learn:</p><ul><li>How Kubernetes components are installed.</li><li>How a Control Plane is initialized.</li><li>How Worker Nodes join a cluster.</li><li>How Kubernetes networking is configured.</li><li>How cluster certificates work.</li><li>How kubelet communicates with the API Server.</li><li>How nodes are registered.</li><li>How cluster upgrades are approached.</li><li>How infrastructure failures affect Kubernetes.</li></ul><h3>Who should use Kubeadm?</h3><p>Kubeadm is useful for:</p><ul><li>Kubernetes learning.</li><li>Infrastructure experimentation.</li><li>Self-managed Kubernetes clusters.</li><li>On-premises Kubernetes.</li><li>Bare-metal Kubernetes.</li><li>Certain self-managed cloud deployments.</li><li>Understanding Kubernetes cluster administration.</li></ul><h3>What are the disadvantages?</h3><p>When you build a cluster yourself, you are responsible for the operational side.</p><p>Depending on the architecture, you may need to manage:</p><ul><li>Control Plane availability.</li><li>etcd backups.</li><li>Certificates.</li><li>Kubernetes upgrades.</li><li>Node replacement.</li><li>Networking.</li><li>Storage.</li><li>Security.</li><li>Monitoring.</li><li>Disaster recovery.</li><li>Infrastructure provisioning.</li></ul><p>A single Control Plane cluster is suitable for learning, but it isn’t a highly available production Control Plane.</p><h3>7. Amazon EKS — Managed Kubernetes on AWS</h3><p>Now let’s move to the cloud and understand how Kubernetes is used in real-world AWS environments.</p><p>Amazon EKS stands for Amazon Elastic Kubernetes Service.</p><p>It is AWS’s managed Kubernetes service.</p><p>When you create a Kubernetes cluster using Kubeadm, you’re responsible for setting up and operating much of the cluster infrastructure yourself.</p><p>With EKS, AWS manages the Kubernetes Control Plane infrastructure for you. This doesn’t mean AWS manages your entire Kubernetes environment.</p><p>You still manage your workloads, configurations, security policies, application deployments and much of the worker infrastructure, depending on how you configure your cluster.</p><h3>Why do companies use EKS?</h3><p>Imagine your company has several applications.</p><ul><li>Frontend.</li><li>Backend API.</li><li>Authentication service.</li><li>Payment service.</li><li>Background workers.</li><li>Database-related workloads.</li></ul><p>The engineering team wants to deploy these applications on Kubernetes.</p><p>They also want:</p><ul><li>A managed Control Plane.</li><li>AWS integrations.</li><li>Cloud networking.</li><li>IAM-based access.</li><li>Scalable compute.</li><li>Monitoring.</li><li>Security.</li><li>Infrastructure automation.</li></ul><p>Building and maintaining every Kubernetes Control Plane component yourself can require significant operational effort.</p><p>EKS reduces that burden by managing the Kubernetes Control Plane infrastructure.</p><h3>EKS Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-0duLXonAKdrwxMmWv4mrA.jpeg" /></figure><p>The diagram is conceptual. EKS Control Plane components are managed by AWS and operate within AWS’s managed infrastructure. Worker nodes and workload resources are configured separately as part of your cluster architecture.</p><h3>What does AWS manage?</h3><p>AWS manages the Kubernetes Control Plane infrastructure, including the managed API Server and Control Plane components, and provides managed operational capabilities.</p><p>The exact operational responsibilities depend on the service and configuration.</p><p>You don’t normally provision and administer the underlying EKS Control Plane servers yourself.</p><h3>What do you manage?</h3><p>Depending on your architecture, you may manage:</p><ul><li>Worker Nodes.</li><li>Node groups.</li><li>EC2 instances.</li><li>VPC and subnets.</li><li>Security groups.</li><li>Kubernetes workloads.</li><li>Deployment configurations.</li><li>IAM permissions.</li><li>Kubernetes RBAC.</li><li>Persistent storage configuration.</li><li>Load balancing.</li><li>Application monitoring.</li><li>Autoscaling configuration.</li><li>Infrastructure costs.</li></ul><p>EKS provides managed capabilities, but Kubernetes is still Kubernetes.</p><p>You need to understand its architecture, scheduling, networking, storage and workload management.</p><h3>How do we create an EKS cluster?</h3><p>There are multiple ways to create an EKS cluster.</p><p>For example:</p><ul><li>AWS Console.</li><li>AWS CLI.</li><li>eksctl.</li><li>Terraform.</li><li>CloudFormation.</li></ul><p>For DevOps and cloud engineering, Terraform is particularly useful because it allows you to define your infrastructure as code.</p><p>A simplified Terraform-based architecture could create:</p><ul><li>VPC.</li><li>Public and private subnets.</li><li>Internet gateway and routing.</li><li>NAT infrastructure where required.</li><li>EKS cluster.</li><li>Managed node groups.</li><li>IAM roles.</li><li>Security configurations.</li></ul><p>The actual infrastructure depends on your requirements.</p><p>If you want to setup eks on Ec2 instance using terraform then go to this repo and bommmm.. You get know to do we use terrafrom to create a eks cluster which is industry standard</p><p>🏴‍☠️ <a href="https://github.com/ravindrasinghh/Kubernetes-Playlist/tree/master/Lesson1">Eks-Setup-Github-Repo</a></p><h3>EKS with Managed Node Groups</h3><p>One common approach is to use EKS Managed Node Groups.</p><p>AWS manages aspects of the node group lifecycle, including provisioning and lifecycle operations, but the EC2 instances are still part of your infrastructure and you remain responsible for workload and cluster configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ts3-sbwrhuAiVN01-hODQ.jpeg" /></figure><p>Managed Node Groups are a useful starting point for many EKS deployments.</p><p>You define the node group configuration and AWS helps manage its lifecycle.</p><p>However, node groups are typically configured with a defined instance type or set of instance types, scaling configuration and other parameters.</p><p>This can be less flexible than dynamically provisioning nodes based on the actual workload requirements.</p><p>That’s one of the reasons Karpenter becomes interesting.</p><h3>8. Karpenter — Automatically Provisioning Kubernetes Nodes</h3><p>Imagine your Kubernetes cluster currently has two Worker Nodes.</p><p>Your application is running smoothly.</p><p>But suddenly, traffic increases.</p><p>New Pods are created, and the existing Worker Nodes don’t have enough resources to schedule them. The Pods may remain in a Pending state.</p><p>Now you need additional compute capacity.</p><p>Traditionally, you might use a cluster autoscaling mechanism associated with node groups to increase the number of nodes.</p><p>But what if you want Kubernetes to dynamically choose suitable EC2 instances based on the workloads that need to be scheduled?</p><p>This is where Karpenter comes in.</p><p>Karpenter is an open-source Kubernetes node provisioning and autoscaling system that can dynamically provision compute capacity based on the requirements of unschedulable workloads.</p><p>It integrates with Kubernetes and cloud infrastructure to help provision nodes when existing capacity isn’t sufficient.</p><p>On AWS, Karpenter can provision EC2 instances based on configured constraints and workload requirements.</p><h3>What problem does Karpenter solve?</h3><p>Suppose your cluster has two EC2 Worker Nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DaWprMtHDo2mqGtkkzKFdQ.jpeg" /></figure><p>Now, several additional Pods are created.</p><p>But the existing nodes don’t have enough resources to schedule them.</p><p>Kubernetes Scheduler attempts to place these Pods on available nodes according to their scheduling requirements.</p><p>If the Pods cannot be scheduled, Karpenter can observe the unschedulable workloads and provision suitable compute capacity when the configured constraints and conditions allow it.</p><h3>How Karpenter works</h3><p>The simplified process looks like this:</p><p>1. A Pod is created.</p><p>2. Kubernetes Scheduler attempts to schedule the Pod.</p><p>3. The Pod remains unschedulable because available nodes cannot satisfy its requirements.</p><p>4. Karpenter observes the unschedulable workload.</p><p>5. Karpenter evaluates the configured provisioning requirements.</p><p>6. Karpenter provisions a suitable EC2 instance.</p><p>7. The new node joins the Kubernetes cluster.</p><p>8. Kubernetes Scheduler places the Pod on the available node.</p><h3>Karpenter Architecture on EKS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zA6Mfigh7pTysMK8XV0Ckg.jpeg" /></figure><p>This diagram simplifies the flow. Karpenter interacts with Kubernetes scheduling state and AWS infrastructure through its controller and cloud-provider integration. The Scheduler itself does not request EC2 instances directly from Karpenter.</p><h3>How does Karpenter decide what to provision?</h3><p>Karpenter doesn’t randomly launch servers.</p><p>You configure constraints that describe what kinds of nodes it can provision.</p><p>Depending on your configuration, these may include:</p><ul><li>CPU requirements.</li><li>Memory requirements.</li><li>Instance categories.</li><li>Instance sizes.</li><li>CPU architectures.</li><li>Availability zones.</li><li>Capacity types.</li><li>Operating systems.</li><li>Node requirements.</li><li>Scheduling constraints.</li></ul><p>Karpenter evaluates the workloads that need to be scheduled and the provisioning constraints you’ve configured.</p><p>It can choose suitable instance types within those constraints.</p><p>This allows a more flexible provisioning model than simply adding another instance to a fixed node group.</p><h3>Karpenter vs Cluster Autoscaler</h3><p>Both tools help scale Kubernetes infrastructure, but their approaches differ.</p><p>Both can be useful. Karpenter isn’t automatically the better choice for every environment, and Cluster Autoscaler is still a valid solution for many Kubernetes deployments.</p><h3>Karpenter and cost optimization</h3><p>One of Karpenter’s interesting capabilities is helping optimize infrastructure utilization.</p><p>Suppose your application requires:</p><ul><li>2 CPU cores.</li><li>4 GB of memory.</li></ul><p>But your current cluster has several large EC2 instances that are mostly idle. You may be paying for significantly more compute capacity than your workloads need.</p><p>Karpenter can help provision more suitable capacity and consolidate eligible workloads onto fewer nodes, depending on workload requirements and its configuration.</p><p>This can potentially reduce compute costs. However, Karpenter doesn’t guarantee savings.</p><p>Costs depend on:</p><ul><li>Instance types.</li><li>CPU and memory requirements.</li><li>Pod requests and limits.</li><li>Availability zones.</li><li>Spot vs On-Demand capacity.</li><li>Workload disruption constraints.</li><li>Node utilization.</li><li>Consolidation policies.</li><li>Persistent storage.</li><li>Network costs.</li><li>The workload’s actual behavior.</li></ul><p>Karpenter is a provisioning and optimization tool, not a billing tool. You still need to monitor costs and design workloads carefully.</p><h3>Karpenter’s important components on AWS</h3><p>In modern Karpenter installations, you’ll commonly work with two important custom resources:</p><h4>— NodePool</h4><p>NodePool defines the provisioning constraints and policies that Karpenter uses to determine what kinds of nodes it can provision.</p><p>It can specify requirements, limits, disruption-related policies and other provisioning settings.</p><h4>— EC2NodeClass</h4><p>EC2NodeClass defines AWS-specific configuration for EC2 node provisioning.</p><p>This can include AMI selection, subnets, security groups, IAM configuration and other EC2-related settings. These resources work together to describe how Karpenter should provision nodes.</p><p>The exact configuration depends on your Karpenter version and installation. Karpenter has evolved over time, so always use the documentation for the version you’re installing.</p><h3>9. Putting Everything Together — How These Tools Fit</h3><p>This is the most important part of the article. These tools aren’t interchangeable.</p><p>They serve different purposes within the Kubernetes ecosystem.</p><p>Let’s visualize the relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXsifghk_IpRLQXcYSV9iQ.jpeg" /></figure><p>This is a conceptual grouping. Karpenter can also be used in other supported Kubernetes environments, and EKS can use multiple compute models. This diagram focuses on common learning and AWS deployment paths.</p><h3>— Kind</h3><p>Kind is useful for running Kubernetes locally using Docker containers as nodes.</p><p>You don’t need cloud infrastructure for your local cluster.</p><h3>— Minikube</h3><p>Minikube provides a local Kubernetes environment using supported drivers.</p><p>It’s particularly convenient for learning and local application development.</p><h3>— Kubeadm</h3><p>Kubeadm helps bootstrap your own Kubernetes cluster.</p><p>You control the infrastructure and are responsible for managing the cluster’s operational requirements.</p><h3>— EKS</h3><p>EKS provides a managed Kubernetes Control Plane on AWS.</p><p>You still manage your workloads and much of the surrounding infrastructure, depending on your architecture.</p><h3>— Karpenter</h3><p>Karpenter dynamically provisions suitable Kubernetes nodes based on workload requirements and configured constraints.</p><p>It can help your EKS cluster adapt to changing workloads.</p><h3>10. Kubernetes Cost — What Actually Costs Money?</h3><p>Kubernetes itself doesn’t automatically mean you’re paying for an expensive cloud infrastructure.</p><p>Your costs depend on where and how you’re running it.</p><p>Let’s understand the cost of each approach.</p><h3>— Kind</h3><p>Kind doesn’t require a cloud Kubernetes Control Plane or EC2 infrastructure by default.</p><p>You’re using your local machine and Docker.</p><p>Your main costs are:</p><ul><li>Laptop hardware.</li><li>Electricity.</li><li>Your existing development environment.</li></ul><p>For local Kubernetes learning, Kind is generally one of the cheapest options.</p><h3>— Minikube</h3><p>Similar to Kind, Minikube runs locally.</p><p>You generally don’t pay AWS or another cloud provider for a Kubernetes Control Plane or compute resources when you’re running a local cluster.</p><p>Your resources are consumed by your laptop or the local infrastructure you’re using.</p><h3>— Kubeadm on AWS</h3><p>Suppose you create:</p><ul><li>One EC2 Control Plane instance.</li><li>Two EC2 Worker Nodes.</li></ul><p>You pay for the AWS infrastructure you provision and use.</p><p>Your cost can include:</p><ul><li>EC2 instances.</li><li>EBS volumes.</li><li>Public IPv4 addresses where applicable.</li><li>Network data transfer.</li><li>Load balancers.</li><li>NAT gateways.</li><li>Other AWS services.</li></ul><p>You also need to consider the operational cost of maintaining the cluster.</p><p>Kubeadm itself doesn’t charge you for Kubernetes cluster management.</p><h3>— Amazon EKS</h3><p>EKS introduces additional costs.</p><p>Your costs may include:</p><ul><li>EKS cluster management fees.</li><li>EC2 instances.</li><li>EBS volumes.</li><li>Load balancers.</li><li>NAT gateways.</li><li>Public IPv4 addresses.</li><li>Network data transfer.</li><li>Cloud monitoring.</li><li>Additional AWS services.</li></ul><p>EKS cluster management pricing and the applicable cluster support options can change. Check the official AWS EKS pricing page before creating a cluster.</p><h3>— Karpenter</h3><p>Karpenter itself is an open-source project.</p><p>You generally don’t pay a separate Karpenter software license fee for the open-source project.</p><p>However, you pay for the infrastructure Karpenter provisions.</p><p>For example:</p><ul><li>EC2 instances.</li><li>EBS volumes.</li><li>Network resources.</li><li>Additional services associated with your workloads.</li></ul><p>Karpenter can potentially reduce costs through better provisioning and consolidation, but you should measure the actual savings.</p><h3>A practical cost-saving approach</h3><p>If you’re learning Kubernetes and AWS:</p><ol><li>Start with Kind or Minikube.</li><li>Learn Kubernetes objects.</li><li>Learn deployments, services, ingress and storage.</li><li>Learn networking.</li><li>Learn Kubeadm on EC2.</li><li>Understand cluster administration.</li><li>Create an EKS cluster for a focused project.</li><li>Experiment with Karpenter.</li><li>Monitor AWS costs.</li><li>Destroy infrastructure when you’re finished.</li></ol><p>You don’t need an expensive permanent EKS cluster to learn Kubernetes.</p><p>In fact, local Kubernetes should be your starting point.</p><h3>11. Which One Should You Learn First?</h3><p>If you’re starting from scratch, I wouldn’t recommend jumping straight into EKS.</p><p>You’ll end up learning AWS infrastructure, IAM, VPC, EC2, Kubernetes, networking and autoscaling simultaneously.</p><p>It can become overwhelming.</p><p>Instead, follow this sequence.</p><h3>Step 1: Learn Docker</h3><p>Understand:</p><ul><li>Containers.</li><li>Docker images.</li><li>Dockerfile.</li><li>Docker Compose.</li><li>Container networking.</li><li>Volumes.</li><li>Image registries.</li></ul><p>Before learning Kubernetes, you should be comfortable running applications using Docker.</p><h3>Step 2: Learn Kubernetes Basics Using Kind or Minikube</h3><p>Learn:</p><ul><li>Pods.</li><li>Deployments.</li><li>ReplicaSets.</li><li>Services.</li><li>ConfigMaps.</li><li>Secrets.</li><li>Namespaces.</li><li>Ingress.</li><li>Persistent Volumes.</li><li>Persistent Volume Claims.</li><li>Jobs.</li><li>CronJobs.</li></ul><p>Build a small project and deploy it locally.</p><h3>Step 3: Learn Kubernetes Networking</h3><p>Understand:</p><ul><li>Pod networking.</li><li>Service networking.</li><li>ClusterIP.</li><li>NodePort.</li><li>LoadBalancer.</li><li>Ingress.</li><li>DNS.</li><li>CNI.</li></ul><h3>Step 4: Learn Kubernetes Storage</h3><p>Understand:</p><ul><li>Volumes.</li><li>Persistent Volumes.</li><li>Persistent Volume Claims.</li><li>Storage Classes.</li><li>StatefulSets.</li></ul><h3>Step 5: Build a Cluster Using Kubeadm</h3><p>Use EC2 instances or virtual machines.</p><p>Understand:</p><ul><li>Control Plane.</li><li>Worker Nodes.</li><li>Kubelet.</li><li>Container runtime.</li><li>CNI.</li><li>Cluster initialization.</li><li>Node joining.</li><li>Cluster upgrades.</li></ul><h3>Step 6: Learn AWS Fundamentals</h3><p>Before EKS, understand:</p><ul><li>VPC.</li><li>Subnets.</li><li>Route tables.</li><li>Security groups.</li><li>IAM.</li><li>EC2.</li><li>EBS.</li><li>Load balancers.</li><li>DNS.</li></ul><h3>Step 7: Learn EKS</h3><p>Understand:</p><ul><li>EKS architecture.</li><li>Managed Control Plane.</li><li>Managed Node Groups.</li><li>EKS access management.</li><li>IAM integration.</li><li>Networking.</li><li>Storage.</li><li>Load balancing.</li></ul><h3>Step 8: Learn Karpenter</h3><p>Understand:</p><ul><li>Node provisioning.</li><li>NodePool.</li><li>EC2NodeClass.</li><li>Pod scheduling.</li><li>Pod resource requests.</li><li>Node consolidation.</li><li>Spot instances.</li><li>Disruption policies.</li></ul><p>By this stage, you will have a much better understanding of why companies use these tools and how they fit into real infrastructure.</p><h3>Final Thoughts</h3><p>When I first came across Kubernetes, tools like Kind, Minikube, Kubeadm, EKS and Karpenter seemed like completely different technologies.</p><p>But once you understand the purpose behind each one, the picture becomes much clearer.</p><p>-Kubernetes is the orchestration platform.</p><p>-Kind and Minikube help you run Kubernetes locally.</p><p>-Kubeadm helps you bootstrap your own Kubernetes cluster.</p><p>-Amazon EKS provides a managed Kubernetes Control Plane on AWS.</p><p>-Karpenter helps dynamically provision Kubernetes nodes based on workload requirements and configured constraints.</p><p>You don’t need to learn all of them on day one.</p><p>Start small. Run Kubernetes locally. Deploy applications. Break things. Fix them. Then move to actual infrastructure and understand what changes when Kubernetes runs in the cloud.</p><p>The goal isn’t to memorize tools.</p><p>The goal is to understand the infrastructure, the problems these tools solve and how to use them in the right environment. And that’s what makes Kubernetes much easier to learn.</p><p>So yeah this is pretty much if you got a knowledge from this article than gimme a clap and do comments and you can also follow me on <a href="https://x.com/Shivatwd1">X</a> &amp; <a href="https://www.linkedin.com/in/shiva-singh-b2104a373/">Linkedin</a></p><p>Read-more my articles:<br><a href="https://medium.com/@shivasingh.1dev/how-a-modern-ci-cd-pipeline-actually-works-from-local-code-to-kubernetes-production-b0b3a122481b">https://medium.com/@shivasingh.1dev/how-a-modern-ci-cd-pipeline-actually-works-from-local-code-to-kubernetes-production-b0b3a122481b</a></p><p><a href="https://medium.com/@shivasingh.1dev/what-is-docker-commands-docker-networking-and-docker-volumes-6e1e3676a96f">https://medium.com/@shivasingh.1dev/what-is-docker-commands-docker-networking-and-docker-volumes-6e1e3676a96f</a></p><p><a href="https://medium.com/@shivasingh.1dev/docker-explained-what-it-is-how-it-works-internally-and-essential-commands-5c0e5c449595">Docker Explained? And How It Works Internally?</a></p><p><a href="https://medium.com/@shivasingh.1dev/kubernetes-deployment-strategies-explained-with-hands-on-examples-2c120c191426">https://medium.com/@shivasingh.1dev/kubernetes-deployment-strategies-explained-with-hands-on-examples-2c120c191426</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eceeb78c0880" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Scale Node.js Applications Using PM2: From Single Core to Multi-Core]]></title>
            <link>https://medium.com/@shivasingh.1dev/how-to-scale-node-js-applications-using-pm2-from-single-core-to-multi-core-906f39f57119?source=rss-ae6be363234d------2</link>
            <guid isPermaLink="false">https://medium.com/p/906f39f57119</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[shivatech]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 18:12:49 GMT</pubDate>
            <atom:updated>2026-11-26T18:12:49.915Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Understanding Node.js bottlenecks, clustering, load balancing and PM2 with a practical example.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*erDnvdgXG-5UJop8qbwY9w.png" /></figure><h3>Introduction</h3><p>Node.js is one of the most popular technologies for building APIs, backend services and real-time applications. It’s fast, lightweight and makes it relatively easy to build applications that can handle a large number of concurrent requests.</p><p>But what happens when your application starts getting more traffic?</p><p>Imagine you’ve built a Node.js backend for an e-commerce website. Initially, everything works perfectly. A few hundred users visit your website, APIs respond quickly and your server is doing just fine.</p><p>But one day, traffic starts increasing. Thousands of users are accessing your application at the same time. Your APIs start taking longer to respond, the server becomes busy and eventually your application might even crash.</p><p>You upgrade your server, add more RAM and CPU resources, but you still haven’t fully utilized the machine.</p><p>Why does this happen?</p><p>One of the reasons is that a typical Node.js application runs as a single process, and its JavaScript execution is primarily handled by a single thread. On a machine with multiple CPU cores, a single Node.js process doesn’t automatically use all those cores for executing your JavaScript.</p><p>So, how do we make our Node.js application use multiple CPU cores?</p><p>That’s where <strong>PM2 and Cluster Mode</strong> come into the picture.</p><p>In this article, we’ll understand the problem from scratch, build a Node.js application and scale it using PM2.</p><h3>1. First, understand how a CPU works</h3><p>Before discussing Node.js, let’s understand something about the machine on which our application runs.</p><p>When you deploy your backend on a server, that server has CPU, RAM, storage and other resources.</p><p>The CPU is responsible for executing instructions. Modern CPUs often contain multiple cores, and each core can execute instructions independently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*okqcQHQycT9_Lmj9BvtA7Q.png" /></figure><p>For example, suppose you have an AWS EC2 instance with a 4-vCPU configuration.</p><p>For simplicity, imagine your server has four CPU cores available:</p><ul><li>Core 1</li><li>Core 2</li><li>Core 3</li><li>Core 4</li></ul><p>These cores allow the machine to execute work in parallel. Think of CPU cores like four employees working in an office.</p><p>If you have four employees but assign all your work to just one employee, the other three might remain underutilized.</p><p>The same kind of inefficiency can occur when one Node.js process is responsible for executing JavaScript on a multi-core machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5wBzJ-mKoEiSJyd4n0-mMQ.png" /></figure><p>Illustration idea: four CPU cores available on one machine. Now let’s understand what Node.js actually does with these cores.</p><h3>2. Why is Node.js called single-threaded?</h3><p>Node.js is built on the V8 JavaScript engine, the same JavaScript engine used by Chrome.</p><p>When we execute a typical Node.js application, the JavaScript code runs on a main thread. This thread uses an event loop to coordinate execution of JavaScript and handle asynchronous operations.</p><p>Let’s take a simple example.</p><pre>console.log(&quot;First&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;Second&quot;);<br>}, 1000);<br><br>console.log(&quot;Third&quot;);</pre><p>The output will be:</p><pre>First<br>Third<br>Second</pre><p>Why?</p><p>Node.js doesn’t wait for the timer to finish before executing the next line. It schedules the timer and continues executing the remaining code.</p><p>When the timer is ready, its callback gets scheduled to run through the event loop.</p><p>This is one of the reasons Node.js works well for applications that perform a lot of I/O operations, such as:</p><ul><li>Database queries</li><li>HTTP requests</li><li>Reading files</li><li>API calls</li><li>Real-time communication</li></ul><p>Node.js can handle many I/O operations without blocking JavaScript execution while waiting for those operations to complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*fY2wgVjRCtuJ0fADvzkk6g.png" /></figure><p>But here’s the important part&gt;&gt;&gt;&gt;&gt;&gt;</p><p>Asynchronous doesn’t mean parallel JavaScript execution on multiple CPU cores.</p><p>A single Node.js process typically executes JavaScript on one main thread. While Node.js can handle I/O asynchronously and some work is performed by the operating system or libuv’s thread pool, the main JavaScript execution thread is not automatically distributed across all CPU cores.</p><p>That’s the distinction we need to understand.</p><h3>What happens when we run Node.js normally?</h3><p>Suppose we have a machine with four CPU cores and run our application:</p><pre>node server.js</pre><p>This starts one Node.js process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G5h3Qk4U4msa__epOgyDVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*M0EDm0GreXzJL769eCMAxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ON0_rb1jaFU-CtCE6cmcOw.png" /></figure><p>The operating system may schedule this process across different cores over time. So it is not accurate to say that the process is permanently locked to Core 1.</p><p>However, the main JavaScript execution of that process is still primarily handled by one thread at a time.</p><p>This means we don’t automatically get four parallel JavaScript workers simply by running node server.js.</p><p>If our application has work that can benefit from multiple JavaScript processes, we need to run multiple instances of the application.</p><p>And that’s exactly what we’re going to do.</p><h3>3. The problem: One Node.js process handling everything</h3><p>Let’s build a small application to understand the problem practically.</p><p>We’ll create a simple Express server.</p><h3>Step 1: Create the project</h3><pre>mkdir node-scaling-demo<br>cd node-scaling-demo<br><br>npm init -y<br>npm install express</pre><p>Create a file called server.js.</p><h3>Step 2: Write the server code</h3><pre>const express = require(&quot;express&quot;);<br><br>const app = express();<br>const PORT = process.env.PORT || 3000;<br>app.get(&quot;/&quot;, (req, res) =&gt; {<br>  res.send(&quot;Hello from Node.js server!&quot;);<br>});<br>app.get(&quot;/api&quot;, (req, res) =&gt; {<br>  res.json({<br>    message: &quot;API is working&quot;,<br>    processId: process.pid,<br>  });<br>});<br>app.listen(PORT, () =&gt; {<br>  console.log(`Server running on port ${PORT}`);<br>  console.log(`Process ID: ${process.pid}`);<br>});</pre><p>Here is what our application does:</p><ul><li>/ returns a simple message.</li><li>/api returns a JSON response.</li><li>process.pid tells us the process ID of the running Node.js application.</li></ul><p>What is a PID?</p><p>PID stands for Process ID. Every running process on your operating system has a unique identifier assigned to it.</p><p>We are using process.pid because later, when we start multiple Node.js instances, we want to identify which process is responding to our requests.</p><h3>Step 3: Start the application</h3><pre>node server.js</pre><p>You should see something like:</p><pre>Server running on port 3000<br>Process ID: 12345</pre><p>The process ID above is just an example. Yours will be different.</p><p>Open your browser:</p><p><a href="http://localhost:3000/api?utm_source=chatgpt.com">http://localhost:3000/api</a></p><p>You’ll get something like:</p><pre>{<br>  &quot;message&quot;: &quot;API is working&quot;,<br>  &quot;processId&quot;: 12345<br>}</pre><p>Our application is running successfully.</p><p>But right now, we are running only one Node.js instance.</p><p>If we have a server with multiple CPU cores, we can run multiple application processes instead of relying on just one.</p><p>Before we do that, let’s understand what PM2 is.</p><h3>4. What is PM2?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UXPyuhubEw2t1nhWK9p4KA.png" /></figure><p>PM2 stands for Process Manager 2. It’s a process manager designed to manage applications, particularly Node.js applications, in production environments.</p><p>Think of PM2 as a supervisor for your backend application.</p><p>Normally, if you start your application using:</p><pre>node server.js</pre><p>You are responsible for keeping that process running.</p><p>If the application crashes, it stops running. If you close your terminal session, the process may also stop depending on how you started it. If your server reboots, you need a way to start your application again.</p><p>In a production environment, we don’t want to manually handle all these things.</p><p>PM2 helps us manage our applications.</p><h3>What can PM2 do?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*wpZ2Fq6P5QbsRUdOWNu99g.png" /></figure><ul><li>Process management: Start, stop and restart Node.js applications.</li><li>Automatic restarts: Restart an application when it crashes.</li><li>Cluster mode: Run multiple instances of an application.</li><li>Load balancing: Distribute incoming requests among workers in cluster mode.</li><li>Monitoring: Inspect process status, CPU and memory usage.</li><li>Logs: View application output and error logs.</li><li>Startup management: Configure applications to start again after machine reboot.</li></ul><p>PM2 is not a replacement for Node.js or Express. It runs alongside your application and manages its processes.</p><p>Now let’s install it.</p><h3>5. Install PM2</h3><p>PM2 is commonly installed globally using npm.</p><pre>npm install -g pm2</pre><p>Check whether it was installed successfully:</p><pre>pm2 --version</pre><p>Now instead of starting our application with node server.js, we&#39;ll start it using PM2.</p><pre>pm2 start server.js</pre><p>You should see a process list showing your application.</p><p>PM2 has now started and is managing our Node.js application.</p><h3>Useful PM2 commands</h3><ol><li>Starts the application</li></ol><p>pm2 start server.js</p><p>2. Lists managed applications</p><p>pm2 list</p><p>3. Shows process status</p><p>pm2 status</p><p>4. Restarts an application</p><p>pm2 restart app</p><p>5. Stops an application</p><p>pm2 stop app</p><p>6. Removes an application from PM2</p><p>pm2 delete app</p><p>7. Displays application logs</p><p>pm2 logs</p><p>8. Displays monitoring information</p><p>pm2 monit</p><p>You can use these commands to manage your application without manually handling every process. But we haven’t solved our main problem yet.</p><p>We still need to run multiple instances of our application.</p><h3>6. PM2 Cluster Mode: The real solution</h3><h4><strong>Cluster Mode</strong></h4><p>PM2 supports two commonly used execution modes: fork mode and cluster mode.</p><h4>Fork mode</h4><p>Fork mode runs your application as a regular process. It is useful for managing individual processes and applications that don’t need PM2’s cluster functionality.</p><h4>Cluster mode</h4><p>Cluster mode allows PM2 to start multiple instances of a Node.js application using Node.js cluster functionality.</p><p>These instances can share the same listening port and handle incoming requests through the cluster mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*zbI-jZNUiwxtpzQBVqUisg.png" /></figure><p>Let’s understand what happens in cluster mode.</p><p>Imagine our server has four CPU cores available.</p><p>Instead of running only one instance of our Node.js application, PM2 can start four worker processes.</p><ul><li>Worker 1 runs a Node.js application instance.</li><li>Worker 2 runs another Node.js application instance.</li><li>Worker 3 runs another Node.js application instance.</li><li>Worker 4 runs another Node.js application instance.</li></ul><p>Each worker is a separate process with its own JavaScript execution thread.</p><p>PM2 and Node.js cluster infrastructure allow the workers to share the listening port and distribute incoming connections among them.</p><p>Now our server can execute JavaScript across multiple processes simultaneously.</p><p>This is one way to scale a Node.js application vertically, by making better use of the CPU resources available on a single machine.</p><p>Let’s implement it.</p><h3>7. Scale our Node.js application using PM2</h3><p>We already have our server.js application.</p><p>Let’s start it using PM2 in cluster mode.</p><h3>Step 1: Stop the previous process</h3><p>If you previously started the application using PM2:</p><pre>pm2 delete all</pre><p>This removes PM2-managed processes. Use it carefully if you have other applications running under PM2.</p><h3>Step 2: Start the application in cluster mode</h3><pre>pm2 start server.js -i 4</pre><p>Let’s understand this command.</p><ul><li>pm2 start starts the application.</li><li>server.js is our application file.</li><li>-i is the instance option.</li><li>4 tells PM2 to start four instances.</li></ul><p>We now have four Node.js processes running.</p><p>If you want PM2 to automatically choose the number of instances based on the available CPUs:</p><pre>pm2 start server.js -i max</pre><p>max tells PM2 to use the maximum number of cluster instances based on the available CPU count.</p><p>Be careful with -i max on production servers.</p><p>More processes aren’t always better. Every worker consumes memory, and the number of workers should be chosen based on the server’s capacity and the application’s workload.</p><h3>Step 3: Check running instances</h3><pre>pm2 list</pre><p>You should see multiple instances of your application.</p><p>Each instance will have its own process ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9082glCaYuDbltzeHYGYw.png" /></figure><h3>Step 4: Test the API</h3><p>Open:</p><p><a href="http://localhost:3000/api?utm_source=chatgpt.com">http://localhost:3000/api</a></p><p>You might get:</p><pre>{<br>  &quot;message&quot;: &quot;API is working&quot;,<br>  &quot;processId&quot;: 12345<br>}</pre><p>Refresh the page multiple times.</p><p>You may see different process IDs responding to requests.</p><p>For example:</p><pre>{<br>  &quot;message&quot;: &quot;API is working&quot;,<br>  &quot;processId&quot;: 12345<br>}</pre><p>Then:</p><pre>{<br>  &quot;message&quot;: &quot;API is working&quot;,<br>  &quot;processId&quot;: 12346<br>}</pre><p>And:</p><pre>{<br>  &quot;message&quot;: &quot;API is working&quot;,<br>  &quot;processId&quot;: 12347<br>}</pre><p>This is the interesting part.</p><p>We have multiple instances of our application running, and requests can be handled by different workers.</p><p>The process IDs you see are examples. Request distribution is not guaranteed to rotate evenly on every browser refresh. Connection reuse, cluster scheduling and traffic patterns can affect which worker responds.</p><h3>8. What is load balancing in PM2?</h3><p>Load balancing means distributing incoming work across multiple workers or servers instead of sending everything to just one.</p><p>In PM2 cluster mode, Node.js cluster functionality provides the mechanism for distributing incoming connections among worker processes sharing a listening port.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*u8aHa2yom7ju9TtR7hfjng.png" /></figure><p>Imagine you have an API that receives 1,000 requests.</p><p>Instead of relying on a single worker to handle all those requests, multiple workers are available to handle incoming connections.</p><p>This doesn’t mean every worker will receive exactly 250 requests. Actual distribution depends on the connection pattern, workload, scheduling and other factors.</p><p>But having multiple workers allows the application to use more CPU resources and potentially handle more traffic.</p><p>That’s the basic idea behind scaling Node.js using PM2 cluster mode.</p><h3>9. What if one worker crashes?</h3><p>This is another important reason to use PM2.</p><p>Let’s say we have four workers running.</p><p>If one worker crashes, PM2 can detect that the process has exited and restart it.</p><p>This helps keep the application running without requiring us to manually start the crashed process.</p><p>For example, let’s create a route that intentionally crashes a worker.</p><p>Add this route to server.js:</p><pre>app.get(&quot;/crash&quot;, (req, res) =&gt; {<br>  res.send(&quot;This worker will crash&quot;);<br><br>setTimeout(() =&gt; {<br>    process.exit(1);<br>  }, 100);<br>});</pre><p>This is only for local testing. Never expose a route like this in a production application.</p><p>Restart your application:</p><pre>pm2 restart all</pre><p>Now visit:</p><p><a href="http://localhost:3000/crash?utm_source=chatgpt.com">http://localhost:3000/crash</a></p><p>The worker that handles the request will exit.</p><p>PM2 should detect that the process has exited and attempt to restart it.</p><p>Check:</p><pre>pm2 list</pre><p>Or:</p><pre>pm2 logs</pre><p>You should see the process restart activity.</p><p>This is one of the benefits of having a process manager.</p><p>But remember, PM2 can’t fix bugs that cause repeated crashes. If your application keeps crashing, PM2 may repeatedly restart it. You still need to identify and fix the underlying problem.</p><h3>10. What happens when you have more than one worker?</h3><p>This is where developers need to think beyond just starting more processes.</p><p>When we run multiple Node.js instances, each instance has its own memory.</p><p>This means variables stored in memory are not automatically shared between workers.</p><p>Let’s understand this with an example.</p><h3>In-memory data</h3><p>Suppose we have this code:</p><pre>let counter = 0;<br><br>app.get(&quot;/counter&quot;, (req, res) =&gt; {<br>  counter++;<br>  res.json({<br>    counter,<br>    processId: process.pid,<br>  });<br>});</pre><p>If you run this application with one process, the counter will increase as requests are handled.</p><p>But when we run multiple workers, each worker has its own copy of the counter variable.</p><p>For example:</p><p>Worker 1:</p><pre>Counter: 1<br>Counter: 2<br>Counter: 3</pre><p>Worker 2:</p><pre>Counter: 1<br>Counter: 2</pre><p>Worker 3:</p><pre>Counter: 1<br>Counter: 2</pre><p>Each process maintains its own counter.</p><p>This can create problems if your application relies on shared in-memory state.</p><h3>How do we solve this?</h3><p>We move shared state into an external system.</p><p>For example:</p><ul><li>Redis for shared caching, counters and suitable shared state.</li><li>PostgreSQL or MySQL for persistent application data.</li><li>MongoDB for persistent document data.</li><li>Shared storage or an external service for data that must be accessible to multiple workers.</li></ul><p>Now all workers can read and write to the same external data store instead of relying on their individual process memory.</p><p>This is a very important concept when scaling backend applications.</p><p>Scaling your application means thinking about architecture, not just running more processes.</p><h3>11. What about sessions and authentication?</h3><p>Imagine a user logs into your application.</p><p>Your backend stores some session information in memory.</p><p>The next request might be handled by another worker that doesn’t have that session information.</p><p>This can cause authentication or session-related problems.</p><p>That’s why session data in a multi-process application should generally be stored in a shared session store rather than in individual worker memory.</p><p>For example, Redis can be used as a shared session store with an appropriate session middleware.</p><p>The same idea applies to other stateful features.</p><p>When you scale your application, make sure that things like sessions, counters, temporary data and other shared state are not dependent on one particular worker.</p><h3>12. PM2 ecosystem file: Managing applications properly</h3><p>So far, we have started our application using commands like:</p><pre>pm2 start server.js -i 4</pre><p>This works perfectly for learning and simple deployments.</p><p>But when you start managing production applications, you may need to configure:</p><ul><li>Application name</li><li>Environment variables</li><li>Instance count</li><li>Cluster mode</li><li>Restart behavior</li><li>Memory limits</li><li>Multiple applications</li></ul><p>Instead of using long commands every time, PM2 supports an ecosystem configuration file.</p><h3>Step 1: Create an ecosystem file</h3><p>Create:</p><p>ecosystem.config.js</p><pre>module.exports = {<br>  apps: [<br>    {<br>      name: &quot;node-scaling-demo&quot;,<br><br>script: &quot;./server.js&quot;,<br>      instances: 4,<br>      exec_mode: &quot;cluster&quot;,<br>      env: {<br>        NODE_ENV: &quot;development&quot;,<br>        PORT: 3000,<br>      },<br>      env_production: {<br>        NODE_ENV: &quot;production&quot;,<br>        PORT: 3000,<br>      },<br>      max_memory_restart: &quot;500M&quot;,<br>    },<br>  ],<br>};</pre><p>Let’s understand the important options.</p><p>Property</p><p>Purpose</p><p>nameGives your application a name</p><p>scriptDefines the entry point</p><p>instancesNumber of instances to start</p><p>exec_modeDefines execution mode</p><p>envEnvironment variables</p><p>env_productionProduction-specific environment variables</p><p>max_memory_restartRestarts a worker when it exceeds the configured memory threshold</p><p>The memory limit is a restart threshold, not a hard memory limit.</p><p>PM2 can restart an application instance when it exceeds the configured memory threshold. This is not the same as limiting the process’s memory usage.</p><h3>Step 2: Start using the ecosystem file</h3><pre>pm2 start ecosystem.config.js</pre><p>For the production environment:</p><pre>pm2 start ecosystem.config.js --env production</pre><p>Now PM2 will use the configuration defined in our ecosystem file.</p><h3>Step 3: Restart using the configuration</h3><pre>pm2 restart ecosystem.config.js</pre><h3>Step 4: Check the application</h3><pre>pm2 list</pre><p>You should see your configured application and its instances.</p><p>This approach is cleaner and easier to maintain.</p><p>You can keep your PM2 configuration in your project repository and use it during deployment.</p><h3>13. PM2 monitoring and logs</h3><p>When an application is running in production, we need to monitor it.</p><p>We need to know:</p><ul><li>Is the application running?</li><li>Is CPU usage increasing?</li><li>Is memory usage too high?</li><li>Are there errors?</li><li>Are processes restarting repeatedly?</li></ul><p>PM2 provides basic monitoring tools.</p><h3>View process status</h3><pre>pm2 status</pre><h3>View logs</h3><pre>pm2 logs</pre><p>To see logs for a specific application:</p><pre>pm2 logs node-scaling-demo</pre><h3>Monitor CPU and memory</h3><pre>pm2 monit</pre><p>This provides a real-time view of managed processes and their resource usage.</p><p>These tools are helpful for debugging and monitoring a deployment, but for production observability, you may also want dedicated monitoring, logging and alerting systems.</p><h3>14. How to make PM2 start your application after a server reboot</h3><p>Suppose you deploy your application on an AWS EC2 instance.</p><p>Your application is running successfully under PM2.</p><p>But the server gets rebooted.</p><p>You don’t want to manually log into the machine and start your application every time.</p><p>PM2 supports startup configuration to help start managed processes when the machine boots.</p><h3>Step 1: Generate startup configuration</h3><pre>pm2 startup</pre><p>PM2 will print a command that you need to execute with the appropriate permissions.</p><p>Copy and execute the exact command generated by PM2 for your operating system and environment.</p><h3>Step 2: Save your process list</h3><p>After starting your applications:</p><pre>pm2 save</pre><p>This saves the current process list so PM2 can restore it when the startup service runs.</p><h3>Step 3: Verify</h3><p>After configuring the startup service and saving your process list, you can test the setup by rebooting your machine in a controlled environment.</p><p>After reboot, check:</p><pre>pm2 list</pre><p>Your saved applications should be restored if the startup configuration is correctly set up.</p><h3>15. How does this look in a real production environment?</h3><p>Let’s imagine we have an application running on an AWS EC2 instance.</p><p>Our application is a Node.js API.</p><p>Initially, we start with a single process.</p><p>As traffic grows, we use PM2 cluster mode to run multiple Node.js processes on the same server.</p><p>A simplified architecture would look like this:</p><pre>User → EC2 Instance → PM2 Cluster → Node.js Workers → Database</pre><p>The EC2 instance provides the machine resources. PM2 manages our Node.js processes. The workers handle incoming requests. The database stores persistent data.</p><p>Redis can be used for shared cache or session storage where needed.</p><p>This is a form of vertical scaling, because we are improving the capacity of one server by utilizing more of its available resources.</p><p>But this isn’t the only way to scale.</p><h3>16. PM2 is not the same as horizontal scaling</h3><p>There are two common approaches to scaling applications.</p><h3>- Vertical scaling</h3><p>Vertical scaling means increasing the resources of a single machine.</p><p>For example:</p><ul><li>Increasing CPU capacity</li><li>Increasing RAM</li><li>Moving to a larger EC2 instance</li></ul><p>PM2 cluster mode can help you utilize multiple CPU cores available on that machine.</p><h3>- Horizontal scaling</h3><p>Horizontal scaling means adding more machines to handle the workload.</p><p>Instead of running everything on one server, you deploy your application on multiple servers and distribute traffic across them.</p><p>For example:</p><pre>Users<br>                     |<br>              Load Balancer<br>               /          \<br>          Server 1       Server 2<br>          PM2 Workers    PM2 Workers<br>               \          /<br>                Database</pre><p>You can use an AWS Application Load Balancer to distribute traffic among multiple EC2 instances.</p><p>Each EC2 instance can independently run your Node.js application, potentially managed by PM2.</p><p>This allows you to scale beyond the resources of a single machine.</p><p>PM2 cluster mode helps scale processes within a server. A load balancer and multiple servers help scale across machines.</p><p>They solve related but different problems.</p><h3>17. Does PM2 solve every Node.js scaling problem?</h3><p>No.</p><p>PM2 helps us run multiple Node.js processes and manage them. But it doesn’t automatically make our entire application scalable.</p><p>There are still things we need to consider.</p><h3>CPU-intensive workloads</h3><p>If your application performs heavy CPU calculations, such as image processing, large data transformations or complex computations, those tasks can block a worker’s JavaScript execution thread.</p><p>Multiple workers can help distribute such work across CPU cores, but they don’t make a CPU-intensive task inside one worker non-blocking.</p><p>For specialized CPU-bound tasks, you may need Worker Threads, separate worker services or other architecture choices.</p><h3>Memory usage</h3><p>Each worker has its own memory overhead. If you start too many workers, your server may run out of memory.</p><h3>Database connections</h3><p>If each worker opens a large connection pool, the total number of database connections can grow significantly.</p><p>For example, if you have four workers and each worker creates a pool of 20 database connections, you could potentially have up to 80 connections.</p><p>You need to configure database pools according to the overall server and database capacity.</p><h3>Shared state</h3><p>Workers don’t automatically share memory.</p><p>Use shared storage or other appropriate architecture when application state must be accessible across workers.</p><h3>Graceful shutdown</h3><p>When deploying updates or shutting down processes, applications should handle termination signals appropriately.</p><p>Your application should stop accepting new work, allow in-flight requests to finish where practical, close database connections and clean up resources.</p><p>PM2 provides process-management and restart mechanisms, but application-level graceful shutdown still needs to be implemented properly.</p><h3>18. Final takeaway</h3><p>Node.js is excellent for building backend applications, especially applications that handle a lot of I/O operations.</p><p>But when we deploy Node.js on a multi-core machine, a single application process doesn’t automatically use all available CPU cores for executing JavaScript.</p><p>That’s where PM2 cluster mode becomes useful.</p><p>Using PM2, we can:</p><ul><li>Run multiple Node.js instances.</li><li>Utilize multiple CPU cores through separate worker processes.</li><li>Distribute incoming connections among workers.</li><li>Restart crashed workers.</li><li>Monitor CPU and memory usage.</li><li>Manage application logs.</li><li>Configure startup after machine reboot.</li></ul><p>But remember, scaling isn’t just about adding more processes.</p><p>You also need to think about database connections, shared state, sessions, memory, graceful shutdowns and monitoring.</p><p>PM2 is a useful tool for scaling and managing Node.js processes on a single machine. It’s a good starting point for understanding how production Node.js applications are managed.</p><p>That’s it for this article. Hopefully, this makes the concept of scaling Node.js using PM2 easier to understand.</p><p>If you’re learning backend development, try this example yourself. Run your application with one process, then switch to cluster mode and observe what changes.</p><p>Understanding these small things is what gradually helps you move from building applications to understanding how they work in production.</p><p>So yeah this is pretty much if you got a knowledge from this article than gimme a clap and do comments and you can also follow me on <a href="https://x.com/Shivatwd1">X</a> &amp; <a href="https://www.linkedin.com/in/shiva-singh-b2104a373/">Linkedin</a></p><p>Read-more my articles:<br><a href="https://medium.com/@shivasingh.1dev/learn-linux-on-windows-the-easy-way-step-by-step-wsl-ubuntu-guide-for-beginners-190d980c5336">https://medium.com/@shivasingh.1dev/learn-linux-on-windows-the-easy-way-step-by-step-wsl-ubuntu-guide-for-beginners-190d980c5336</a></p><p><a href="https://medium.com/@shivasingh.1dev/what-is-docker-commands-docker-networking-and-docker-volumes-6e1e3676a96f">https://medium.com/@shivasingh.1dev/what-is-docker-commands-docker-networking-and-docker-volumes-6e1e3676a96f</a></p><p><a href="https://medium.com/@shivasingh.1dev/docker-explained-what-it-is-how-it-works-internally-and-essential-commands-5c0e5c449595">https://medium.com/@shivasingh.1dev/docker-explained-what-it-is-how-it-works-internally-and-essential-commands-5c0e5c449595</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=906f39f57119" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Fixed My Slow E-Commerce Website by Moving from Vercel to AWS S3, CloudFront, and RDS A…]]></title>
            <link>https://medium.com/@shivasingh.1dev/how-i-fixed-my-slow-e-commerce-website-by-moving-from-vercel-to-aws-s3-cloudfront-and-rds-a-bf37f30e58e2?source=rss-ae6be363234d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf37f30e58e2</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[aws-s3]]></category>
            <dc:creator><![CDATA[shivatech]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 16:58:15 GMT</pubDate>
            <atom:updated>2026-11-20T16:58:15.663Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I Fixed My Slow E-Commerce Website by Moving from Vercel to AWS S3, CloudFront, and RDS A Real-World Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B7m6eyMd9XQfgCBYw57rHw.png" /></figure><p><em>When traffic spikes, hosting heavy product photos, videos, and PDFs directly on your web server will slow your store down. Here is how I rebuilt my architecture so anyone — tech or non-tech — can understand how modern apps scale.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GSVbM4oBm-1m0NSuPQHkyA.png" /></figure><p>3-months ago, I launched my e-commerce website. Like most developers, I wanted to move fast, so I deployed the whole thing on Vercel and kept my product photos, demo videos, and size-chart PDFs right inside my project folders.</p><p>At first, it felt magical. Pages loaded quickly, and everything worked out of the box.</p><p>Then, traffic started growing. People began browsing multiple product pages at once, watching product videos, and downloading brochures. Suddenly, my dashboard metrics turned red. Images took 4 to 5 seconds to appear, videos buffered endlessly, and customers started bouncing before even reaching the checkout page.</p><p>If you run an online store — or you are building one — you will hit this wall eventually. Here is the exact story of how I diagnosed the bottleneck and fixed it using <strong>Amazon S3</strong>, <strong>Amazon CloudFront</strong>, and <strong>Amazon RDS (PostgreSQL)</strong> with a <strong>Node.js/Express</strong> backend.</p><p>Why Was My Website Slowing Down? (The Restaurant Analogy)</p><p>Before diving into code, let’s understand what was actually happening behind the scenes.</p><p>Imagine running a busy restaurant where <strong>one single waiter</strong> has to take orders, cook the food, carry heavy boxes from the storeroom, and deliver heavy water jugs to every table. As soon as 50 customers walk in at the same time, that waiter collapses.</p><p>That was my Vercel/Node.js server. Every time a user opened a product page, my server was forced to:</p><ol><li>Fetch product prices and descriptions.</li><li>Read heavy image and video files from disk.</li><li>Push all those megabytes over the network to the user.</li></ol><p>To fix this, I needed to split the workload into specialized roles:</p><ul><li><strong>Amazon S3 (The Warehouse):</strong> A dedicated, virtually unlimited storage space built specifically to hold heavy files like high-res photos, videos, and PDFs.</li><li><strong>Amazon CloudFront (The Local Delivery Riders):</strong> Instead of making a customer in Mumbai wait for a file to travel from a faraway server, CloudFront caches copies of my images in local data centers near the user so they load in milliseconds.</li><li><strong>Amazon RDS with PostgreSQL (The Digital Ledger):</strong> A fast, structured database that stores lightweight text — like product names, prices, and the <em>exact shelf address</em> (file key) of where each photo sits inside S3.</li></ul><p>The “Aha!” Moment: Stop Uploading Files Through Your Backend</p><p>When I first started integrating S3, I made a rookie mistake. I sent the image from the admin dashboard to my Node.js server first, and then my Node.js server uploaded it to S3.</p><p>When uploading a 50MB product video, my Node.js server’s memory spiked and choked other users’ requests.</p><p>The real production trick is using <strong>Pre-Signed URLs</strong>. Instead of handling the heavy file itself, my Express backend simply checks if the admin is logged in, asks AWS for a temporary 5-minute “VIP upload pass” (a Pre-Signed URL), and hands that link to the browser. The browser then uploads the file <strong>directly to S3</strong>, completely bypassing my server.</p><p>Step 1: Organizing the Database (Amazon RDS)</p><p>Never store actual images or videos inside your database — it makes backups huge and queries sluggish. Instead, I created two simple tables in my <strong>PostgreSQL</strong> database on Amazon RDS: one for the product details, and one for the file paths.</p><pre>-- 1. Stores basic product info<br>CREATE TABLE products (<br>  id SERIAL PRIMARY KEY,<br>  name VARCHAR(255) NOT NULL,<br>  price DECIMAL(10, 2) NOT NULL,<br>  description TEXT,<br>  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP<br>);</pre><pre>-- 2. Stores only the S3 address (file_key) of the photos, videos, and PDFs<br>CREATE TABLE product_media (<br>  id SERIAL PRIMARY KEY,<br>  product_id INT REFERENCES products(id) ON DELETE CASCADE,<br>  file_key VARCHAR(255) NOT NULL, -- Example: &#39;products/171234-sneakers.jpg&#39;<br>  media_type VARCHAR(20) NOT NULL -- &#39;image&#39;, &#39;video&#39;, or &#39;pdf&#39;<br>);</pre><p>Step 2: Setting Up the Node.js &amp; Express Backend</p><p>On AWS (I used an EC2 instance in the ap-south-1 Mumbai region to keep latency low for Indian shoppers), I attached an <strong>IAM Role</strong> directly to my server. This is a huge security win: it allows my Express code to talk to S3 without me ever having to hardcode secret AWS passwords in my .env file.</p><p>Here is the clean, three-route setup I wrote using @aws-sdk/client-s3 and pg:</p><pre>require(&#39;dotenv&#39;).config();<br>const express = require(&#39;express&#39;);<br>const { Pool } = require(&#39;pg&#39;);<br>const { S3Client, PutObjectCommand } = require(&#39;@aws-sdk/client-s3&#39;);<br>const { getSignedUrl } = require(&#39;@aws-sdk/s3-request-presigner&#39;);</pre><pre>const app = express();<br>app.use(express.json());<br>const s3 = new S3Client({ region: &#39;ap-south-1&#39; });<br>const pool = new Pool({<br>  host: process.env.DB_HOST,<br>  port: 5432,<br>  user: process.env.DB_USER,<br>  password: process.env.DB_PASSWORD,<br>  database: process.env.DB_NAME,<br>  ssl: { rejectUnauthorized: false },<br>});<br>// ROUTE 1: Generate a 5-minute VIP pass for direct S3 upload<br>app.post(&#39;/api/admin/get-upload-url&#39;, async (req, res) =&gt; {<br>  try {<br>    const { fileName, fileType } = req.body;<br>    const fileKey = `products/${Date.now()}-${fileName}`;<br>    const command = new PutObjectCommand({<br>      Bucket: process.env.S3_BUCKET_NAME,<br>      Key: fileKey,<br>      ContentType: fileType,<br>    });<br>    const uploadUrl = await getSignedUrl(s3, command, { expiresIn: 300 });<br>    res.json({ uploadUrl, fileKey });<br>  } catch (err) {<br>    res.status(500).json({ error: &#39;Could not generate upload link&#39; });<br>  }<br>});<br>// ROUTE 2: Save product info &amp; the S3 file key into PostgreSQL<br>app.post(&#39;/api/admin/products&#39;, async (req, res) =&gt; {<br>  const client = await pool.connect();<br>  try {<br>    const { name, price, description, mediaFiles } = req.body;<br>    await client.query(&#39;BEGIN&#39;);<br>    const productRes = await client.query(<br>      &#39;INSERT INTO products (name, price, description) VALUES ($1, $2, $3) RETURNING id&#39;,<br>      [name, price, description]<br>    );<br>    const productId = productRes.rows[0].id;<br>    for (const file of mediaFiles) {<br>      await client.query(<br>        &#39;INSERT INTO product_media (product_id, file_key, media_type) VALUES ($1, $2, $3)&#39;,<br>        [productId, file.fileKey, file.mediaType]<br>      );<br>    }<br>    await client.query(&#39;COMMIT&#39;);<br>    res.status(201).json({ message: &#39;Product published!&#39;, productId });<br>  } catch (err) {<br>    await client.query(&#39;ROLLBACK&#39;);<br>    res.status(500).json({ error: &#39;Database transaction failed&#39; });<br>  } finally {<br>    client.release();<br>  }<br>});<br>// ROUTE 3: Serve products to customers using ultra-fast CloudFront links<br>app.get(&#39;/api/products&#39;, async (req, res) =&gt; {<br>  try {<br>    const query = `<br>      SELECT p.id, p.name, p.price, p.description,<br>      json_agg(<br>        json_build_object(<br>          &#39;url&#39;, CONCAT($1::text, &#39;/&#39;, pm.file_key),<br>          &#39;type&#39;, pm.media_type<br>        )<br>      ) AS media<br>      FROM products p<br>      LEFT JOIN product_media pm ON p.id = pm.product_id<br>      GROUP BY p.id<br>    `;<br>    const { rows } = await pool.query(query, [process.env.CLOUDFRONT_URL]);<br>    res.json(rows);<br>  } catch (err) {<br>    res.status(500).json({ error: &#39;Failed to load products&#39; });<br>  }<br>});<br>app.listen(5000, () =&gt; console.log(&#39;Server running smoothly on port 5000&#39;));</pre><p>Step 3: How the Frontend Handles the Upload</p><p>On my React/Next.js admin panel, uploading a product now happens in a smooth, three-step chain:</p><pre>const handleProductUpload = async (file, productData) =&gt; {<br>  // 1. Ask our Express server for a temporary S3 upload link<br>  const res = await fetch(&#39;/api/admin/get-upload-url&#39;, {<br>    method: &#39;POST&#39;,<br>    headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>    body: JSON.stringify({ fileName: file.name, fileType: file.type }),<br>  });<br>  const { uploadUrl, fileKey } = await res.json();</pre><pre>// 2. Push the heavy file directly to S3 (Zero load on our backend!)<br>  await fetch(uploadUrl, {<br>    method: &#39;PUT&#39;,<br>    headers: { &#39;Content-Type&#39;: file.type },<br>    body: file,<br>  });<br>  // 3. Save the text details + fileKey in RDS PostgreSQL<br>  await fetch(&#39;/api/admin/products&#39;, {<br>    method: &#39;POST&#39;,<br>    headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>    body: JSON.stringify({<br>      ...productData,<br>      mediaFiles: [{ fileKey, mediaType: &#39;image&#39; }],<br>    }),<br>  });<br>};</pre><h4>3 Mistakes I Made (So You Don’t Have To)</h4><ol><li><strong>Forgetting S3 CORS Settings:</strong> When my frontend first tried uploading directly to S3, the browser blocked it with a CORS error. I had to go into my S3 Bucket <strong>Permissions &gt; Cross-origin resource sharing (CORS)</strong> and explicitly whitelist my website domain for PUT and GET requests.</li><li><strong>Leaving RDS Publicly Accessible:</strong> During testing, it is tempting to open your database to the whole internet. In production, I kept RDS private inside the same VPC as my Express server and configured the Security Group to only accept traffic on port 5432 from my backend server.</li><li><strong>Migrating Old Files Manually:</strong> I had hundreds of existing product images sitting in my old repository. Instead of uploading them one by one, I ran a single AWS CLI command from my laptop (aws s3 sync ./public/assets s3://my-bucket-name/products) and moved everything in under two minutes.</li></ol><p>The Results After Migrating</p><p>The difference was night and day:</p><ul><li><strong>Image &amp; Video Load Times:</strong> Dropped from <strong>4+ seconds</strong> down to <strong>under 300 milliseconds</strong> thanks to CloudFront edge caching.</li><li><strong>Server CPU &amp; RAM:</strong> Dropped by nearly <strong>70%</strong> because my Node.js server only handles lightweight JSON data now.</li><li><strong>Peace of Mind:</strong> Whether 10 people or 10,000 people browse my catalog at the same time, S3 and CloudFront absorb the traffic effortlessly.</li></ul><p>If your full-stack project is starting to feel sluggish as you grow, don’t just throw money at a bigger server — separate your storage, your CDN, and your database. Your users (and your server bill) will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf37f30e58e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How a Modern CI/CD Pipeline Actually Works: From Local Code to Kubernetes Production]]></title>
            <link>https://medium.com/@shivasingh.1dev/how-a-modern-ci-cd-pipeline-actually-works-from-local-code-to-kubernetes-production-b0b3a122481b?source=rss-ae6be363234d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0b3a122481b</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[shivatech]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 12:49:56 GMT</pubDate>
            <atom:updated>2026-11-10T12:49:56.499Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HAFjXKk4FeXP52A3nWpYpg.png" /></figure><p>When you write code on your laptop, how does it securely and safely reach millions of users in production at top tech companies? Most tutorials make it look like a simple script running a couple of commands. In reality, a production-grade CI/CD pipeline is a robust, multi-step engineering system designed to catch errors early, guarantee artifact integrity, and manage risk without causing downtime.</p><p>Here is a detailed breakdown of the entire end-to-end journey.</p><h3>1. Catching Mistakes Locally Before Pushing</h3><p>Before any code reaches GitHub, engineers want to catch simple mistakes right on their development machine.</p><ul><li><strong>Pre-commit hooks</strong> run automated checks locally right before a git commit is created.</li><li>Tools like <strong>gitleaks</strong> scan your staged changes to ensure you didn’t accidentally commit sensitive information like an AWS secret key.</li><li>While local checks are fast and helpful, they can be bypassed or misconfigured. That is why they are only the first line of defense, not the final security gate.</li></ul><h3>2. Pull Requests and Automated CI Validation</h3><p>Once you push your branch and open a pull request, the code goes through centralized validation using Continuous Integration tools like <strong>GitHub Actions</strong>.</p><ul><li>Every pull request runs the exact same automated checks: formatting validation, unit tests, security scans, and secret detection.</li><li>Repositories enforce <strong>branch protection rules</strong> so that nobody can merge code unless all required checks pass successfully.</li><li>These workflows execute on <strong>runners</strong> — either fresh virtual machines hosted by GitHub or self-hosted servers managed by the company for specific hardware needs or private network access.</li></ul><h3>3. Building Artifacts and Optimizing Docker</h3><p>Once the pull request is approved and merged into the main branch, the focus shifts from testing code to building a deployable artifact.</p><ul><li><strong>Build Once, Deploy Many:</strong> A golden rule of production is that you build your application artifact exactly once. Whether it is a JAR file or a container image, that exact build output moves forward through staging and production.</li><li><strong>Docker Multi-Stage Builds:</strong> Building code often requires heavy tools like compilers and test utilities. Using multi-stage builds, the first stage builds the application using the full toolbox, while the final runtime stage only copies over the compiled binary and necessary production files. This keeps production images lean and secure.</li><li><strong>Caching:</strong> To speed up slow builds, pipelines cache package manager downloads and Docker layers so that unchanged parts of the application are never rebuilt from scratch.</li></ul><h3>4. Secure AWS Authentication Using OIDC</h3><p>Instead of storing permanent AWS access keys inside GitHub secrets — which can leak and cause security breaches — modern workflows use <strong>OpenID Connect (OIDC)</strong>:</p><ol><li>GitHub Actions requests a temporary identity token directly from GitHub.</li><li>AWS checks that token against IAM trust policies to verify the repository and branch.</li><li>If trusted, AWS grants <strong>temporary credentials</strong> following the principle of least privilege, allowing the workflow to push images safely to <strong>Amazon ECR (Elastic Container Registry)</strong>.</li></ol><h3>5. Ensuring Image Trust, Scanning, and SBOMs</h3><p>Before an image moves anywhere near production, engineering teams must verify its security and origin:</p><ul><li><strong>Tags vs. Digests:</strong> Git commit SHAs make great human-readable tags for traceability, but image <strong>digests (SHA-256)</strong> point to the exact immutable manifest and content. Staging and production rely on digests to guarantee they run the exact same code.</li><li><strong>Vulnerability Scanning:</strong> Tools like <strong>Trivy</strong> scan the image packages for known security flaws.</li><li><strong>Software Bill of Materials (SBOM):</strong> An SBOM provides an ingredient list of every software component inside the image so security teams can quickly track down vulnerabilities.</li><li><strong>Build Provenance:</strong> Cryptographic attestations prove where an artifact came from, which repository it was built in, and which workflow produced it.</li></ul><h3>6. GitOps and Staging with Argo CD</h3><p>With a verified image sitting securely in ECR, it is time to deploy it to staging. Instead of having the CI pipeline directly run commands against the Kubernetes cluster, modern teams use a <strong>GitOps</strong> model:</p><ul><li>The desired deployment state — including the exact image digest — is stored in a Git repository.</li><li><strong>Argo CD</strong> constantly monitors that Git repository and compares it with what is actually running inside the cluster. If Git says version two should run, but Kubernetes is still running version one, Argo CD automatically synchronizes the environment to match Git.</li></ul><h3>7. Kubernetes Probes and Application Testing</h3><p>When a new container starts in a Kubernetes Pod, traffic shouldn’t flood in immediately. Kubernetes uses specialized health probes to manage this:</p><ul><li><strong>Startup Probe:</strong> Checks if the application has finished booting up.</li><li><strong>Readiness Probe:</strong> Determines if the app is ready to accept real user traffic.</li><li><strong>Liveness Probe:</strong> Continuously checks if the container is healthy or needs to be restarted due to a deadlock.</li></ul><p>Once probes pass, teams run automated <strong>smoke tests</strong>, <strong>integration tests</strong>, and <strong>end-to-end browser flows</strong> (using tools like Playwright) to verify that databases and core business logic work properly.</p><h3>8. Managing Zero-Downtime Database Migrations</h3><p>Deploying new application versions alongside database changes can easily break production if handled poorly. Teams use the <strong>Expand and Contract</strong> pattern:</p><ol><li><strong>Expand:</strong> Add new database columns while keeping old ones intact.</li><li><strong>Dual Writes:</strong> Deploy an application version that is compatible with both the old and new schema structures.</li><li><strong>Backfill:</strong> Populate historical data into the new columns.</li><li><strong>Switch &amp; Contract:</strong> Shift the application to rely entirely on the new structure, and clean up the old columns only after all legacy instances are completely gone.</li></ol><h3>9. Production Release Strategies</h3><p>Moving a release from staging to live production is the riskiest step. To protect users from downtime or bugs, teams rely on specific deployment strategies:</p><ul><li><strong>Rolling Deployments:</strong> Kubernetes gradually replaces old pods with new ones little by little.</li><li><strong>Blue-Green Deployments:</strong> A complete parallel environment (Green) is prepared alongside the live environment (Blue) before instantly switching traffic over once verified.</li><li><strong>Canary Deployments:</strong> A tiny fraction of traffic (like 5%) is routed to the new version first. Using tools like <strong>Argo Rollouts</strong> integrated with an AWS Application Load Balancer (ALB), traffic weights are adjusted dynamically based on real-world behavior.</li><li><strong>Automated Canary Analysis:</strong> Systems like <strong>Prometheus</strong> monitor error rates and latency in real time. If error thresholds spike, the canary rollout automatically aborts.</li><li><strong>Feature Flags:</strong> Code can be safely deployed to production while keeping new features hidden behind feature flags until marketing or product teams are ready to flip the switch.</li></ul><h3>10. Observability, Alerting, and Recovery</h3><p>Production monitoring gives engineers real-time visibility into system health using the three pillars: <strong>Metrics</strong> (numbers over time like latency and CPU usage), <strong>Logs</strong> (individual event histories), and <strong>Traces</strong> (following a single request across microservices), often standardized through <strong>OpenTelemetry</strong>.</p><ul><li><strong>Alerting:</strong> If error rates spike at two in the morning, alerting tools notify the on-call engineer with exact metadata, including commit SHAs and image digests.</li><li><strong>Rollback &amp; Recovery:</strong> If a release proves unhealthy, teams don’t panic or scramble to rewrite code. They simply revert the desired image digest in Git for Argo CD to reconcile, or abort an active canary rollout, restoring stability safely and quickly.</li></ul><h3>Summary</h3><p>At its core, a production CI/CD pipeline is not just a random collection of tools like GitHub Actions, Docker, and Kubernetes. It is a disciplined engineering system built to control change, establish artifact trust, manage risk across environments, and ensure you can recover safely when things go wrong.</p><p>So yeah this is pretty much if you got a knowledge from this article than gimme a clap and do comments and you can also follow me on <a href="https://x.com/Shivatwd1">X</a> &amp; <a href="https://www.linkedin.com/in/shiva-singh-b2104a373/">Linkedin</a></p><p>Read-more my articles:<br><a href="https://medium.com/@shivasingh.1dev/learn-linux-on-windows-the-easy-way-step-by-step-wsl-ubuntu-guide-for-beginners-190d980c5336">https://medium.com/@shivasingh.1dev/learn-linux-on-windows-the-easy-way-step-by-step-wsl-ubuntu-guide-for-beginners-190d980c5336</a></p><p><a href="https://medium.com/@shivasingh.1dev/what-is-docker-commands-docker-networking-and-docker-volumes-6e1e3676a96f">https://medium.com/@shivasingh.1dev/what-is-docker-commands-docker-networking-and-docker-volumes-6e1e3676a96f</a></p><p><a href="https://medium.com/@shivasingh.1dev/docker-explained-what-it-is-how-it-works-internally-and-essential-commands-5c0e5c449595">https://medium.com/@shivasingh.1dev/docker-explained-what-it-is-how-it-works-internally-and-essential-commands-5c0e5c449595</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0b3a122481b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Deployment Strategies Explained with Hands-On Examples]]></title>
            <link>https://medium.com/@shivasingh.1dev/kubernetes-deployment-strategies-explained-with-hands-on-examples-2c120c191426?source=rss-ae6be363234d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c120c191426</guid>
            <category><![CDATA[blue-green-deployment]]></category>
            <category><![CDATA[rolling-updates]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kubernete-strategies]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[shivatech]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 07:42:20 GMT</pubDate>
            <atom:updated>2026-09-21T07:42:20.251Z</atom:updated>
            <content:encoded><![CDATA[<p>Deploying a new version of an application sounds simple until the application is already being used by real users.</p><p>Suppose version 1 of an application is currently running:</p><pre>Version 1<br>   |<br>   ├── Pod<br>   ├── Pod<br>   └── Pod</pre><p>Now version 2 is ready.</p><p>The question is not just <strong>“How do I deploy version 2?”</strong></p><p>The more important question is:</p><p><strong>“How do I move from version 1 to version 2 without creating unnecessary downtime or exposing every user to an untested release?”</strong></p><p>This is where deployment strategies come into the picture.</p><p>Kubernetes gives us the primitives to control application rollouts. A Deployment manages ReplicaSets and Pods, and when the Pod template changes for example, when the container image changes Kubernetes can create a new ReplicaSet and move the application toward the desired state. Kubernetes directly supports two Deployment strategies:<strong> Recreate </strong>and <strong>RollingUpdate</strong>. Patterns such as <strong>Blue-Green</strong> and <strong>Canary</strong> are built using multiple Kubernetes resources and traffic-routing mechanisms.</p><p>In this project, I wanted to understand these strategies by actually implementing them rather than only reading their definitions.</p><p>I built the experiments on an AWS EC2 instance using Docker, Kind, and Kubernetes.</p><p>The strategies covered in this project are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*QdqS8cJuuLUyHih1bFLN-g.gif" /></figure><ul><li>Recreate</li><li>Rolling Update</li><li>Rollback</li><li>Blue-Green</li><li>Simple Canary</li></ul><p>The complete implementation is available in my GitHub repository:</p><p><strong>GitHub:</strong> <a href="https://github.com/SHIVA-SINGHx/k8s-deployment-strategies">https://github.com/SHIVA-SINGHx/k8s-deployment-strategies</a></p><h3>1. The Problem We Are Trying to Solve</h3><p>Let’s start with a simple example.</p><p>Imagine an online shopping application is currently running version 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*BqcEW2-MvU1F1Jr5Eu-ZZw.png" /></figure><p>Now the development team releases version 2.</p><p>Maybe it contains:</p><ul><li>a new UI</li><li>a bug fix</li><li>a new feature</li><li>a database change</li><li>or simply a newer container image.</li></ul><p>We need to replace V1 with V2.</p><p>The simplest approach would be:</p><pre>Stop V1<br>   ↓<br>Deploy V2</pre><p>But the problem is obvious.</p><p>Between stopping V1 and starting V2, there may be no application available. That is downtime Instead we can control this transition in different ways.</p><p>For example:</p><pre>Recreate<br>V1 → stop everything → V2</pre><pre>Rolling Update<br>V1 → V1/V2 → V2</pre><pre>Blue-Green<br>V1 + V2 → switch traffic</pre><pre>Canary<br>V1 + small V2 traffic → gradually increase V2</pre><p>These are different approaches to the same fundamental problem:</p><p><strong>How should a new version reach production?</strong></p><h3>2. A Few Kubernetes Concepts Before We Start</h3><p>Before looking at deployment strategies, it helps to understand the Kubernetes objects involved.</p><h3>Pod</h3><p>A Pod is the smallest deployable unit in Kubernetes.</p><p>For a simple application, a Pod might contain one application container:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*dQVxwqXGI2es4TEQYTBT3w.png" /></figure><pre>Pod<br> |<br> └── Container<br>       |<br>       └── Online Shop</pre><p>Pods are not normally something we manually manage one by one.</p><p>We use controllers such as Deployments to manage them.</p><h3>3. Deployment</h3><p>A Deployment describes the desired state of an application.</p><p>For example:</p><pre>replicas: 3</pre><p>means that we want three Pods running.</p><p>The simplified relationship is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*Mxb54BQbEjCY_CXD3nUqTQ.png" /></figure><pre>Deployment<br>     |<br>     v<br>ReplicaSet<br>     |<br>     +---------+---------+<br>     |         |         |<br>    Pod       Pod       Pod</pre><p>When we change the Pod template for example, change the container image the Deployment creates a new ReplicaSet and manages the transition between the old and new Pods.</p><p>This behavior is what makes Deployment strategies possible.</p><h3>4. Service</h3><p>There is another important problem.</p><p>Pods can be recreated, which means their IP addresses are not something we should treat as permanent endpoints.</p><p>A Service gives us a stable way to reach a group of Pods.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*cer06MGdb4sfrcD-qoJzPA.png" /></figure><pre>Service<br>                |<br>       -------------------<br>       |        |        |<br>      Pod      Pod      Pod</pre><p>The Service uses labels and selectors to determine which Pods should receive traffic.</p><p>For example:</p><pre>selector:<br>  app: online-shop</pre><p>If the Pods have:</p><pre>labels:<br>  app: online-shop</pre><p>the Service can route traffic to them.</p><p>This becomes especially important when Pods are changing during a Rolling Update or when different versions are running simultaneously.</p><h3>5. Ingress</h3><p>For HTTP applications we often need another layer in front of our Services.</p><p>That is where Ingress comes in.</p><p>Ingress defines HTTP/HTTPS routing rules such as:</p><pre>example.com/<br>       |<br>       v<br>     Service A</pre><pre>example.com/api<br>       |<br>       v<br>     Service B</pre><p>An Ingress resource defines the routing rules while an Ingress Controller actually implements those rules.</p><p>In my Canary experiment I used the NGINX Ingress Controller.</p><p>For this project however, Ingress was useful because I wanted to understand how traffic can enter the cluster and reach different application versions.</p><h3>6. My Kubernetes Lab</h3><p>I wanted to run these experiments somewhere closer to a real Linux environment instead of only using a local laptop.</p><p>So I used an AWS EC2 instance. Inside the EC2 instance I installed Docker and Kind.</p><p>Kind stands for <strong>Kubernetes IN Docker</strong>.</p><p>Instead of creating separate virtual machines for Kubernetes nodes Kind runs the Kubernetes nodes as Docker containers.</p><p>My cluster contains:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*8aH1PGZYRQINfSwXbIHUHw.png" /></figure><pre>AWS EC2<br>   |<br>   └── Docker<br>        |<br>        └── Kind Cluster<br>              |<br>              ├── Control Plane<br>              ├── Worker<br>              └── Worker</pre><p>This setup gave me enough of a real Kubernetes environment to observe Deployments, Pods, Services and Ingress while keeping the infrastructure relatively simple.</p><h3>7. Setting Up the Cluster</h3><p>I first created a medium-sized EC2 environment with around 30 GiB of RAM.</p><p>After connecting to the instance I cloned the project:</p><pre>git clone https://github.com/SHIVA-SINGHx/k8s-deployment-strategies.git</pre><p>Then:</p><pre>cd k8s-deployment-strategies</pre><p>The repository contains separate directories for the different deployment experiments.</p><p>I first moved into the Kind cluster setup:</p><pre>cd kind-cluster</pre><p>The repository contains an installation script, so I gave it execute permission:</p><pre>chmod 700 install.sh</pre><p>and ran it:</p><pre>./install.sh</pre><p>After configuring Docker access:</p><pre>newgrp docker</pre><p>I created the Kubernetes cluster:</p><pre>kind create cluster \<br>  --config kind-config.yml \<br>  --name tws-kind-cluster</pre><p>Then I verified the nodes:</p><pre>kubectl get nodes</pre><p>The important thing at this point is that all nodes should show. Once the cluster was ready I could start testing deployment strategies.</p><h3>8. Recreate Deployment</h3><p>Let’s start with the simplest strategy.</p><h3>What is Recreate?</h3><p>The Recreate strategy takes a very straightforward approach:</p><p><strong>Terminate the existing version before creating the new version.</strong></p><p>The flow looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*SxiJ5ZLQSAxOU_ar2_FmLw.png" /></figure><pre>V1 Pods<br>   |<br>   | terminate<br>   v<br>No V1 Pods<br>   |<br>   | create<br>   v<br>V2 Pods</pre><p>Kubernetes documents this behavior directly with <strong>strategy.type: Recreate</strong>all existing Pods are terminated before the new Pods are created during an upgrade.</p><p>This makes Recreate easy to understand and easy to reason about. But there is an obvious trade-off.</p><p>During the transition the application may have no available Pods.</p><h3>9. Recreate — Advantages</h3><h3>1. Very simple</h3><p>There is no overlap between the old and new versions.</p><p>You don’t have:</p><pre>V1 + V2</pre><p>at the same time.</p><p>The transition is simply:</p><pre>V1 → V2</pre><h3>2. Avoids running two versions simultaneously</h3><p>Some applications may not work correctly if two versions run at the same time.</p><p>For example, if an application has a compatibility constraint between its application version and another component, running both versions simultaneously may be undesirable.</p><h3>3. Predictable transition</h3><p>The behavior is easy to understand:</p><pre>Stop old<br>Start new</pre><h3>10. Recreate — Disadvantages</h3><p>The biggest problem is downtime.</p><p>Imagine:</p><pre>10:00:00 → V1 running</pre><pre>10:00:02 → V1 Pods terminated</pre><pre>10:00:02 - 10:00:06 → No application Pods</pre><pre>10:00:06 → V2 starts</pre><p>During that gap:</p><pre>Users → Application<br>          ❌</pre><p>For an application that needs continuous availability, this can be a problem.</p><p>There is also no gradual exposure of the new version.</p><p>You don’t get:</p><pre>10% V2<br>25% V2<br>50% V2</pre><p>The transition is effectively all-or-nothing.</p><h3>11. Implementing Recreate in My Project</h3><p>I moved into the deployment strategy directory and created the namespace:</p><pre>kubectl apply -f recreate-namespace.yml</pre><p>Then I created the Deployment:</p><pre>kubectl apply -f recreate-deployment.yml</pre><p>I checked the Pods:</p><pre>kubectl get pods -n recreate-ns</pre><p>Next I created the Service:</p><pre>kubectl apply -f recreate-svc.yml</pre><p>To see all resources:</p><pre>kubectl get all -n recreate-ns</pre><p>I then exposed the application through port forwarding:</p><pre>kubectl port-forward \<br>  --address 0.0.0.0 \<br>  svc/recreate-service \<br>  3000:3000 \<br>  -n recreate-ns &amp;</pre><p>Since the Kubernetes cluster was running inside an EC2 instance, I also opened port 3000 in the EC2 Security Group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*-mlHG_FybbNhL6-nuXtdAg.png" /></figure><p>At this point the first version of the application was accessible.</p><h3>12. Watching the Recreate Rollout</h3><p>I opened another terminal and ran:</p><pre>watch kubectl get pods -n recreate-ns</pre><p>This was useful because I could actually watch Kubernetes change the Pods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*hfe8Q2dxtO5coUQliiSCzw.png" /></figure><p>Then I changed the container image:</p><pre>kubectl set image deployment/online-shop \<br>  online-shop=amitabhdevops/online_shop_without_footer \<br>  -n recreate-ns</pre><p>Now Kubernetes started replacing the old version.</p><p>Because this Deployment was configured for Recreate I could see the old Pods disappear before the new version became available. That was the main observation I wanted from this experiment.</p><p>The application was updated but there was a period where it was unavailable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*M-99E23q4qxmaW_XjzZYvw.png" /></figure><p>That is the key characteristic of Recreate.</p><p>After finishing the experiment make sure you delete this</p><pre>kubectl delete -f .</pre><h3>13. Rolling Update</h3><p>Rolling Update solves the main availability problem we just saw.</p><p>Instead of removing all old Pods first, Kubernetes gradually replaces them with new Pods.</p><p>Suppose we have three replicas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*Oaf0mu9YayHD-XdIPXMWDw.png" /></figure><pre>V1  V1 </pre><p>During the rollout:</p><pre>V2  V1  V1</pre><pre>V2  V2  V1</pre><pre>V2  V2  </pre><p>The exact sequence depends on the Deployment configuration.</p><p>The important idea is that the old and new ReplicaSets can temporarily coexist while Kubernetes moves the workload toward the new version.</p><p>RollingUpdate is the default Deployment strategy in Kubernetes.</p><h3>14. How Rolling Update Actually Works</h3><p>This is where ReplicaSets become important.</p><p>Suppose the current Deployment has:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*C--YanZJgPoSnCFUS1cdSw.png" /></figure><pre>ReplicaSet V1<br>   |<br>   +-- Pod V1<br>   +-- Pod V1<br>   +-- Pod V1</pre><p>When we change the image, Kubernetes creates another ReplicaSet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*pC_a4Q4mpjpfLomm7NrGIw.png" /></figure><pre>ReplicaSet V1          ReplicaSet V2<br>     |                      |<br>   V1 V1 V1                V2</pre><p>Then it gradually changes the number of replicas:</p><pre>V1: 3 → 2<br>V2: 1 → 2</pre><p>Then:</p><pre>V1: 2 → 1<br>V2: 2 → 3</pre><p>Finally:</p><pre>V1: 0<br>V2: 3</pre><p>The Deployment controller manages this process.</p><h3>15. MaxUnavailable and MaxSurge</h3><p>Two settings are particularly important when tuning a Rolling Update:</p><pre>strategy:<br>  type: RollingUpdate<br>  rollingUpdate:<br>    maxUnavailable: 1<br>    maxSurge: 1</pre><h3>MaxUnavailable</h3><p>This tells Kubernetes the maximum number of Pods that can be unavailable during the update.</p><p>For example:</p><pre>replicas = 3<br>maxUnavailable = 1</pre><p>means one Pod can be unavailable while the rollout is happening.</p><h3>MaxSurge</h3><p>This controls how many additional Pods can temporarily be created above the desired replica count.</p><p>For example:</p><pre>replicas = 3<br>maxSurge = 1</pre><p>Kubernetes can temporarily have four Pods during the update.</p><p>So:</p><pre>V1 V1 V1</pre><pre>       ↓</pre><pre>V1 V1 V1 V2</pre><p>Then Kubernetes removes old Pods as the new Pods become available.</p><p>The values can be specified as numbers or percentages. Kubernetes currently documents a default of 25% for both settings.</p><h3>16. Rolling Update — Advantages</h3><h3>Reduced downtime</h3><p>The main benefit is that the application can remain available during the rollout when the Deployment is properly configured and the application has enough replicas.</p><h3>Gradual replacement</h3><p>Instead of switching everything at once, Pods are replaced progressively.</p><h3>Built-in Kubernetes support</h3><p>RollingUpdate is a native Deployment strategy. There is no need to build the basic rollout mechanism yourself.</p><h3>Easy rollback</h3><p>Because Deployment revisions are maintained, a problematic rollout can be reverted.</p><h3>17. Rolling Update — Disadvantages</h3><p>Rolling Update is not automatically perfect.</p><h3>1. Old and new versions can coexist</h3><p>During the rollout:</p><pre>V1 + V2</pre><p>May both be serving traffic. Your application should therefore tolerate this situation.</p><h3>2. Requires enough resources</h3><p>If you configure a large <strong>maxSurge</strong>, Kubernetes may temporarily create additional Pods. That means additional CPU and memory consumption.</p><h3>3. Database changes need care</h3><p>Application code and database schema changes need to be compatible during the transition because both versions may exist simultaneously.</p><p>This is one of the reasons deployment strategy is not just a Kubernetes configuration problem it also depends on how the application is designed.</p><h3>18. Implementing Rolling Update in My Project</h3><p>I created the namespace:</p><pre>kubectl apply -f rolling-namespace.yml</pre><p>Then applied the manifests:</p><pre>kubectl apply -f .</pre><p>I exposed the application:</p><pre>kubectl port-forward \<br>  --address 0.0.0.0 \<br>  svc/rolling-update-service \<br>  3000:3000 \<br>  -n rolling-ns &amp;</pre><p>The first version of my application contained the footer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*sxl8fcsBhg548BgLEYSL7Q.png" /></figure><p>I wanted to deploy the second version without the footer.</p><p>So I edited:</p><pre>vim rolling-update-deployment.yaml</pre><p>and changed the image to:</p><pre>online_shop_without_footer</pre><p>Then:</p><pre>kubectl apply -f rolling-update-deployment.yaml</pre><p>Kubernetes detected that the Pod template had changed and started a new rollout. I could observe the Pods while this was happening.</p><p>Unlike Recreate, the application did not need to completely disappear before the new version appeared.</p><p>Kubernetes gradually moved the Deployment from V1 to V2.</p><p>I could also verify the rollout with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*9qlTLVdDVAt8tikF2c8sew.png" /></figure><pre>kubectl rollout status deployment/online-shop</pre><p>This is the part of the experiment where the difference between Recreate and RollingUpdate becomes very obvious.</p><h3>19. Rollback</h3><p>Deployment strategy and rollback are closely related but they are not the same thing.</p><p>A deployment strategy answers:</p><blockquote><strong><em>How do I release the new version?</em></strong></blockquote><p>Rollback answers:</p><blockquote><strong><em>What do I do if the new version causes a problem?</em></strong></blockquote><p>Suppose:</p><pre>V1 → V2</pre><p>but V2 has a serious bug.</p><p>Kubernetes keeps Deployment revision history allowing us to return to an earlier revision.</p><p>Check the history:</p><pre>kubectl rollout history deployment/online-shop</pre><p>Then rollback:</p><pre>kubectl rollout undo deployment/online-shop</pre><p>Or rollback to a specific revision:</p><pre>kubectl rollout undo deployment/online-shop --to-revision=1</pre><p>Then:</p><pre>kubectl rollout status deployment/online-shop</pre><p>This is particularly useful with Rolling Updates because the rollout can be reversed without manually rebuilding the previous Deployment configuration.</p><h3>20. Blue-Green Deployment</h3><p>Rolling Update gradually changes the Pods inside the same release.</p><p>Blue-Green takes a different approach.</p><p>Instead of gradually replacing the old application, we run <strong>two environments</strong>.</p><pre>BLUE  → Current version</pre><pre>GREEN → New version</pre><p>For example:</p><pre>Users<br>                  |<br>                  v<br>               BLUE<br>                V1</pre><p>At the same time:</p><pre>GREEN<br>                 V2</pre><p>The Green environment can be deployed and tested while Blue continues serving the current users.</p><p>Once Green is ready, traffic can be switched.</p><p>Conceptually:</p><pre>Users → BLUE → V1<br></pre><pre>After:</pre><pre>Users → GREEN → V2</pre><p>The important thing is that the two versions are separated.</p><h3>21. Blue-Green — Advantages</h3><h3>1. Very fast switch</h3><p>Once the new environment is ready, traffic can be redirected to it.</p><p>You don’t have to wait for every old Pod to gradually become a new Pod.</p><h3>2. Easy rollback conceptually</h3><p>If Green has a problem:</p><pre>GREEN ❌</pre><p>traffic can be directed back to:</p><pre>BLUE ✅</pre><p>assuming the previous environment is still healthy and available.</p><h3>3. Full environment testing</h3><p>The new version can be tested independently before receiving production traffic.</p><h3>22. Blue-Green — Disadvantages</h3><h3>1. More infrastructure</h3><p>For a period of time, you’re running both:</p><pre>BLUE<br>GREEN</pre><p>That means more Pods and therefore more resource usage.</p><h3>2. Database changes can still be difficult</h3><p>Running two application versions does not magically solve database compatibility.</p><p>If V2 requires a database schema that V1 cannot understand, switching between them becomes more complicated.</p><h3>3. Traffic switching needs to be designed</h3><p>In a real environment, you need a traffic layer capable of switching between the two versions.</p><p>That could involve:</p><ul><li>Services</li><li>Ingress</li><li>Gateway API</li><li>Load balancers</li><li>Service mesh</li><li>DNS</li></ul><h3>23. Implementing Blue-Green in My Project</h3><p>I created a separate namespace:</p><pre>kubectl apply -f blue-green-ns.yml</pre><p>I first deployed the Blue environment:</p><pre>kubectl apply -f online-shop-without-footer-blue-deployment.yaml</pre><p>Then I exposed the Blue application:</p><pre>kubectl port-forward \<br>  --address 0.0.0.0 \<br>  svc/online-shop-blue-deployment-service \<br>  30001:3001 \<br>  -n blue-green-ns &amp;</pre><p>I opened port 30001 in the EC2 Security Group so I could access the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*GwlSediPOL9gSl56QrRTsA.png" /></figure><p>Then I deployed the second environment for the new version and exposed it separately:</p><pre>kubectl port-forward \<br>  --address 0.0.0.0 \<br>  svc/online-shop-green-deployment-service \<br>  30000:3000 \<br>  -n blue-green-ns &amp;</pre><p>Now I had two environments:</p><pre>Blue  → V1<br>Green → V2</pre><p>I could access them independently and verify the difference between the two versions.</p><p>For the lab, I used separate Services and port-forwarding so that I could see both versions directly.</p><p>In a production implementation the important part would be the traffic switch itself for example changing which version a Service, Ingress, or Gateway sends production traffic to.</p><p>After completing the experiment:</p><pre>kubectl delete -f .</pre><h3>24. Canary Deployment</h3><p>Canary is based on a different idea.</p><p>Instead of replacing the old version completely, we introduce the new version to only a subset of users or traffic.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*D4ufNW5ldckhqFUaRWDemw.png" /></figure><pre>Users<br>                |<br>       -------------------<br>       |                 |<br>      V1                 V2<br>     95%                 5%</pre><p>If V2 behaves correctly, we can gradually increase its exposure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*CJQAoBHofSvQo0cenOZFfg.png" /></figure><pre>95% V1 / 5% V2<br>        ↓<br>80% V1 / 20% V2<br>        ↓<br>50% V1 / 50% V2<br>        ↓<br>0% V1 / 100% V2</pre><p>This gives us an opportunity to observe the new release before exposing it to everyone.</p><p>Kubernetes documents Canary as a pattern where multiple Deployments represent different releases. For more precise traffic percentages, Kubernetes also documents using Gateway API <strong>HTTPRoute</strong> for traffic splitting.</p><h3>25. Canary — Advantages</h3><h3>Smaller blast radius</h3><p>If V2 has a bug, only the users receiving V2 are initially affected.</p><h3>Real traffic testing</h3><p>The new version can receive real requests instead of only synthetic testing.</p><h3>Gradual release</h3><p>The rollout can happen in stages.</p><h3>Easy to stop</h3><p>If the canary behaves badly, its Deployment can be scaled down while the stable Deployment continues running.</p><h3>26. Canary — Disadvantages</h3><h3>More complicated traffic management</h3><p>The difficult part isn’t creating two Deployments. The difficult part is deciding:</p><blockquote><em>Which users should receive which version?</em></blockquote><h3>Monitoring becomes important</h3><p>You need to watch things such as:</p><ul><li>error rate</li><li>latency</li><li>CPU/memory</li><li>application logs</li><li>HTTP status codes</li><li>business metrics</li></ul><h3>Replica count is not precise traffic splitting</h3><p>This is important.</p><p>Suppose we have:</p><pre>V1 = 3 replicas<br>V2 = 1 replica</pre><p>It is tempting to say:</p><pre>75% V1<br>25% V2</pre><p>but Kubernetes does not guarantee that exact user traffic percentage simply because the replica ratio is 3:1.</p><p>For precise traffic percentages, you need appropriate traffic-management capabilities.</p><h3>27. My Simple Canary Implementation</h3><p>For my experiment I wanted the two versions to be visually obvious.</p><p>So I used:</p><pre>NGINX = V1</pre><pre>Apache = V2</pre><p>I first installed the NGINX Ingress Controller:</p><pre>kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.8.2/deploy/static/provider/kind/deploy.yaml</pre><p>Because this was a Kind environment I also patched the controller:</p><pre>kubectl patch deployment ingress-nginx-controller \<br>  -n ingress-nginx \<br>  --type=json \<br>  -p=&#39;[{&quot;op&quot;: &quot;remove&quot;, &quot;path&quot;: &quot;/spec/template/spec/nodeSelector&quot;}]&#39;</pre><p>Now the cluster had an Ingress Controller capable of processing the Ingress resources I created.</p><h3>28. Creating the Canary Applications</h3><p>I created a namespace:</p><pre>kubectl apply -f namespace.yaml</pre><p>Then configuration for the NGINX application:</p><pre>kubectl apply -f nginx-configmap.yaml</pre><p>and Apache:</p><pre>kubectl apply -f apache-configmap.yaml</pre><p>Then I deployed both applications:</p><pre>kubectl apply -f nginx-deployment.yaml</pre><pre>kubectl apply -f apache-deployment.yaml</pre><p>Finally:</p><pre>kubectl apply -f ingress.yaml</pre><p>I checked the Ingress:</p><pre>kubectl get ing -n simple-canary</pre><p>Then exposed the Ingress Controller:</p><pre>kubectl port-forward \<br>  -n ingress-nginx \<br>  svc/ingress-nginx-controller \<br>  8080:80 \<br>  --address 0.0.0.0 &amp;</pre><h3>29. Controlling Which Version Is Active</h3><p>For the simple experiment, I used scaling to control the number of Pods.</p><p>For example:</p><pre>kubectl scale deployment nginx-deployment \<br>  -n simple-canary \<br>  --replicas=3</pre><p>and:</p><pre>kubectl scale deployment apache-deployment \<br>  -n simple-canary \<br>  --replicas=0</pre><p>Now the state was:</p><pre>NGINX<br>3 Pods</pre><pre><br>Apache<br>0 Pods</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*oQnIbusesnwXHgyEYrCK6Q.png" /></figure><p>So requests were handled by the NGINX version.</p><p>Then I could reverse the setup:</p><pre>NGINX<br>0 Pods</pre><pre>Apache<br>3 Pods</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*c-w4s4fCHAn4u0OcIHsYRQ.png" /></figure><p>and the Apache version became active.</p><p>This experiment helped me understand the basic idea of having multiple release tracks.</p><p>However this is worth emphasizing:</p><p><strong>This is a simple Canary demonstration, not precise percentage-based traffic splitting.</strong></p><p>For example if I want:</p><pre>90% V1<br>10% V2</pre><p>I should not simply assume that setting replica counts to 9 and 1 guarantees exactly 90/10 traffic.</p><p>For precise HTTP traffic splitting a routing layer such as Gateway API a capable Ingress implementation, or a service mesh can be used.</p><h3>30. The Difference Between All Four Strategies</h3><p>After implementing them, I found it easier to think about the strategies as four different answers to one question:</p><p><strong>“How aggressively should I move users from V1 to V2?”</strong></p><h3>Recreate</h3><pre>V1<br> ↓<br>STOP<br> ↓<br>V2</pre><p>Everything is replaced.</p><h3>Rolling Update</h3><pre>V1 V1 V1<br> ↓<br>V2 V1 V1<br> ↓<br>V2 V2 V1<br> ↓<br>V2 V2 V2</pre><p>The replacement happens gradually.</p><h3>Blue-Green</h3><pre>BLUE  → V1<br>GREEN → V2</pre><pre>       ↓</pre><pre>Switch traffic</pre><p>Two environments exist and traffic moves from one to the other.</p><h3>Canary</h3><pre>V1 → most traffic<br>V2 → small traffic</pre><pre>       ↓</pre><pre>increase V2 gradually</pre><p>Only a portion of users are initially exposed to the new version.</p><h3>31. When Would I Use Each Strategy?</h3><p>There isn’t one strategy that is correct for every application.</p><h3>Recreate</h3><p>Useful when the old and new versions should not run simultaneously or when temporary downtime is acceptable.</p><h3>Rolling Update</h3><p>A common choice for normal Kubernetes application updates where gradual replacement and availability are desired.</p><h3>Blue-Green</h3><p>Useful when you want two complete environments and a clear switch between the current and new release.</p><h3>Canary</h3><p>Useful when you want to expose a new release gradually and observe its behavior before a full rollout.</p><p>The right choice depends on the application, infrastructure, resource budget, compatibility requirements, monitoring, and how traffic is managed.</p><h3>32. What This Project Taught Me</h3><p>The biggest thing I learned from this project was that Kubernetes deployment strategies are not just YAML configurations.</p><p>They are really <strong>release-management patterns</strong>.</p><p>Kubernetes gives us the building blocks:</p><pre>Deployments<br>Services<br>ReplicaSets<br>Pods<br>Ingress<br>Gateway<br>Labels<br>Selectors</pre><p>and we combine those building blocks to control how an application moves from one version to another. The practical difference only became obvious when I watched the Pods change during the deployments.</p><p>With Recreate I could see the application disappear before the new version appeared.</p><p>With Rolling Update I could watch old and new Pods coexist during the rollout.</p><p>With Blue-Green I could run two versions independently and think about the traffic switch as a separate operation.</p><p>With the simple Canary setup I could run two release tracks and control which one was active.</p><p>That was much more useful to me than simply memorizing four definitions.</p><h3>33. What I Would Add for a Production Setup</h3><p>This project was intentionally built as a learning environment on Kind running inside an AWS EC2 instance.</p><p>A production Kubernetes environment would need considerably more around the deployment itself.</p><p>For example:</p><pre>Git Push<br>   |<br>   v<br>CI/CD Pipeline<br>   |<br>   v<br>Build Container<br>   |<br>   v<br>Container Registry<br>   |<br>   v<br>EKS<br>   |<br>   +---- Deployment<br>   |<br>   +---- Service<br>   |<br>   +---- Gateway / Ingress<br>   |<br>   +---- Monitoring<br>   |<br>   +---- Logging<br>   |<br>   +---- Alerts</pre><p>For a production rollout, I would also want:</p><ul><li>health checks and readiness probes</li><li>automated rollback</li><li>proper load balancing</li><li>TLS</li><li>centralized logging</li><li>metrics and monitoring</li><li>resource requests and limits</li><li>autoscaling</li><li>CI/CD</li><li>image versioning</li><li>secrets management</li><li>proper traffic management for Canary or Blue-Green releases</li></ul><p>That is where deployment strategies become part of a larger DevOps workflow rather than being isolated Kubernetes exercises.</p><h3>34. Final Takeaway</h3><p>A deployment strategy answers a very practical question:</p><p><strong>What should happen between the old version of my application and the new version?</strong></p><p><strong>Recreate says:</strong></p><blockquote><em>Stop the old version first, then start the new one.</em></blockquote><p><strong>Rolling Update says:</strong></p><blockquote><em>Replace the old Pods gradually.</em></blockquote><p><strong>Blue-Green says:</strong></p><blockquote><em>Keep the old and new environments separate, then switch traffic.</em></blockquote><p><strong>Canary says:</strong></p><blockquote><em>Give the new version a small amount of exposure first and increase it gradually.</em></blockquote><p>Understanding these differences is much easier when you actually watch them happen inside a cluster.</p><p><strong>Repository:</strong><br><a href="https://github.com/SHIVA-SINGHx/k8s-deployment-strategies">https://github.com/SHIVA-SINGHx/k8s-deployment-strategies</a></p><p>If you’re learning Kubernetes, I would strongly recommend running these experiments yourself. The moment you watch the Pods change during a rollout these strategies stop feeling like four definitions and start making sense as four different ways of releasing software.</p><p>So yeah this is pretty much if you got a knowledge from this article than gimme a clap and do comments and you can also follow me on <a href="https://x.com/Shivatwd1">X</a> &amp; <a href="https://www.linkedin.com/in/shiva-singh-b2104a373/">Linkedin</a></p><p>Read-more my articles: <br><a href="https://medium.com/@shivasingh.1dev/learn-linux-on-windows-the-easy-way-step-by-step-wsl-ubuntu-guide-for-beginners-190d980c5336">https://medium.com/@shivasingh.1dev/learn-linux-on-windows-the-easy-way-step-by-step-wsl-ubuntu-guide-for-beginners-190d980c5336</a></p><p><a href="https://medium.com/@shivasingh.1dev/what-is-docker-commands-docker-networking-and-docker-volumes-6e1e3676a96f">https://medium.com/@shivasingh.1dev/what-is-docker-commands-docker-networking-and-docker-volumes-6e1e3676a96f</a></p><p><a href="https://medium.com/@shivasingh.1dev/docker-explained-what-it-is-how-it-works-internally-and-essential-commands-5c0e5c449595">https://medium.com/@shivasingh.1dev/docker-explained-what-it-is-how-it-works-internally-and-essential-commands-5c0e5c449595</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c120c191426" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Docker Commands, Docker Networking and Docker Volumes?]]></title>
            <link>https://medium.com/@shivasingh.1dev/what-is-docker-commands-docker-networking-and-docker-volumes-6e1e3676a96f?source=rss-ae6be363234d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e1e3676a96f</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[docker-networking]]></category>
            <category><![CDATA[docker-volume]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-image]]></category>
            <dc:creator><![CDATA[shivatech]]></dc:creator>
            <pubDate>Mon, 12 Jan 2026 17:58:18 GMT</pubDate>
            <atom:updated>2026-01-12T17:58:18.156Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is Part-2 of my Docker learning series. In </em><a href="https://medium.com/@shivasingh.1dev/docker-explained-what-it-is-how-it-works-internally-and-essential-commands-5c0e5c449595"><strong><em>Part-1</em></strong></a><strong><em> </em></strong><em>I covered Docker fundamentals such as Dockerfile, Docker Daemon, Docker CLI, and core Docker concepts.</em></p><p><em>In this article we’ll move into practical Docker usage the commands you actually use every day how containers communicate with each other, and how Docker handles persistent data.</em></p><p>If you’ve only used Docker to run hello-world this article will help you understand how Docker is actually used in real-world projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*izSGlM1WkrbbfLqP_h7JpQ.png" /></figure><h3>1️. Docker Commands You Must Know (Practical &amp; Real-World)</h3><p>Docker has many commands but in real projects you only use a small set of them repeatedly. Let’s focus on the <strong>most important commands</strong> and what they actually do.</p><h3>🔹 Pull an Image</h3><pre>docker pull node:20</pre><p>Downloads an image from Docker Hub. If an image doesn’t exist locally Docker will automatically pull it when you run a container.</p><h3>🔹 List Images</h3><pre>docker images</pre><p>or</p><pre>docker image ls</pre><p>Shows:</p><ul><li>Available images</li><li>Image size (important for optimization)</li></ul><h3>🔹 Run a Container</h3><pre>docker run -d -p 3000:3000 node</pre><p>This single command:</p><ul><li>Pulls the image (if not present)</li><li>Creates a container</li><li>Starts the container</li><li>Maps ports</li></ul><p>-d Detached mode<br> -p Port mapping (host:container)</p><h3>🔹 List Containers</h3><p>Running containers:</p><pre>docker ps</pre><p>All containers (including stopped):</p><pre>docker ps -a</pre><h3>🔹 Stop a Container</h3><pre>docker stop &lt;container_id&gt;</pre><h3>🔹 Remove a Container</h3><pre>docker rm &lt;container_id&gt;</pre><p>⚠️ Container must be stopped first.</p><h3>🔹 Remove an Image</h3><pre>docker rmi &lt;image_id&gt;</pre><h3>🔹 View Container Logs</h3><pre>docker logs &lt;container_id&gt;</pre><p>This is one of the most important commands for debugging in production.</p><h3>🔹 Enter Inside a Running Container</h3><pre>docker exec -it &lt;container_id&gt;</pre><p>or</p><pre>docker exec -it &lt;container_id&gt; </pre><p>Used when you want to:</p><ul><li>Debug a running app</li><li>Inspect file</li><li>Check configurations</li></ul><h3>🔹 Clean Unused Resources</h3><pre>docker system prune</pre><p>Removes:</p><ul><li>Stopped containers</li><li>Unused images</li><li>Unused networks</li></ul><p>Very helpful when disk space is full.</p><h3>2. Docker Networking (How Containers Talk to Each Other)</h3><p>Docker networking is confusing at first but the core idea is simple.</p><p>Imagine you have One container for backend, One container for database, One container for frontend</p><p>How do these containers communicate?</p><p>And the answer is <strong>Docker Networks</strong></p><h3>🔹 Default Bridge Network</h3><p>Docker creates a default <strong>bridge network</strong>.</p><pre>docker network ls</pre><p>In the default bridge:</p><ul><li>Containers communicate using IP addresses</li><li>IPs can change</li></ul><h3>🔹 Custom Docker Network</h3><pre>docker network create my-network</pre><p>Think of this as <strong><em>Create a private room for my containers</em></strong></p><p>Run containers inside this network:</p><pre>docker run -d --name backend --network my-network backend-image<br>docker run -d --name db --network my-network mongo</pre><p>Now Docker says. <strong><em>These containers belong to the same family</em></strong></p><p>Key benefit:<br>Containers can communicate using <strong>container names</strong>.</p><p>Example:</p><pre>mongodb://db:27017</pre><p>No IP addresses. No hardcoding.</p><h3>🔹 Why Custom Networks Matter</h3><p>1. Service-to-service communication<br> 2. Clean architecture<br> 3. Required for Docker Compose<br> 4. Production-like environment</p><p>If you are building real projects or microservices, custom networks are essential.</p><h3>3. Docker Volumes (How Docker Stores Data Safely)</h3><p>A very common beginner question:</p><blockquote>What happens to data when a container is deleted?</blockquote><p>Answer: <strong>Data is lost</strong> ❌<br>Solution: <strong>Docker Volumes</strong> ✅</p><h3>🔹 Problem Without Volumes</h3><p>Containers are <strong>ephemeral</strong>. When a container is deleted, its data is deleted too.</p><p>This is dangerous for databases.</p><h3>🔹 What Is a Docker Volume?</h3><p>A Docker volume is:</p><ul><li>Storage managed by Docker</li><li>Exists outside the container lifecycle</li><li>Persists even if the container is deleted</li></ul><h3>🔹 Create a Volume</h3><pre>docker volume create my-volume</pre><h3>🔹 Use a Volume in a Container</h3><pre>docker run -d \-v my-volume:/data \mongo</pre><p>/data directory inside the container<br> my-volume persistent storage</p><h3><strong>Outro</strong></h3><p>So yeah, that’s pretty much it for now! If you gained some knowledge from this article then give me a clap and drop a comment. You can also follow me on X.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e1e3676a96f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Explained? And How It Works Internally?]]></title>
            <link>https://medium.com/@shivasingh.1dev/docker-explained-what-it-is-how-it-works-internally-and-essential-commands-5c0e5c449595?source=rss-ae6be363234d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c0e5c449595</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[shivatech]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 14:23:37 GMT</pubDate>
            <atom:updated>2025-12-21T16:35:43.819Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever heard someone say <strong><em>“It works on my machine”</em></strong> and then watched the same app break on another system Docker exists to fix <strong>exactly that problem</strong></p><p>This blog is written for developers and learners who want to understand Docker <strong>from the ground up </strong>not just commands but what is <em>actually happening under the hood</em>. I’ll keep things simple &amp; practical.</p><blockquote><strong><em>Content inside in this blog?</em></strong></blockquote><blockquote><strong>1. What is Docker?</strong></blockquote><blockquote><strong>2. Why Docker is Needed (The Problem It Solves)</strong></blockquote><blockquote><strong>3. Virtual Machines vs Docker (The rise of Virtual Machine)</strong></blockquote><blockquote><strong>4. Core Docker Components?</strong></blockquote><blockquote><strong>5. How Docker Works Internally?</strong></blockquote><blockquote><strong>6. What is Dockerfile?</strong></blockquote><blockquote><strong>7. Outro</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JUOITpaBdlrMP9D__-K5Fw.png" /></figure><h3>1. What is Docker?</h3><p>Docker is a <strong>containerization platform</strong> that lets you package an application <strong>along with everything it needs to run</strong> code, runtime, system libraries, dependencies, and configuration into a single unit called a <strong>container</strong>.</p><p><strong>Think of Docker like this:</strong></p><blockquote>“I don’t care where you run my app laptop, server, cloud it should behave the same everywhere.”</blockquote><p><strong><em>Docker makes that possible.</em></strong></p><h4>Real-life analogy</h4><p>Imagine you’re cooking food:</p><ul><li><strong>Traditional setup:</strong> You go to someone else’s kitchen and hope they have the same stove, gas, utensils, and ingredients.</li><li><strong>Docker way:</strong> You carry your <strong>own portable kitchen</strong> with everything inside.</li></ul><p>That portable kitchen is a <strong>Docker container.</strong></p><h3>2. Why Docker is Needed (The Problem It Solves)</h3><p>Before Docker software development looked simple on the surface but was actually full of hidden problems. Most issues did not come from bad code they came from <strong>differences in environments</strong>.</p><p>Let’s understand this properly.</p><h3>The Core Problem: Environment Mismatch</h3><p>An application does not run only on code. It depends on:</p><ul><li>Operating system</li><li>System libraries</li><li>Language runtime (Node, Python, Java, etc.)</li><li>Dependency versions</li><li>Environment variables</li></ul><p>When any one of these changes the app behavior can change.</p><p>This is why developers often hear:</p><blockquote><em>“It works on my machine.”</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*WrAm1F_s9XN-vPeqc6FQ3Q.jpeg" /></figure><h3>Common Problems Before Docker</h3><p>Before Docker teams faced issues like:</p><ul><li><strong>Different OS versions</strong><br>A developer might use Windows another uses macOS while production runs on Linux.</li><li><strong>Dependency conflicts</strong><br>One system has Node 16 another has Node 18. One has an older library installed globally.</li><li><strong>Missing system libraries</strong><br>App runs locally but crashes on server because a required system package is missing.</li><li><strong>Hard-to-reproduce bugs</strong><br>A bug appears only in production, but no one can recreate it locally.</li><li><strong>Manual server setup</strong><br>Setting up a new server meant hours of installing and configuring things by hand.</li></ul><h3>How Docker Fixes This</h3><p>Docker solves this by <strong>freezing the environment</strong>.</p><p>When you create a Docker image you are saying:</p><blockquote><em>“This exact setup is how my app should run.”</em></blockquote><p>The image includes:</p><ul><li>OS-level dependencies</li><li>Runtime version</li><li>Libraries</li><li>App code</li></ul><p>That same image is used everywhere.</p><h3>With Docker (Modern Flow)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*eumqYBDrxqlDvWvEQ4csRw.png" /></figure><p>Result:</p><ul><li>Same container everywhere ✅</li><li>Predictable behavior ✅</li><li>Faster and safer deployments ✅</li></ul><h3>Why This Matters in Real Life</h3><ul><li>New developers can start a project in minutes</li><li>CI/CD pipelines become reliable</li><li>Production bugs reduce drastically</li><li>Scaling apps becomes easier</li></ul><p>In short Docker removes <strong>environment-related pain </strong>so developers can focus on writing code instead of fixing setups.</p><h3><strong>3. Virtual Machines vs Docker?</strong></h3><h3>Before Docker How We Used to Run Applications</h3><p>To understand Docker we first need to look at <strong>what existed before it</strong> and how application deployment evolved over time.</p><p>Docker did not appear suddenly. It is the result of <strong>years of problems and improvements</strong> in how we run software.</p><h3>The Early Days Running Apps Directly on the Server</h3><p>In the beginning, the strategy was very simple.</p><ul><li>One physical server</li><li>One operating system</li><li>Applications installed directly on that OS</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*C_F_0btua3wfxaCCsMPNHA.png" /></figure><h4>How this worked</h4><ul><li>Developers logged into the server</li><li>Installed required software manually</li><li>Deployed code directly on the machine</li></ul><h4>Problems with this approach</h4><ul><li><strong>Dependency conflicts</strong><br>App A needs Python 2 and App B needs Python 3 both cannot peacefully coexist.</li><li><strong>No isolation</strong><br>One buggy app could crash the entire server.</li><li><strong>Poor resource utilization</strong><br>One heavy app could consume all CPU or memory.</li><li><strong>Scaling was painful</strong><br>To scale, you needed another full server.</li></ul><p>This approach worked for small systems but completely broke down as applications grew.</p><h3>The Rise of Virtual Machines (VMs)</h3><p>To solve these issues <strong>Virtual Machines</strong> were introduced.</p><p>A Virtual Machine allows you to run <strong>multiple isolated operating systems</strong> on a single physical machine.</p><p>Each VM behaves like a <strong>real computer</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*Oie_pLPDoY904H2g77ap9g.png" /></figure><h3>What Exactly Is a Virtual Machine?</h3><p>A Virtual Machine is:</p><ul><li>A full operating system</li><li>Running on top of another OS</li><li>Managed by a hypervisor (VirtualBox, VMware, Hyper-V, etc.)</li></ul><p>Each VM includes:</p><ul><li>Its own kernel</li><li>Its own system libraries</li><li>Its own file system</li><li>Its own applications</li></ul><p>From inside, a VM feels like a <strong>real physical machine</strong>.</p><h3>Why Virtual Machines Were a Big Improvement</h3><p>VMs solved many earlier problems:</p><ul><li><strong>Strong isolation</strong><br>One VM crashing does not affect others.</li><li><strong>Dependency freedom</strong><br>Each VM can have different OS and library versions.</li><li><strong>Better security</strong><br>VMs are isolated at the OS level.</li></ul><p>This was a huge step forward.</p><h3>The Hidden Problems with Virtual Machines</h3><p>Over time, teams started noticing limitations.</p><ul><li><strong>Heavyweight</strong><br>Each VM includes a full OS often several GBs.</li><li><strong>Slow startup</strong><br>Booting a VM takes minutes.</li><li><strong>High resource usage</strong><br>Multiple OS kernels waste CPU and memory.</li><li><strong>Hard to scale fast</strong><br>Creating new VMs is slow and expensive.</li></ul><p>As systems moved toward microservices and cloud-native architectures, VMs started feeling too heavy.</p><h3>Virtual Machines vs Docker Containers</h3><p>Now that we understand both worlds the comparison becomes very clear.</p><h3>Virtual Machines (VMs)</h3><ul><li>Each VM has its <strong>own full operating system</strong></li><li>Includes its <strong>own kernel</strong></li><li>Heavy (GBs in size)</li><li>Slower to start (minutes)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*Oie_pLPDoY904H2g77ap9g.png" /></figure><h3>Docker Containers</h3><ul><li>Containers <strong>share the host OS kernel</strong></li><li>No separate guest OS</li><li>Lightweight (MBs)</li><li>Start in seconds</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*U3oEiW75RxKHCDmfxSJTig.png" /></figure><h3>The key idea is simple:</h3><p>VMs virtualize hardware. Docker virtualizes the operating system.</p><p>This shared kernel concept is <strong>the heart of Docker’s speed efficiency and popularity</strong>.</p><h3><strong>4. Core Docker Components?</strong></h3><p>Let’s understand Docker’s main building blocks.</p><h3>4.1 Docker Engine</h3><p>Docker Engine is the <strong>brain of Docker</strong>. It includes:</p><ul><li>Docker CLI (what you type)</li><li>Docker Daemon (runs in background)</li><li>REST API (communication layer)</li></ul><p>When you run a command, the CLI talks to the daemon, and the daemon does the actual work.</p><h3>4.2 Docker Image</h3><p>A Docker image is a <strong>read-only blueprint</strong>.</p><p>It contains:</p><ul><li>Base OS layer</li><li>App code</li><li>Dependencies</li><li>Configurations</li></ul><p>Images do <strong>not run</strong>. They are just templates.</p><p>Example:</p><ul><li>node:18</li><li>nginx:latest</li></ul><h3>4.3 Docker Container</h3><p>A container is a <strong>running instance of an image</strong>. You can create multiple containers from the same image.</p><p>Example:</p><ul><li>One image contains many containers</li></ul><h3><strong>5. How Docker Works Internally?</strong></h3><p>This is the most important part of Docker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rZvsBOkoLNBpAscHlvkiw.png" /></figure><p>Now let’s deeply understand Docker’s internal working using the <strong>internal architecture diagram</strong> you saw earlier. We’ll go component by component and connect the dots so nothing feels magical or hidden.</p><p>Think of Docker not as a single tool, but as a <strong>pipeline</strong> that turns a command into a running, isolated process.</p><h3>5.1 Docker CLI (User Command Layer)</h3><p>This is the part you interact with directly.</p><p>Example:</p><pre>docker run myapp</pre><p>What actually happens here?</p><ul><li>The Docker CLI is just a <strong>command-line client</strong></li><li>It does NOT create containers by itself</li><li>It converts your command into an <strong>API request</strong></li></ul><p>Important point:</p><p><em>Docker CLI is like a remote control. The real work happens elsewhere.</em></p><p>The CLI sends this request to the <strong>Docker Daemon</strong>.</p><h3>5.2 Docker Daemon (The Brain of Docker)</h3><p>The Docker Daemon <strong><em>dockerd</em></strong> is a background service running on your system.</p><p>Its responsibilities:</p><ul><li>Manage images</li><li>Create containers</li><li>Control networking</li><li>Manage volumes</li></ul><p>When it receives a command like docker run:</p><p>It checks whether the image exists locally If not it pulls the image from Docker Hub Prepares the container environment</p><p>This daemon is the <strong>decision-maker</strong> of Docker.</p><h3>5.3 Docker Image</h3><p>Before a container can exist Docker needs an image.</p><p>From the diagram an image consists of layered parts:</p><ul><li>Base OS layer (example: Ubuntu, Alpine)</li><li>Runtime layer (Node, Python, Java)</li><li>Dependency layer (node_modules, pip packages)</li><li>Application code layer</li></ul><p>Important internal detail:</p><ul><li>Images are <strong>immutable</strong> (read-only)</li><li>They never change once built</li></ul><p>Docker uses these layers to efficiently reuse data across images.</p><h3>5.4 Container Creation</h3><p>This is a very important concept.</p><p>A Docker container is:</p><ul><li>NOT a virtual machine</li><li>NOT a mini OS</li></ul><p>Internally it is <em>A group of isolated Linux processes</em></p><p>Docker creates a container by:</p><ul><li>Starting a normal Linux process</li><li>Applying isolation and limits to it</li></ul><p>This is where Linux kernel features come in.</p><h3>6. What is a Dockerfile?</h3><p>A Dockerfile is essentially a text file containing instructions that tell Docker how to build your image. It’s like giving Docker a step-by-step guide First, start with this base system, then add these files run these commands and finally here’s what to do when someone uses this container.”</p><h3>The Building Blocks Four Essential Commands</h3><h3>FROM — Your Starting Point</h3><p>Every Dockerfile journey begins with FROM. This command tells Docker what base image you want to start with. Think of it as choosing the foundation for your house before you start building.</p><pre>FROM ubuntu:18.04</pre><p>This line says Hey Docker, I want to start with Ubuntu version 18.04 as my foundation. The FROM instruction must be the first real command in your Dockerfile (though you can have some ARG commands before it if needed).</p><h3>PULL — Bringing in Your Files</h3><p>The PULL command is your way of grabbing files from your Docker repository and adding them to your image. It&#39;s like fetching ingredients from your pantry before you start cooking.</p><h3>RUN — Building Your Environment</h3><p>RUN is where the magic happens. This command executes instructions that actually build your container. Want to install software? Update packages? Set up configurations? RUN is your go-to command.</p><pre>RUN apt-get update &amp;&amp; apt-get install -y python3</pre><h3>CMD — The Final Action</h3><p>CMD specifies what command should run when someone starts a container from your image. It&#39;s like setting the default action—what happens when you press &quot;play.&quot;</p><p>dockerfile</p><pre>CMD [&quot;python3&quot;, &quot;app.py&quot;]</pre><h3>How to Write a Dockerfile</h3><p>Let me show you a practical example of a Dockerfile that creates a simple Python Flask web application. I’ll walk you through each line so you understand exactly what’s happening.</p><pre># Use Python 3.9 as our base image<br>FROM python:3.9-slim<br><br># Set the working directory inside the container<br>WORKDIR /app<br><br># Copy the requirements file to the container<br>COPY requirements.txt .<br><br># Install Python dependencies<br>RUN pip install --no-cache-dir -r requirements.txt<br><br># Copy all application files to the container<br>COPY . .<br><br># Expose port 5000 for the Flask app<br>EXPOSE 5000<br><br># Set environment variables<br>ENV FLASK_APP=app.py<br>ENV FLASK_RUN_HOST=0.0.0.0<br><br># Command to run when the container starts<br>CMD [&quot;flask&quot;, &quot;run&quot;]</pre><h3>Breaking It Down</h3><p><strong>FROM python:3.9-slim</strong></p><ul><li>We’re starting with a lightweight Python 3.9 image as our foundation</li><li>The “slim” version keeps things minimal and efficient</li></ul><p><strong>WORKDIR /app</strong></p><ul><li>This sets /app as our working directory inside the container</li><li>All subsequent commands will run from this location</li></ul><p><strong>COPY requirements.txt .</strong></p><ul><li>We copy our requirements file first before the rest of the code</li><li>This is a smart trick for Docker caching dependencies don’t change often</li></ul><p><strong>RUN pip install — no-cache-dir -r requirements.txt</strong></p><ul><li>This installs all our Python packages</li><li>The --no-cache-dir flag keeps the image size smaller</li></ul><p><strong>COPY . .</strong></p><ul><li>Now we copy all our application files into the container</li></ul><p><strong>EXPOSE 5000</strong></p><ul><li>This tells Docker that our app will listen on port 5000</li></ul><p><strong>ENV FLASK_APP=app.py</strong></p><ul><li>We’re setting environment variables that Flask needs</li></ul><p><strong>CMD [“flask”, “run”]</strong></p><ul><li>This is what runs when someone starts our container</li><li>It launches our Flask application</li></ul><h3>How to Use This Dockerfile</h3><ol><li><strong>Build the image:</strong></li></ol><pre>docker build -t my-flask-app .</pre><ol><li><strong>Run the container:</strong></li></ol><pre>docker run -p 5000:5000 my-flask-app</pre><ol><li><strong>Open your browser:</strong> Navigate to http://localhost:5000 and you&#39;ll see your app running!</li></ol><h3>What’s Happening Behind the Scenes?</h3><p>When you run docker build Docker reads your Dockerfile line by line:</p><ol><li>It pulls the Python base image</li><li>Creates a working directory</li><li>Installs your dependencies</li><li>Copies your application code</li><li>Sets everything up just right</li></ol><p>When you run docker run it takes that built image and creates a living breathing container with your Flask app running inside it!</p><p><strong>Pro Tip:</strong> This Dockerfile follows best practices like copying requirements separately and using multi-stage awareness for better caching. Each time you rebuild Docker only re-runs the steps that changed making your builds lightning fast</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*P23uyGQaB2F7FSpXSrqvWA.jpeg" /></figure><h3>Understanding Layers</h3><p>Here’s something cool Docker builds images in layers like a stack of pancakes. Each instruction creates a new layer. When you run your image and create a container, Docker adds one more layer on top a writable layer called the <strong>container layer</strong>.</p><p>This writable layer is special because it captures all the changes that happen while your container is running new files you create, files you modify or files you delete. Everything else below it stays unchanged which makes Docker images efficient and reusable.</p><p><strong>Remember:</strong> Docker reads your Dockerfile from top to bottom, executing each instruction in order. Start with FROM build up your environment with RUN and PULL and finish with CMD to define what your container does. That&#39;s the basic flow!</p><h3><strong>Outro</strong></h3><p>That’s it! This blog is already getting a little bit lengthy so I’ll cover the remaining topics like Docker Commands You Must Know, Docker Networking, and Docker Volumes in a second article where I’ll explain each and every topic in detail and share some tips and tricks with you.</p><p>So yeah, that’s pretty much it for now! If you gained some knowledge from this article, then give me a clap and drop a comment. You can also follow me on X.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c0e5c449595" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create a FastAPI Todo App with PostgreSQL Database?]]></title>
            <link>https://medium.com/@shivasingh.1dev/how-to-create-a-fastapi-todo-app-with-postgresql-database-202f08e3f70d?source=rss-ae6be363234d------2</link>
            <guid isPermaLink="false">https://medium.com/p/202f08e3f70d</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[fastapi-tutorials]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[shivatech]]></dc:creator>
            <pubDate>Wed, 19 Nov 2025 18:02:14 GMT</pubDate>
            <atom:updated>2025-11-19T18:02:14.235Z</atom:updated>
            <content:encoded><![CDATA[<p>A few days ago I had a simple goal to learn FastApi and Implement it. My project.</p><p><strong>Build a full-stack app where I can add, update, and delete todos. and learn how a FastApi backend talks to a frontend.</strong></p><p><strong>I didn’t want something too confusing.<br>I didn’t want to get lost in advanced theory.</strong></p><p>I wanted something simple, practical, and real. And also i wanna explore highly. Scalable backend</p><p>So, I picked <strong>FastAPI</strong> for backend, <strong>PostgreSQL</strong> for database, and <strong>React + TailwindCSS</strong> for the UI.</p><p>And trust me — even if you’re new you can build this step-by-step.</p><p>This article will walk you through everything I did.</p><p><em>No complicated jargon.<br>No messy explanations.<br>Just a clean roadmap.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7CKR6oPfQ1YhUunjcXzMIw.png" /></figure><h3>Why FastAPI?</h3><p>Before anything let me tell you why FastAPI clicked for me:</p><ul><li>It’s <strong>super fast</strong></li><li>The documentation is great</li><li>It automatically generates Swagger API docs</li><li>Python code feels clean and readable</li><li>It’s highly scalable</li></ul><p>The main reason I’m building this app is my growing interest in backend development. After spending a few months working with the MERN stack and building full-stack projects. I realized I wanted to go deeper into backend engineering. That’s why I chose FastAPI so I can explore backend architecture more seriously and learn how to build highly scalable backend systems.</p><p>If you’ve ever written backend code and felt like:</p><p><em>“Why is setup so confusing?”</em></p><h3>Step 1 — Create the Project Folder</h3><p>Create a main folder anywhere:</p><pre>Todo/<br> └── backend/</pre><p>Now move inside backend folder:</p><pre>cd Todo/backend</pre><h3>Step 2 — Create a Virtual Environment (Optional but recommended)</h3><pre>python -m venv venv</pre><p>Activate it:</p><p>Windows:</p><pre>venv\Scripts\activate</pre><p>Mac/Linux:</p><pre>source venv/bin/activate</pre><h3>Step 3 — Install FastAPI and Uvicorn</h3><pre>pip install fastapi uvicorn sqlalchemy psycopg2</pre><p>We’ll use:</p><ul><li><strong>FastAPI → API building</strong></li><li><strong>Uvicorn → Server runner</strong></li><li><strong>SQLAlchemy → Database ORM</strong></li><li><strong>psycopg2 → PostgreSQL connector</strong></li></ul><p>I’ll share my <a href="https://github.com/SHIVA-SINGHx/Fast-Api-Todo"><strong><em>GitHub</em></strong></a> repository where you can find the complete source code. The repository also includes a requirements.txt file so you can install all necessary dependencies by running it directly.</p><p>GitHub Repo → <a href="https://github.com/SHIVA-SINGHx/Fast-Api-Todo">https://github.com/SHIVA-SINGHx/Fast-Api-Todo</a></p><h3>Step 4 — Setup Database Connection</h3><p>Inside backend folder, create a file:</p><p>📄 config.py</p><pre>from dotenv import load_dotenv<br>import os<br><br>load_dotenv()<br><br>class Settings:<br>    DATABASE_URL: str = os.getenv(&quot;DATABASE_URL&quot;)<br><br>settings = Settings()</pre><p>The <strong>config.py</strong> file is responsible for handling all important configuration values of our backend project in this case our <strong>database connection URL</strong>.</p><p>Instead of writing the database URL directly into the code (which is risky and bad practice) we store it securely inside a <strong>.env file. </strong>The <strong>.env file</strong> is never uploaded to GitHub or shared publicly which keeps our sensitive information safe.</p><p>Inside <strong>config.py </strong>we use:</p><ul><li><strong>dotenv</strong> → to load environment variables from .env</li><li><strong>os.getenv</strong> → to read those values in Python</li><li>A <strong>Settings class</strong> → to keep the configuration clean, organized, and easy to access throughout the project.</li></ul><p>So anytime we need the database URL, we simply use:</p><pre>settings.DATABASE_URL</pre><p>This approach makes the application more professional secure and scalable especially when working on larger projects or deploying to cloud platforms later.</p><h3>Step 5— Connection Database with PostgreSQL</h3><p>Inside backend folder, create a file:</p><p>📄 database.py</p><pre>from sqlalchemy import create_engine<br>from sqlalchemy.orm import sessionmaker, declarative_base</pre><pre>DATABASE_URL = &quot;postgresql://postgres:password@localhost/todo_db&quot;</pre><pre>engine = create_engine(DATABASE_URL)<br>SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)</pre><pre>Base = declarative_base()</pre><p><em>Replace the URL with your own PostgreSQL username/password/database.</em></p><h3>What Does database.py Do?</h3><p>This file is responsible for creating a <strong>connection between our FastAPI app and our PostgreSQL database.</strong></p><p>Think of it like a <strong>bridge</strong> our application sends data like tasks updates or deletes and the database responds back.</p><p>Here’s what happens inside this file in simple terms:</p><ul><li><strong>DATABASE_URL</strong><br> This is the address of your database including username password and database name.<br> It tells FastAPI <em>where</em> your database lives.</li><li><strong>engine</strong><br> This is like starting the vehicle that will talk to the database.<br> Without this FastAPI can&#39;t send or receive data.</li><li><strong>SessionLocal</strong><br> This creates a <strong>session </strong>which means every time the app wants to read or write something in the database it uses this session.</li><li><strong>Base</strong><br> This will be used later to create tables inside the database.</li></ul><p><strong>In short:</strong></p><p>database.py makes sure your app can communicate with PostgreSQL successfully.</p><p>Without this file, your app and database are like two people speaking different languages — they can’t talk to each other.</p><h3>Step 6— Create Todo Model</h3><p>Create file:</p><p>📄 models.py</p><pre>from sqlalchemy import Column, Integer, String, Boolean<br>from database import Base</pre><pre>class Todo(Base):<br>    __tablename__ = &quot;todos&quot;</pre><pre>    id = Column(Integer, primary_key=True, index=True)<br>    task = Column(String, nullable=False)<br>    description = Column(String, nullable=True)<br>    completed = Column(Boolean, default=False)</pre><h3>What Does models.py Do?</h3><p>This file is responsible for defining what a <strong>Todo item</strong> looks like in the database.</p><p>Think of it like designing a form before storing data you first decide what fields are required (like task name, description, completed status).<br>This file creates that structure.</p><p>Inside this file:</p><ul><li><strong>class Todo(Base)</strong><br> This creates a blueprint (called a <em>model</em>) for storing data in the PostgreSQL database.</li><li><strong>__tablename__ = &quot;todos&quot;</strong><br> This tells the database:</li><li><strong><em>“Create a table named todos.”</em></strong></li></ul><h4>In Simple Words:</h4><p><strong>models.py</strong> creates the <strong>shape of data</strong> that will be stored in your database.<br> Without this file the database wouldn’t know what fields a Todo item contains.</p><h3>Step 7— Create Schema</h3><p>Create file:</p><p>📄 schema.py</p><pre>from pydantic import BaseModel<br><br>class TodoBase(BaseModel):<br>    task: str<br>    description: str | None = None<br>    completed: bool | None = None<br><br>class TodoCreate(TodoBase):<br>    pass<br><br>class TodoUpdate(BaseModel):<br>    task: str | None = None<br>    description: str | None = None<br>    completed: bool | None = None<br><br>class TodoResponse(TodoBase):<br>    id: int<br>    completed: bool<br><br>    class Config:<br>        orm_mode = True</pre><h3>Why We Need It. Schema.py?</h3><p>Now that we have our database model the next step is to define how data will be received from the user and returned from the API. This is where <strong>Pydantic schemas</strong> come in.</p><p>Even though our models.py defines the structure for the database it is <strong>not responsible for validating or shaping the data</strong> that comes in through API requests.</p><h3>What This File Does</h3><p>This file defines <strong>how the data flows in and out of the API</strong>.</p><p>FastAPI uses <strong>Pydantic</strong> for validation meaning any data coming from the frontend or any client must match these schema definitions. If the data is invalid FastAPI will automatically reject it and send a clear error message.</p><p>TodoBaseDefines the common fields a Todo should have.</p><p>TodoCreateUsed when creating a new Todo inherits everything from TodoBase.</p><p>TodoUpdateUsed when updating a Todo here every field is optional because the user may update only one field.</p><p>TodoResponseDefines how data should be structured when returned to the client.</p><h3>What is Pydantic?</h3><p>Pydantic is a Python library that helps us <strong>validate and structure data</strong> in a clean and reliable way. FastAPI uses Pydantic under the hood to ensure that the data coming into our API is correct well-formatted and safe.</p><ul><li>If the user sends valid data → accepted</li><li>If the user sends incomplete or wrong data → rejected with a helpful message</li></ul><h3>Step 8— Create Controller</h3><p>Create file:</p><p>📄 controller/todo_controller.py</p><pre>from sqlalchemy.orm import Session<br>from .. import models, schema</pre><pre>def create_todo(db: Session, data: schema.TodoCreate):<br>    todo = models.Todo(task=data.task, description=data.description, completed = data.completed)<br>    db.add(todo)<br>    db.commit()<br>    db.refresh(todo)<br>    return todo</pre><pre>def get_all_todos(db: Session):<br>    return db.query(models.Todo).all()</pre><pre>def get_one(db: Session, todo_id: int):<br>    return db.query(models.Todo).filter(models.Todo.id == todo_id).first()</pre><pre>def update(db: Session, todo_id: int, data: schema.TodoUpdate):<br>    todo = get_one(db, todo_id)<br>    if not todo:<br>        return None</pre><pre>if data.task:<br>        todo.task = data.task<br>    if data.description:<br>        todo.description = data.description<br>    if data.completed is not None:<br>        todo.completed = data.completed</pre><pre>db.commit()<br>    db.refresh(todo)<br>    return todo</pre><pre>def delete(db: Session, todo_id: int):<br>    todo = get_one(db, todo_id)<br>    if not todo:<br>        return None</pre><pre>db.delete(todo)<br>    db.commit()<br>    return todo</pre><p>This is our pure logic file just like a typical MERN Stack Project..</p><h3>Step 9— Create Routes</h3><p>Create file:</p><p>📄 routes/ todo_route.py</p><pre>from fastapi import APIRouter, Depends<br>from sqlalchemy.orm import Session<br>from database import SessionLocal<br>import models, schemas</pre><pre>router = APIRouter()</pre><pre>def get_db():<br>    db = SessionLocal()<br>    try:<br>        yield db<br>    finally:<br>        db.close()</pre><pre>@router.get(&quot;/todos/&quot;)<br>def get_all(db: Session = Depends(get_db)):<br>    return db.query(models.Todo).all()</pre><pre>@router.post(&quot;/todos/&quot;)<br>def create(todo: schemas.TodoCreate, db: Session = Depends(get_db)):<br>    new_todo = models.Todo(task=todo.task, description=todo.description)<br>    db.add(new_todo)<br>    <br>    db.commit()<br>    db.refresh(new_todo)<br>    <br>    return new_todo</pre><p>This is our pure routing section just like a typical MERN Stack Project..</p><h3>Step 10— Run Server</h3><p>Create main.py</p><pre>from fastapi import FastAPI<br>from .database import engine, Base<br>from .routes.todo_route import router<br></pre><pre>app = FastAPI(<br>    title=&quot;FastAPI Todo App&quot;,    <br>    )</pre><pre>Base.metadata.create_all(bind=engine)</pre><pre>app.include_router(router)</pre><pre><a href="http://twitter.com/app">@app</a>.get(&quot;/&quot;)<br>def home():<br>    return {&quot;message&quot;: &quot;FastAPI Todo Server Running&quot;}</pre><pre>## Middleware</pre><pre>from fastapi.middleware.cors import CORSMiddleware<br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;<a href="http://localhost:5173/">http://localhost:5173</a>&quot;],<br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)</pre><p>Run the server:</p><pre>uvicorn main:app --reload</pre><p>Now open browser:</p><p>👉 <a href="http://127.0.0.1:8000/docs">http://127.0.0.1:8000/docs</a></p><p>Boom — interactive API with UI.</p><p>If you learned something new from this blog don’t forget to <strong>leave a clap</strong> 👏it really motivates me to share more valuable content like this.</p><p>Make sure to <strong>follow me</strong> so you don’t miss out on upcoming blogs and tutorials!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=202f08e3f70d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Pivot Table & Group By Aggregations in Pandas?]]></title>
            <link>https://medium.com/@shivasingh.1dev/what-is-pivot-table-in-pandas-and-group-by-aggregations-2ad91717161f?source=rss-ae6be363234d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ad91717161f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[shivatech]]></dc:creator>
            <pubDate>Wed, 29 Oct 2025 19:16:01 GMT</pubDate>
            <atom:updated>2025-11-01T03:25:01.676Z</atom:updated>
            <content:encoded><![CDATA[<p>In he previous article we explored how to combine data using <strong>concat()</strong> <strong>merge()</strong>, and <strong>join()</strong>. And much more. If you haven’t read yet, so please check that blog first before moving on to this <a href="https://medium.com/@shivasingh.1dev/master-pandas-library-in-python-the-ultimate-beginners-guide-part-1-ccab4f97e37e">article</a>…<br>Now it’s time to take the next step <strong>analyzing and transforming data</strong> efficiently using some of the most powerful Pandas tools….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*junNzvQfp4OGTol3_WoNkw.jpeg" /></figure><h3>1. What is a Pivot Table?</h3><p>A <strong>pivot table</strong> is one of the most powerful tools in Pandas and Excel too. It allows you to <strong>summarize, analyze and reorganize</strong> your data turning <strong>raw rows</strong> into <strong>meaningful insights</strong>.</p><p>Think of it like this:<br>You have a big dataset of sales and you want to quickly find out</p><p>How much each product sold in each region or which representative sold the most in a month.</p><p>You can do all that with <strong>just one line</strong> using a Pivot Table.</p><h3>Syntax of a Pivot Table</h3><pre>pd.pivot_table(<br>    data, <br>    values=&#39;column_to_aggregate&#39;, <br>    index=&#39;rows&#39;, <br>    columns=&#39;columns&#39;, <br>    aggfunc=&#39;function&#39;<br>)</pre><ul><li><strong>data:</strong> the DataFrame you’re working on</li><li><strong>values:</strong> which column’s data you want to summarize</li><li><strong>index:</strong> what you want to show as rows</li><li><strong>columns:</strong> what you want to show as columns</li><li><strong>aggfunc:</strong> how you want to aggregate (like <strong>sum, mean, count</strong>)</li></ul><h3>Example 1 — Simple Pivot Table</h3><p>Let’s say we have this small dataset:</p><pre>import pandas as pd<br><br>data = pd.DataFrame({<br>    &#39;Product&#39;: [&#39;A&#39;, &#39;A&#39;, &#39;B&#39;, &#39;B&#39;, &#39;C&#39;, &#39;C&#39;],<br>    &#39;Region&#39;: [&#39;North&#39;, &#39;South&#39;, &#39;North&#39;, &#39;South&#39;, &#39;North&#39;, &#39;South&#39;],<br>    &#39;Sales&#39;: [1200, 800, 1500, 1300, 1000, 900]<br>})</pre><p>Now we want to know:<br>Total sales of each product in each region.</p><pre>pivot = pd.pivot_table(<br>    data,<br>    values=&#39;Sales&#39;,<br>    index=&#39;Product&#39;,<br>    columns=&#39;Region&#39;,<br>    aggfunc=&#39;sum&#39;<br>)<br><br>print(pivot)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*kMzxD3uZmfSrhs32qlfM4g.png" /></figure><p>In just one line you’ve summarized your entire dataset showing each product’s total sales across regions.</p><h3>Example 2 — Multiple Aggregations</h3><p>What if you also want to see both sum and mean?</p><pre>pivot = pd.pivot_table(<br>    data,<br>    values=&#39;Sales&#39;,<br>    index=&#39;Product&#39;,<br>    columns=&#39;Region&#39;,<br>    aggfunc=[&#39;sum&#39;, &#39;mean&#39;]<br>)<br>print(pivot)<br><br></pre><p>Now you’ll get <strong>multi-level columns</strong> showing both total and average sales per region. This is especially useful when comparing <strong>performance metrics</strong>.</p><h3>Example 3 — Real-World Example</h3><p>Imagine a dataset of sales reps:</p><pre>import pandas as pd<br><br>data = pd.DataFrame({<br>    &#39;Rep&#39;: [&#39;Riya&#39;, &#39;Riya&#39;, &#39;Aryan&#39;, &#39;Aryan&#39;],<br>    &#39;Region&#39;: [&#39;North&#39;, &#39;North&#39;, &#39;South&#39;, &#39;South&#39;],<br>    &#39;Month&#39;: [&#39;Jan&#39;, &#39;Feb&#39;, &#39;Jan&#39;, &#39;Feb&#39;],<br>    &#39;Sales&#39;: [1200, 1500, 800, 900]<br>})<br>print(data)<br><br>##output: <br><br>     Rep Region Month  Sales<br>0   Riya  North   Jan   1200<br>1   Riya  North   Feb   1500<br>2  Aryan  South   Jan    800<br>3  Aryan  South   Feb    900</pre><p>Apply Pivot Table:</p><pre>pivot = pd.pivot_table(<br>    data,<br>    values=&#39;Sales&#39;,     # the column we want to summarize<br>    index=&#39;Month&#39;,      # show months as rows<br>    columns=&#39;Region&#39;,   # show regions as columns<br>    aggfunc=&#39;sum&#39;       # aggregate (sum) the sales<br>)<br>print(pivot)</pre><p>output:</p><pre>Region  North  South<br>Month                <br>Feb      1500    900<br>Jan      1200    800</pre><p><strong>Pivot tables is like Instant insights.</strong> No loops no filters just one line to summarize your entire dataset.</p><h3>2. What is Group by?</h3><p>groupby() lets you <strong>split</strong> the DataFrame into groups based on one or more keys columns <strong>apply</strong> some operation aggregation, transformation, filter to each group, and then <strong>combine</strong> the results.</p><p>It’s like SQL GROUP BY or Excel pivot, but more flexible.</p><h3>Basic grouping — count, sum, mean</h3><p>Example DataFrame (small):</p><pre>import pandas as pd<br>data = {<br>  &#39;Product&#39;: [&#39;A&#39;,&#39;A&#39;,&#39;B&#39;,&#39;B&#39;,&#39;C&#39;,&#39;C&#39;],<br>  &#39;Region&#39;:  [&#39;North&#39;,&#39;South&#39;,&#39;North&#39;,&#39;South&#39;,&#39;North&#39;,&#39;South&#39;],<br>  &#39;Sales&#39;:   [1200, 800, 1500, 1300, 1000, 900],<br>  &#39;Units&#39;:   [12, 8, 15, 13, 10, 9]<br>}<br>df = pd.DataFrame(data)</pre><p>Group by Product and get total sales:</p><pre>df.groupby(&#39;Product&#39;)[&#39;Sales&#39;].sum()</pre><p>Output:</p><pre>Product<br>A    2000<br>B    2800<br>C    1900<br>Name: Sales, dtype: int64</pre><p>Average sales by Region:</p><pre>df.groupby(&#39;Region&#39;)[&#39;Sales&#39;].mean()</pre><p>Count rows per product:</p><pre>df.groupby(&#39;Product&#39;).size()<br># or<br>df[&#39;Product&#39;].value_counts()</pre><h3>1. Aggregating multiple functions</h3><p>Use .agg() to run many aggregations at once:</p><pre>df.groupby(&#39;Product&#39;)[&#39;Sales&#39;].agg([&#39;sum&#39;, &#39;mean&#39;, &#39;max&#39;, &#39;min&#39;])</pre><p>Or aggregate different columns with different functions:</p><pre>df.groupby(&#39;Product&#39;).agg({<br>    &#39;Sales&#39;: [&#39;sum&#39;, &#39;mean&#39;],<br>    &#39;Units&#39;: &#39;mean&#39;<br>})</pre><h3>2. Named aggregations (clean column names)</h3><pre>df.groupby(&#39;Product&#39;).agg(<br>    total_sales=(&#39;Sales&#39;,&#39;sum&#39;),<br>    avg_sales=(&#39;Sales&#39;,&#39;mean&#39;),<br>    avg_units=(&#39;Units&#39;,&#39;mean&#39;)<br>).reset_index()</pre><p>This returns a tidy DataFrame with readable column names.</p><h3>3. Group by multiple columns (multi-index)</h3><p>Group by Product and Region:</p><pre>df.groupby([&#39;Product&#39;,&#39;Region&#39;])[&#39;Sales&#39;].sum()</pre><p>Output is a <strong>MultiIndex</strong> Series. Convert to flat DataFrame:</p><pre>df.groupby([&#39;Product&#39;,&#39;Region&#39;])[&#39;Sales&#39;].sum().reset_index()</pre><h3>4. as_index parameter</h3><p>By default groupby() returns group keys as index. To keep them as columns:</p><pre>df.groupby(&#39;Product&#39;, as_index=False)[&#39;Sales&#39;].sum()</pre><p>This is often handy when you want a clean DataFrame for plotting or saving.</p><h3>5. agg() vs transform() vs apply() — when to use which</h3><ul><li><strong>.agg()</strong> (or .aggregate) → reduces each group to a single value per aggregation summary.<br>Example: sum, mean per group.</li><li><strong>.transform()</strong> → returns a Series aligned with original index useful when you want to create a column of group-level values repeated for each row.<br>Example: add a column with each row’s group mean:</li><li>df[&#39;product_mean_sales&#39;] = df.groupby(&#39;Product&#39;)[&#39;Sales&#39;].transform(&#39;mean&#39;)</li><li><strong>.apply()</strong> → runs an arbitrary function on each group; returns flexible output can be scalar, Series, DataFrame powerful but slower.</li><li>def top_row(group): return group.sort_values(&#39;Sales&#39;, ascending=False).head(1) df.groupby(&#39;Product&#39;).apply(top_row)</li></ul><h3>6. Filtering groups with .filter()</h3><p>Keep only groups that satisfy a condition. Example: products with total sales &gt; 2000:</p><pre>df.groupby(&#39;Product&#39;).filter(lambda g: g[&#39;Sales&#39;].sum() &gt; 2000)</pre><p>This returns the <strong>original rows</strong> of groups that meet the condition.</p><h3>7. Count distinct values: nunique()</h3><p>Unique representatives per region, for instance:</p><pre>df_sales.groupby(&#39;Region&#39;)[&#39;Rep&#39;].nunique()</pre><h3>8. Group size and normalized counts</h3><p>Number of rows per group:</p><pre>df.groupby(&#39;Product&#39;).size()</pre><p>Proportion of rows per product:</p><pre>df.groupby(&#39;Product&#39;).size() / len(df)</pre><h3>9. Grouping with time series</h3><p>If you have a datetime column, convert it and group by month/quarter:</p><pre>df_sales[&#39;Date&#39;] = pd.to_datetime(df_sales[&#39;Date&#39;])<br>df_sales.set_index(&#39;Date&#39;, inplace=True)<br><br># monthly sales<br>monthly = df_sales[&#39;Sales&#39;].resample(&#39;M&#39;).sum()<br># or group by month name<br>df_sales.groupby(df_sales.index.month)[&#39;Sales&#39;].sum()<br># or:<br>df_sales.groupby(df_sales.index.to_period(&#39;M&#39;))[&#39;Sales&#39;].sum()</pre><p>Or group by a column Month or Quarter if you already have it:</p><pre>df_sales.groupby(&#39;Quarter&#39;)[&#39;Sales&#39;].sum()</pre><h3>10. Multiple aggregations with named columns (complex example)</h3><p>Suppose you want per-region metrics:</p><ul><li>total sales</li><li>average units</li><li>number of orders</li></ul><pre>region_stats = df_sales.groupby(&#39;Region&#39;).agg(<br>    total_sales=(&#39;Sales&#39;, &#39;sum&#39;),<br>    avg_units=(&#39;Units&#39;, &#39;mean&#39;),<br>    orders=(&#39;Sales&#39;, &#39;count&#39;)<br>).reset_index()</pre><h3>11. Quick recipes you’ll use repeatedly</h3><p>Top-3 products by total sales:</p><pre>df.groupby(&#39;Product&#39;)[&#39;Sales&#39;].sum().sort_values(ascending=False).head(3)</pre><p>Department-wise average &amp; count:</p><pre>df.groupby(&#39;Department&#39;).agg(avg_salary=(&#39;Salary&#39;,&#39;mean&#39;), employees=(&#39;Salary&#39;,&#39;count&#39;))</pre><p>Add group-level column to original df (e.g., department mean):</p><pre>df[&#39;dept_avg&#39;] = df.groupby(&#39;Department&#39;)[&#39;Salary&#39;].transform(&#39;mean&#39;)</pre><p>Filter groups before aggregating:</p><pre>big_groups = df.groupby(&#39;Department&#39;).filter(lambda g: g[&#39;Salary&#39;].sum() &gt; 200000)<br>big_groups.groupby(&#39;Department&#39;)[&#39;Salary&#39;].sum()</pre><p>So yeah that’s it for today! <br>If you learned something new from this blog don’t forget to <strong>leave a clap</strong> 👏it really motivates me to share more valuable content like this.</p><p>Make sure to <strong>follow me</strong> so you don’t miss out on upcoming blogs and tutorials! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ad91717161f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master Pandas Library in Python. The Ultimate Beginner’s Guide Part-1]]></title>
            <link>https://medium.com/@shivasingh.1dev/master-pandas-library-in-python-the-ultimate-beginners-guide-part-1-ccab4f97e37e?source=rss-ae6be363234d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccab4f97e37e</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[shivatech]]></dc:creator>
            <pubDate>Sat, 25 Oct 2025 18:01:42 GMT</pubDate>
            <atom:updated>2025-10-25T18:01:42.674Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction</h3><ul><li>What is Pandas?</li><li>Why Pandas is Needed?</li><li>How it Became Popular in Data Science</li></ul><h3>2. Installing and Importing Pandas</h3><ul><li>Installation using pip</li></ul><h3>3. Pandas Data Structures</h3><ul><li>Series (1D)</li><li>DataFrame (2D)</li></ul><h3>4. Reading Files in Pandas.</h3><ul><li>Excel Sheets</li><li>CSV files</li><li>Databases</li><li>JSON or APIs</li></ul><h3>5. Basic Data Exploration</h3><ul><li>head(), tail(), info(), describe()</li><li>Understanding dataset structure</li></ul><h3>6. Combining Data</h3><ul><li><strong>Concat</strong>, <strong>Merge</strong>, and <strong>Join</strong></li><li>Understanding when to use each</li></ul><p><strong>Imagine</strong> you have a huge Excel or Google sheet thousands of rows and columns and you want to filter, clean, and analyze that data <strong>with just a few lines of code</strong>.</p><p><strong><em>That’s exactly what Pandas does for you.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*iv0esZMkQ3ZC09D0WgGeJw.avif" /></figure><h3>1. What is Pandas?</h3><p>Pandas is a <strong>Python library for data analysis and manipulation</strong>. It allows you to work with tabular data (rows and columns) easily just like you do in <strong>Microsoft Excel or Google Sheets</strong>, but <strong>faster</strong> <strong>more powerful</strong> and <strong>programmable</strong>.</p><p>It was created by <strong>Wes McKinney in 2008</strong>,<br>and since then, it has become the <strong>backbone of data analysis</strong> in Python.</p><h3>Why Do We Need Pandas?</h3><p>Let’s say you have this simple sales data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*nsAYyw4viiGV03D_TPNsMg.png" /></figure><p>Now if you want to find:</p><ul><li>Total revenue = Price × Quantity</li><li>Filter only products above ₹500 total revenue</li><li>Sort by price</li></ul><p>Using <strong>Python</strong> you’d write loops conditions and a lot of code. But with <strong>Pandas</strong> it’s just <strong>a few lines of code</strong>:</p><pre>import pandas as pd<br><br>data = {<br>    &quot;Product&quot;: [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;],<br>    &quot;Price&quot;: [100, 200, 150],<br>    &quot;Quantity&quot;: [3, 5, 2]<br>}<br><br>df = pd.DataFrame(data)<br>df[&quot;Revenue&quot;] = df[&quot;Price&quot;] * df[&quot;Quantity&quot;]<br>filtered = df[df[&quot;Revenue&quot;] &gt; 500].sort_values(&quot;Price&quot;, ascending=False)<br><br>print(filtered)</pre><p>Your output will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*le0s0oCeT2KbYSr_IwcvMQ.png" /></figure><p>What the hell is this code. Don’t get confused I’ll cover all of these topics in details a few minutes later.</p><h3>Why Pandas Became So Popular?</h3><ol><li>It’s <strong>easy to learn </strong>especially for those familiar with Excel.</li><li>It’s <strong>built on NumPy</strong>, so it’s <strong>fast and optimized</strong>.</li><li>It integrates with all major <strong>data science libraries</strong> (Matplotlib, Seaborn, Scikit-learn).</li><li>It helps with <strong>data cleaning, transformation, analysis, and visualization</strong>.</li></ol><h3>2. Installing and Importing Pandas</h3><p>Before we start working with Pandas, let’s first make sure it’s installed correctly on your system.<br>Without installation<strong> Python</strong> can’t recognize the Pandas library. If you haven’t install python yet in your system first go and install python.</p><h4>1. Installing Pandas</h4><p>You can install Pandas using <strong>pip</strong>.<br>Simply open your terminal or command prompt and type:</p><pre>pip install pandas</pre><p>If you are using <strong>Jupyter Notebook</strong>, you can install it directly from inside the notebook using:</p><pre><br>!pip install pandas</pre><p><em>Always make sure you’re using the latest version for new features and bug fixes.</em></p><p>You can check the installed version by running:</p><pre>import pandas as pd<br>print(pd.__version__)</pre><h4>2. Importing Pandas in Your Code</h4><p>Once Pandas is installed import it into your Python script or notebook like this:</p><pre>import pandas as pd</pre><p>Here pd is just a short alias.<br>It’s a <strong>convention</strong> used by almost every Python developer so whenever you see pd in code it means it’s referring to the Pandas library.</p><p><strong>we can just use:</strong></p><pre>import pandas as pd<br><br>pd.DataFrame()<br>pd.Series()<br>pd.read_csv()</pre><p>It keeps the code <strong>clean</strong>, <strong>short</strong>, and <strong>consistent</strong>.</p><h4>3. Verify Installation</h4><p>Let’s run a quick test to ensure everything is working fine:</p><pre>import pandas as pd<br><br>data = {<br>    &quot;Name&quot;: [&quot;Shiva&quot;, &quot;Aman&quot;, &quot;Riya&quot;],<br>    &quot;Age&quot;: [22, 25, 21],<br>    &quot;City&quot;: [&quot;Delhi&quot;, &quot;Mumbai&quot;, &quot;Pune&quot;]<br>}<br>df = pd.DataFrame(data)<br>print(df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*5e6nXBpFlP5N3meNUdJZ3g.png" /></figure><p>Congratulations! Pandas is installed successfully and you’ve created your <strong>first DataFrame</strong>! That’s your first step toward mastering pandas.</p><h3>3. Pandas Data Structures Series &amp; DataFrame Explained</h3><p>When working with Pandas, everything revolves around two core data structures:<br> 👉 <strong>Series</strong> (1-dimensional)<br> 👉 <strong>DataFrame</strong> (2-dimensional)</p><p>Let’s break them down in the easiest way possible.</p><h3>1. What is a Pandas Series?</h3><p>A <strong>Series</strong> is like a <strong>single column</strong> of data for example a list or column in Excel.</p><p>Think of it as:</p><pre>0    Apple  <br>1    Banana  <br>2    Mango  <br>dtype: object</pre><p>Each value has an <strong>index</strong> on the <strong>left </strong>and a <strong>data value</strong> on the<strong> right</strong>.</p><h4>Example:</h4><p>Let’s say you have a list of prices for products:</p><pre>import pandas as pd<br><br>prices = pd.Series([120, 250, 180], index=[&quot;Apple&quot;, &quot;Banana&quot;, &quot;Mango&quot;])<br>print(prices)</pre><p><strong>Output:</strong></p><pre>Apple     120<br>Banana    250<br>Mango     180<br>dtype: int64</pre><p>Here, we’ve assigned custom <strong>indexes</strong> (Apple, Banana, Mango) instead of <strong>0,1,2.</strong><br>So now you can easily access data like this:</p><pre>print(prices[&quot;Banana&quot;])<br><br>##output<br>250</pre><h3>2. What is a Pandas DataFrame?</h3><p>A <strong>DataFrame</strong> is like a <strong>table</strong> made up of multiple Series combined together. It has <strong>rows and columns</strong> just like an Excel or Google sheet.</p><pre>import pandas as pd<br><br>data = {<br>    &quot;Name&quot;: [&quot;Shiva&quot;, &quot;Riya&quot;, &quot;Aman&quot;],<br>    &quot;Age&quot;: [22, 21, 25],<br>    &quot;City&quot;: [&quot;Delhi&quot;, &quot;Pune&quot;, &quot;Mumbai&quot;]<br>}<br><br>df = pd.DataFrame(data)<br>print(df)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*pmRwRiVFSPF6OtmSFzuYXg.png" /></figure><h3>3. Accessing Data in DataFrame</h3><h3>Access a Single Column</h3><pre>print(df[&quot;Name&quot;])</pre><h3>Access Multiple Columns</h3><pre>print(df[[&quot;Name&quot;, &quot;City&quot;]])</pre><h3>Access Rows Using Index</h3><pre>print(df.iloc[0])  # first row</pre><p><strong>In Short:</strong></p><ul><li>Series → Single column</li><li>DataFrame → Collection of columns</li><li>Both are super fast and easy to use for data analysis.</li></ul><h3>4. Reading and Writing Data in Pandas</h3><p>In real-world projects, data usually doesn’t come manually.<br>You’ll get it from:</p><p><strong>1. Excel Sheets<br> 2. CSV files<br> 3. Databases<br> 4. JSON or APIs</strong></p><p>Pandas makes it super easy to <strong>read</strong> this data <strong>analyze</strong> it and then <strong>export</strong> the results back.</p><h3>1. Reading CSV Files</h3><p>CSV (Comma-Separated Values) is the most common file format in data analysis.</p><h4>Example:</h4><pre>import pandas as pd<br><br># Reading a CSV file<br>df = pd.read_csv(&quot;sales_data.csv&quot;)-&gt; # This is your fileName<br><br>print(df)<br><br># Display first 5 rows<br>print(df.head())</pre><p><strong>Output:</strong></p><pre>Date     Product  Region  Sales  Units  Rep  Month Quarter<br>0  2025-01-05  A  North  1050  10  Shiva  January  Q1<br>1  2025-01-06  B  South  2200  20  Riya   January  Q1<br>...</pre><p><strong>Explanation:</strong></p><ul><li>read_csv() → loads data from a .csv file.</li><li>.head() → shows first 5 rows.</li></ul><h3>2. Reading Excel Files</h3><p>To read Excel files you need the openpyxl library installed.</p><h4>Example:</h4><pre>df = pd.read_excel(&quot;sales_data.xlsx&quot;, sheet_name=&quot;Sheet1&quot;)<br>print(df.head())</pre><p><strong>Note:</strong><br> If your Excel file has multiple sheets, you can read specific ones using sheet_name.</p><h3>3. Reading JSON Files</h3><p>JSON files are widely used in APIs and modern web apps.</p><h4>Example:</h4><pre>df = pd.read_json(&quot;data.json&quot;)<br>print(df.head())</pre><h3>4. Reading Data from a URL</h3><p>You can even load CSV files directly from the internet.</p><pre>url = &quot;https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv&quot;<br>df = pd.read_csv(url)<br>print(df.head())</pre><p>This is super useful for working with <strong>open datasets</strong>.</p><h3>5. Writing Exporting Data</h3><p>Once you clean or analyze your data, you can <strong>save it back</strong> into files.</p><h4>Export to CSV:</h4><pre>df.to_csv(&quot;cleaned_sales.csv&quot;, index=False)</pre><p>index=False means Pandas won’t save row numbers in the file.</p><h4>Export to Excel:</h4><pre>df.to_excel(&quot;sales_report.xlsx&quot;, index=False)</pre><h4>Export to JSON:</h4><pre>df.to_json(&quot;sales_data.json&quot;, orient=&quot;records&quot;, indent=4)</pre><p>orient=&quot;records&quot; makes it JSON API-friendly,<br> and indent=4 makes it pretty formatted.</p><p>Pandas makes <strong>data loading and saving</strong> a one-line process. Once data is loaded You can explore clean and analyze it with ease.</p><h3>5. Basic Data Exploration in Pandas</h3><p>Before diving deep into data analysis, the first step is <strong>exploring your dataset</strong>.</p><p>Data exploration helps you answer questions like:</p><ul><li>How many rows and columns does the dataset have?</li><li>What are the data types of each column?</li><li>Are there missing values?</li><li>What are the summary statistics (mean, min, max, etc.)</li></ul><p>Pandas provides some <strong>powerful built-in functions</strong> to help with this:<br> head(), tail(), info(), and describe().</p><h3>1. Head (Preview the Top Rows)</h3><p>When working with a large dataset (thousands of rows), it’s impractical to print everything.</p><p>The head() function displays the <strong>first few rows</strong> (default is 5).</p><h4>Example:</h4><pre>import pandas as pd<br><br>df = pd.read_csv(&quot;sales_data.csv&quot;)<br>print(df.head())</pre><p><strong>Output:</strong></p><pre>Date Product Region  Sales  Units    Rep    Month Quarter<br>0  2025-01-05      A  North   1050     10   Shiva  January      Q1<br>1  2025-01-06      B  South   2200     20    Riya  January      Q1<br>2  2025-02-10      A   West   3300     30    Aman  February    Q1<br>...</pre><p>You can also specify the number of rows:</p><pre>df.head(10)  # Shows the top 10 rows</pre><h3>2. Tail (Preview the Bottom Rows)</h3><p>The tail() function shows the <strong>last few rows</strong> (default = 5).</p><p>This is useful to check <strong>recent data entries</strong>.</p><h4>Example:</h4><pre>import pandas as pd<br><br>df = pd.read_csv(&quot;sales_data.csv&quot;)<br>print(df.tail(3))</pre><p><strong>Output:</strong></p><pre>Date Product Region  Sales  Units    Rep    Month Quarter<br>27  2025-07-22      C  South   1800     15   Riya   July     Q3<br>28  2025-08-15      B   East   2900     25   Aman   August   Q3<br>29  2025-09-05      A  North   2500     20   Shiva  September Q3</pre><h3>3. Info (Understand the Dataset Structure)</h3><p>The info() function provides a <strong>quick overview</strong> of your dataset, including:</p><ul><li>Total rows and columns</li><li>Column names</li><li>Data types (int, float, object)</li><li>Non-null counts (helpful for detecting missing data)</li></ul><h4>Example:</h4><pre>df.info()</pre><p><strong>Output:</strong></p><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 30 entries, 0 to 29<br>Data columns (total 8 columns):<br> #   Column   Non-Null Count  Dtype  <br>---  ------   --------------  -----<br> 0   Date     30 non-null     object<br> 1   Product  30 non-null     object<br> 2   Region   30 non-null     object<br> 3   Sales    30 non-null     int64<br> 4   Units    30 non-null     int64<br> 5   Rep      30 non-null     object<br> 6   Month    30 non-null     object<br> 7   Quarter  30 non-null     object<br>dtypes: int64(2), object(6)<br>memory usage: 2.0 KB</pre><p><em>Think of this as a </em><strong><em>health report</em></strong><em> of your dataset.</em></p><h3>🔹 4. Describe (Statistical Summary)</h3><p>describe() provides a <strong>statistical overview</strong> of numeric columns, including:</p><ul><li>count</li><li>mean</li><li>standard deviation (std)</li><li>minimum (min)</li><li>maximum (max)</li><li>percentiles (25%, 50%, 75%)</li></ul><h4>Example:</h4><pre>df.describe()</pre><p><strong>Output:</strong></p><pre>Sales      Units<br>count   30.000000  30.000000<br>mean   2250.000000  20.000000<br>std     950.000000   7.000000<br>min    1000.000000  10.000000<br>25%    1600.000000  15.000000<br>50%    2100.000000  20.000000<br>75%    2800.000000  25.000000<br>max    4000.000000  35.000000</pre><p>To include <strong>all columns</strong> (numeric + non-numeric):</p><pre>df.describe(include=&#39;all&#39;)</pre><p>This gives summary for categorical columns as well:</p><ul><li>unique values</li><li>most frequent value (top)</li><li>frequency of top value (freq)</li></ul><h3>5. Additional Quick Attributes</h3><p>Some other attributes are very handy for quick exploration:</p><ul><li><strong>Dataset size:</strong></li></ul><pre>df.shape  # Returns (30, 8) → 30 rows, 8 columns</pre><ul><li><strong>Column names:</strong></li></ul><pre>df.columns</pre><ul><li><strong>Data types:</strong></li></ul><pre>df.dtypes</pre><h3>6. Combining Data in Pandas (Concat) (Merge) and (Join)</h3><p>In real-world projects, data rarely comes in a single file.<br>You often have <strong>multiple tables or CSVs</strong> that need to be combined for analysis.</p><p>Pandas provides <strong>three powerful methods</strong> for combining datasets:</p><ol><li><strong>concat()</strong> → Stacking datasets vertically or horizontally</li><li><strong>merge()</strong> → SQL-style joins (inner, outer, left, right)</li><li><strong>join()</strong> → Join based on index</li></ol><p>Let’s explore each in detail with examples.</p><h3>1.Concatenate.</h3><p>concat() is used to <strong>stack DataFrames</strong> either <strong>vertically (rows)</strong> or <strong>horizontally (columns)</strong>.</p><h4>Example: Vertical Concatenation</h4><pre>import pandas as pd<br><br>df1 = pd.DataFrame({<br>    &quot;Product&quot;: [&quot;A&quot;, &quot;B&quot;],<br>    &quot;Sales&quot;: [1000, 2000]<br>})<br>df2 = pd.DataFrame({<br>    &quot;Product&quot;: [&quot;C&quot;, &quot;D&quot;],<br>    &quot;Sales&quot;: [1500, 2500]<br>})<br># Combine vertically<br>result = pd.concat([df1, df2])<br>print(result)</pre><p><strong>Output:</strong></p><pre>Product  Sales<br>0       A   1000<br>1       B   2000<br>0       C   1500<br>1       D   2500</pre><p>Tip: You can reset the index if needed:</p><pre>result = pd.concat([df1, df2], ignore_index=True)</pre><h4>Example: Horizontal Concatenation</h4><pre>df3 = pd.DataFrame({&quot;Region&quot;: [&quot;North&quot;, &quot;South&quot;]})<br>df4 = pd.DataFrame({&quot;Rep&quot;: [&quot;Shiva&quot;, &quot;Riya&quot;]})<br><br># Combine horizontally<br>result = pd.concat([df3, df4], axis=1)<br>print(result)</pre><p><strong>Output:</strong></p><pre>Region    Rep<br>0  North  Shiva<br>1  South   Riya</pre><p><strong><em>Use Case:</em></strong><em> Use </em><em>concat() when you want to </em><strong><em>stack datasets with similar structure</em></strong><em> or </em><strong><em>add new columns</em></strong><em>.</em></p><h3>2. Merge.</h3><p>merge() allows combining datasets based on <strong>common columns or keys</strong>.</p><h4>Example:</h4><pre>import pandas as pd<br><br>df1 = pd.DataFrame({<br>    &quot;Product&quot;: [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;],<br>    &quot;Sales&quot;: [1000, 2000, 1500]<br>})<br><br>df2 = pd.DataFrame({<br>    &quot;Product&quot;: [&quot;A&quot;, &quot;B&quot;, &quot;D&quot;],<br>    &quot;Region&quot;: [&quot;North&quot;, &quot;South&quot;, &quot;East&quot;]<br>})<br># Merge on &#39;Product&#39;<br>result = pd.merge(df1, df2, on=&quot;Product&quot;, how=&quot;inner&quot;)<br>print(result)</pre><p><strong>Output (Inner Join):</strong></p><pre>Product  Sales Region<br>0       A   1000  North<br>1       B   2000  South</pre><h4>Example: Outer Merge</h4><pre>result = pd.merge(df1, df2, on=&quot;Product&quot;, how=&quot;outer&quot;)<br>print(result)</pre><p><strong>Output:</strong></p><pre>Product  Sales Region<br>0       A   1000  North<br>1       B   2000  South<br>2       C   1500    NaN<br>3       D    NaN   East</pre><p>innerOnly matching keys</p><p>outerAll keys from both DataFrames</p><p>leftAll keys from left DataFrame</p><p>rightAll keys from right DataFrame</p><p><strong><em>Use Case:</em></strong><em> Use </em><em>merge() when datasets share </em><strong><em>common columns or keys</em></strong><em> like SQL tables.</em></p><h3>3. Join.</h3><p>join() is similar to merge but <strong>mainly works with indexes</strong> instead of columns.</p><h4>Example:</h4><pre>import pandas as pd<br><br>df1 = pd.DataFrame({<br>    &quot;Sales&quot;: [1000, 2000]<br>}, index=[&quot;A&quot;, &quot;B&quot;])<br><br>df2 = pd.DataFrame({<br>    &quot;Region&quot;: [&quot;North&quot;, &quot;South&quot;]<br>}, index=[&quot;A&quot;, &quot;B&quot;])<br>result = df1.join(df2)<br>print(result)</pre><p><strong>Output:</strong></p><pre>Sales Region<br>A   1000  North<br>B   2000  South</pre><p><strong><em>Use Case:</em></strong><em> Use </em><em>join() when your </em><strong><em>indexes match</em></strong><em> and you want a simple, fast combination.</em></p><p>That’s it for this article! We’ve covered only these topics for now, but we’re not done yet. There are still many important concepts remaining like <strong>Pivot Tables</strong>, <strong>Grouping &amp; Aggregation</strong>, <strong>Lambda Functions</strong>, and much more.<br>We’ll be covering all of these in the <strong>next blog article</strong>.</p><p>If you found this article helpful drop a clap or a comment your support keeps me writing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccab4f97e37e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>