<?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 Rishaw Kumar Singh on Medium]]></title>
        <description><![CDATA[Stories by Rishaw Kumar Singh on Medium]]></description>
        <link>https://medium.com/@rishaw-kumar?source=rss-45749c5ed508------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2yiVzgV8gFE4VPFsLcOB8g.jpeg</url>
            <title>Stories by Rishaw Kumar Singh on Medium</title>
            <link>https://medium.com/@rishaw-kumar?source=rss-45749c5ed508------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:53:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rishaw-kumar/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[Build and Deploy a Three-Tier React-Flask-RDS App on AWS EKS with Kubernetes Ingress & ALB]]></title>
            <link>https://rishaw-kumar.medium.com/build-and-deploy-a-three-tier-react-flask-rds-app-on-aws-eks-with-kubernetes-ingress-alb-04c321caf233?source=rss-45749c5ed508------2</link>
            <guid isPermaLink="false">https://medium.com/p/04c321caf233</guid>
            <category><![CDATA[aws-eks-using-terraform]]></category>
            <category><![CDATA[three-tier-architecture]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[elastickubernetesservice]]></category>
            <category><![CDATA[aws-eks]]></category>
            <dc:creator><![CDATA[Rishaw Kumar Singh]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 17:30:25 GMT</pubDate>
            <atom:updated>2025-07-08T17:30:25.626Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ll set up an EKS cluster with a comprehensive three-tier application. The application is made up of a Flask backend API for business logic, a React frontend for the user interface, and a private connection to an RDS PostgreSQL database for persistent storage.</p><p>I’ll use the AWS Load Balancer Controller to automatically create and configure an Application Load Balancer using Kubernetes Ingress resources in order to make the application publicly accessible. ConfigMaps will be used for configuration, while Kubernetes Secrets will be used to hold private database credentials.</p><p>I’ll use a Kubernetes Job to do database migrations and make sure the schema is correctly initialised prior to launching the backend service. I’ll use an External Service for the RDS instance to streamline database connectivity, use Kubernetes’ DNS-based service discovery to keep the application configuration clean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*F9ZoGISf4u-OUazmhl0BWw.png" /></figure><h3>Kubernetes in 2025</h3><p>You’ve probably heard of Kubernetes if you work in the tech industry in 2025. If not, there’s a problem — see if you’ve been sleeping for the past ten years!</p><p>Jokes aside, Kubernetes has grown to be a very popular solution for easily operating microservices or large-scale containerised systems. Working with Kubernetes is essential if you want to remain relevant in your role as a developer, SRE, or DevOps engineer.</p><p>Because Kubernetes can be difficult to set up and maintain, the majority of well-known public cloud providers provide Kubernetes managed services. AKS (Azure), GKE (GCP), and EKS (AWS) are the most popular.</p><p>I will utilize Amazon EKS, which is AWS’s managed Kubernetes service, to deploy my three-tier application. EKS offers a managed Kubernetes control plane and gives you the flexibility to run your workloads according to your preferences. There are three options available for running workloads in EKS:</p><ul><li>Managed Node Group — AWS takes care of the nodes, including scaling and updates.</li><li>Self-managed node group — You are responsible for managing the nodes, configuring autoscaling, applying patches, and more. This option is beneficial when you need to customize the nodes for specific requirements (like security or compliance) and determine the timing and method for patching your cluster nodes.</li><li>Fargate Nodes — Deploy your workload without the need for EC2 nodes by using a Fargate profile (with AWS handling everything on your behalf).This has limitations as you cannot use persistent volumes with Fargate; it only supports EFS.</li></ul><p>I plan to utilize the EKSCTL tool to create the EKS cluster along with a Managed node group.</p><h3>Creating EKS cluster with EKSCTL</h3><p>To set up an EKS cluster using EKSCTL, you need to have EKSCTL, AWS CLI, Kubectl, and Helm installed on your system. Additionally, ensure you have the credentials for your AWS account to provision the necessary resources.</p><p>Please note: <a href="https://github.com/rishawsingh/prod-eks-setup.git">I’ve included all the source code for the backend, frontend, and Kubernetes manifest files in my public GitHub repository.</a></p><pre># EKS ctl command to build an EKS cluster with a managed node group<br># with 2 node(min:1, max: 3 nodes as autoscaling)</pre><pre>eksctl create cluster \<br>  --name rishaw-prd-cluster \<br>  --region eu-west-1 \<br>  --version 1.31 \<br>  --nodegroup-name standard-workers \<br>  --node-type t3.medium \<br>  --nodes 2 \<br>  --nodes-min 1 \<br>  --nodes-max 3 \<br>  --managed</pre><p>When we execute EKSCTL commands, a CloudFormation stack is initiated in the background to set up the resources, specifically the EKS cluster in this instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ppksUECDDG8bGt-C8RtKhA.png" /><figcaption>EKS Cluster creation</figcaption></figure><p>This process will generate a new VPC, subnets, a NAT gateway, and an EKS cluster that includes a managed node group</p><ul><li>List the cluster</li></ul><pre>aws eks list-clusters --region eu-west-1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*2nDrMJQYVB4PBP5kePzdLg.png" /></figure><ul><li>Setting up the cluster config to access the cluster from the local machine.</li></ul><pre>export cluster_name=rishaw-prd-cluster # Name of the cluster<br>echo $cluster_name</pre><pre># Configure the kube config<br>aws eks update-kubeconfig --name $cluster_name --region eu-west-1</pre><pre># Get the current context<br>kubectl config current-context</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*c-6x8FiVvCrA7O7fZlQn8w.png" /></figure><p>Now you can connect to the EKS cluster using the kubectl command.</p><p>Note: Make sure you have installed Kubectl CLI on your local machine.</p><h3>Kubectl to connect to EKS cluster</h3><p>Let’s run some commands to see the status of the cluster</p><pre>kubectl get namespaces<br>kubectl get node<br>kubectl get pod -A<br>kubectl get services -A</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sxjklS44HDYDDP8WL8xEYQ.png" /></figure><h3>Deploying a 3-tier application on the EKS cluster</h3><p>I have created an application with a Flask backend and a React frontend that connects to an RDS instance in the backend.</p><h3>Creating RDS postgres instance</h3><p>My RDS instance will be deployed using the VPC’s private subnets, and I will set it up in the same VPC as the EKS cluster.</p><ul><li>Creating a DB subnet group</li></ul><pre># VPC ID associated with your cluster<br>aws eks describe-cluster --name rishaw-prd-cluster --region eu-west-1 --query &quot;cluster.resourcesVpcConfig.vpcId&quot; --output text</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXPxpofsQRWrRJ8UgeLpiw.png" /></figure><pre># Find private subnets (subnets without a route to an internet gateway)<br>aws ec2 describe-subnets \<br>  --filters &quot;Name=vpc-id,Values=$VPC_ID&quot; \<br>  --query &quot;Subnets[*].[SubnetId,MapPublicIpOnLaunch]&quot; \<br>  --output table \<br>  --region eu-west-1<br># Create a subnet group using only private subnet<br>aws rds create-db-subnet-group \<br>  --db-subnet-group-name rishaw-postgres-private-subnet-group \<br>  --db-subnet-group-description &quot;Private subnet group for rishaw PostgreSQL RDS&quot; \<br>  --subnet-ids subnet-085b8569d01347d60 subnet-0251a9aa85f0bec91 subnet-090b4fb5836bcf3b1 \<br>  --region eu-west-1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dx7DmYREi4WIjAEVaqowzQ.png" /></figure><ul><li>Create a security group that</li></ul><pre># Create security group for rds<br>aws ec2 create-security-group \<br>  --group-name postgressg \<br>  --description &quot;SG for RDS&quot; \<br>  --vpc-id $VPC_ID \<br>  --region eu-west-1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*BAjm50da0dALZQ9WYT9Brg.png" /></figure><p>Allows the cluster nodes to reach RDS on port 5432. For security reasons, we should only open the ports from a particular security group instead of opening it for all (0.0.0.0/0)</p><ul><li>Creating the ingress rule for the security group to permit inbound traffic on port 5432 from the Cluster Security Group.</li></ul><pre># Store the security group ID<br>SG_ID=$(aws ec2 describe-security-groups \<br>  --filters &quot;Name=group-name,Values=postgressg&quot; &quot;Name=vpc-id,Values=$VPC_ID&quot; \<br>  --query &quot;SecurityGroups[0].GroupId&quot; \<br>  --output text \<br>  --region eu-west-1)</pre><pre># get the SG attached with cluster nodes:<br>NODE_SG=$(aws eks describe-cluster --name rishaw-prd-cluster --region eu-west-1 \<br>  --query &quot;cluster.resourcesVpcConfig.securityGroupIds[0]&quot; --output text)<br># Allow cluster to reach rds on port 5432<br>aws ec2 authorize-security-group-ingress \<br>  --group-id sg-02930caf4db41a6f4 \<br>  --protocol tcp \<br>  --port 5432 \<br>  --source-group $NODE_SG \<br>  --region eu-west-1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQcSyeerGqjM35gHP3ArEw.png" /></figure><ul><li>Creating an RDS instance that can only be privately accessed.</li></ul><pre># create the PostgreSQL RDS instance in the private subnet group<br>aws rds create-db-instance \<br>  --db-instance-identifier rishaw-postgres \<br>  --db-instance-class db.t3.small \<br>  --engine postgres \<br>  --engine-version 15 \<br>  --allocated-storage 20 \<br>  --master-username postgresadmin \<br>  --master-user-password RishawStrongPassword123! \<br>  --db-subnet-group-name akhilesh-postgres-private-subnet-group \<br>  --vpc-security-group-ids $SG_ID \<br>  --no-publicly-accessible \<br>  --backup-retention-period 7 \<br>  --multi-az \<br>  --storage-type gp2 \<br>  --region eu-west-1</pre><p>As we can see that RDS instance is getting created.</p><p>The RDS will take few minutes to be ready. Once it is up, you can fetch RDS details from AWS console.</p><p><em>USERNAME: postgresadmin PASSWORD: RishawStrongPassword123!</em><em> DB_HOST:rishaw-postgres.cd8ecu8oueer.eu-west-1.rds.amazonaws.com</em><em> (You can find this in the RDS instance endpoint configuration) DB_NAME: postgres (default database name since we did not provide a custom name)</em></p><h3>Deploying a 3-tier application on EKS</h3><p>I have app images pushed on Docker Hub, I will use these images.</p><p>Backend image: shawdoesdevops/prd-eks:backend-latest</p><p>Frontend image: shawdoesdevops/prd-eks:frontend-latest</p><h4>Clone the repo</h4><pre>git clone https://github.com/rishawsingh/prod-eks-setup.git<br>cd prod-eks-setup/k8s<br>tree .</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*y0bX3ygdQxqL5MMG5me2Vw.png" /></figure><p>This is the repo with all the code.</p><h4>Create a namespace — 3-tier-app-eks</h4><blockquote>In Kubernetes, a namespace serves as a means to segregate collections of resources within a cluster. This enables teams to operate within their own virtual cluster, alleviating concerns regarding conflicts in resource naming.</blockquote><pre>kubectl apply -f namespace.yaml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*_eoT1x5R-hiVk81ZhgDaQQ.png" /></figure><h4>Creating a service pointing to the RDS endpoint</h4><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: postgres-db<br>  namespace: 3-tier-app-eks<br>  labels:<br>    service: database<br>spec:<br>  type: ExternalName<br>  externalName: rishaw-postgres.cd8ecu8oueer.eu-west-1.rds.amazonaws.com<br>  ports:<br>  - port: 5432<br>kubectl apply -f database-service.yaml</pre><blockquote>An abstraction that specifies a logical collection of pods and a policy for gaining access to them is called a service. Regardless of where pod sets are running, services allow network connection to those that meet certain selector requirements.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*cyc-iKpZlAMnvyYi-Rmw4w.png" /></figure><p>If we need to update the cluster, we can now use this service to point to RDS; we can update this service and everything will remain the same.</p><p>Service discovery now allows us to use the DNS name for RDS. The format is service_name.namespace.svc.cluster.local</p><p>We ought to be able to connect to the database using postgres-db.3-tier-app-eks.svc.cluster.local</p><p>Run this command to check the DNS</p><pre>kubectl run -it --rm --restart=Never dns-test --image=tutum/dnsutils \<br> -- dig postgres-db.3-tier-app-eks.svc.cluster.local</pre><ul><li>Testing the RDS connectivity</li></ul><p>If for some reason, you see issues on your backend, you can troubleshoot with the below commands. You can validate if you can connect to the DB from the k8s cluster and other things.</p><pre>## to check the db connection for troubleshooting<br># Run a postgres pod and access the shell<br>kubectl run debug-pod --rm -it --image=postgres -- bash<br># run this command<br>PGPASSWORD=RishawStrongPassword123! psql -h \<br>postgres-db.3-tier-app-eks.svc.cluster.local -U postgresadmin -d postgres<br># run query<br>SELECT COUNT(*) FROM topics;</pre><p>I was having issues connecting to the DB from the cluster. Issue could be related to the security group.</p><p>So for testing I allowed inbound rule to allow all IPs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eL1DYn06qHpJ1Nj7IfJsaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9SCvcEz6k6lbHL4alntbA.png" /></figure><h4>Creating a secret and configmaps with RDS DB details</h4><blockquote>Kubernetes objects that hold sensitive data like passwords, OAuth tokens, and SSH keys are known as Secrets. Non-confidential configuration data is stored in key-value pairs by ConfigMaps, which may be used by pods as command-line arguments, environment variables, or configuration files in a volume.</blockquote><p>Kubernetes allows you to store secrets in base64 encoded format.We can do base64 encoding for username, password and then mount secrets and configmap as environment variables in the application.</p><pre>echo &#39;postgresadmin&#39; | base64<br>echo &#39;RishawStrongPassword123!&#39; | base64<br>echo &#39;postgresql://postgresadmin:RishawStrongPassword123!@postgres-db.3-tier-app-eks.svc.cluster.local:5432/postgres&#39; | base64</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t5Mjjdusx7z9yrqq5MNi1w.png" /></figure><p>secrets.yaml</p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: db-secrets<br>  namespace: 3-tier-app-eks<br>type: Opaque<br>data:<br>  DB_USERNAME: cG9zdGdyZXNhZG1pbg==<br>  DB_PASSWORD: WW91clN0cm9uZ1Bhc3N3b3JkMTIzIQ==<br>  SECRET_KEY: ZGV2LXNlY3JldC1rZXk=<br>  DATABASE_URL: cG9zdGdyZXNxbDovL3Bvc3RncmVzYWRtaW46WW91clN0cm9uZ1Bhc3N3b3JkMTIzIUBwb3N0Z3Jlcy1kYi4zLXRpZXItYXBwLWVrcy5zdmMuY2x1c3Rlci5sb2NhbDo1NDMyL3Bvc3RncmVz</pre><p>configmap.yaml</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: app-config<br>  namespace: 3-tier-app-eks<br>data:<br>  DB_HOST: &quot;postgres-db.3-tier-app-eks.svc.cluster.local&quot;<br>  DB_NAME: &quot;postgres&quot;<br>  DB_PORT: &quot;5432&quot;<br>  FLASK_DEBUG: &quot;0&quot;</pre><p>Run these commands</p><pre>kubectl apply -f configmap.yaml <br>kubectl apply -f secrets.yaml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7BIphTpV_ZzVRMfsN9Jk5A.png" /></figure><h4>Executing the database migrations job</h4><p>Prior to initiating our backend Flask API, we must execute database migrations. This will be executed as a Kubernetes job that will establish the database tables and seed data necessary for the application.</p><blockquote>A Kubernetes job produces one or more pods and guarantees that they will complete their execution. Data migrations, batch processes, or one-time operations that must be completed benefit from the use of jobs.</blockquote><p>Use following command to run the migration job</p><pre>kubectl apply -f migration_job.yaml<br>kubectl get job -A<br>kubectl get pods -n 3-tier-app-eks<br>kubectl logs database-migration-nlz9f -n 3-tier-app-eks</pre><p>This migration job will create the database tables and the seed data that your application will have at the start</p><h4>Initiate the deployments for both the backend and frontend.</h4><blockquote>A deployment is a resource in Kubernetes that facilitates declarative updates for pods and replica sets. It enables you to outline the life cycle of an application, specifying the images to be utilized, the quantity of pods, and the methods for updating them.</blockquote><pre># Creating frontend and backend deployments and services<br>kubectl apply -f backend.yaml<br>kubectl apply -f frontend.yaml</pre><pre># checking the deployments and services<br>kubectl get deployment -n 3-tier-app-eks<br>kubectl get svc -n 3-tier-app-eks<br>kubectl get po -n 3-tier-app-eks</pre><h3>Accessing the application</h3><p>We have not set up any ingress; however, we can reach the application by port-forwarding the services (both the backend and the frontend). It is advisable to utilize multiple tabs, as both services must be accessible through port forwarding.</p><pre># port forward backend<br>kubectl port-forward -n 3-tier-app-eks svc/backend 8000:8000</pre><pre># port forward the frontend <br>kubectl port-forward -n 3-tier-app-eks svc/frontend 8080:80</pre><p>You can access the backend API with the command curl <a href="http://localhost:8000/api/topics">http://localhost:8000/api/topics</a></p><p>You can access the frontend on localhost on port 8080 127.0.0.1:8080</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*HjuENX68G7h2JjeQ.png" /></figure><p>This is a quiz application around devops topics. Seed data only creates a few questions, you can add more questions using the manage question option. I have added sample csv files on the path, 3-tier-app-eks/backend/questions-answers that you can upload to add more questions.</p><p>Check the pods’ logs for backend and frontend deployment.</p><pre>kubectl logs -n devops-learning -l app=backend</pre><pre>kubectl logs -n devops-learning -l app=frontend</pre><h3>Configuring the ingress for the application</h3><blockquote>An ingress is a resource in Kubernetes that oversees external access to services within a cluster, usually through HTTP/HTTPS. It offers load balancing, SSL termination, and name-based virtual hosting.</blockquote><p>The AWS Load Balancer Controller facilitates the automatic creation of AWS Application Load Balancers when Kubernetes Ingress resources are established. This integration enables smooth traffic routing to your services while utilizing AWS-native features such as SSL termination, HTTP/2 support, and web ACLs.</p><h4>Set up OIDC provider for the EKS cluster to enable IAM roles for service accounts</h4><pre>export cluster_name=rishaw-prd-cluster</pre><pre>oidc_id=$(aws eks describe-cluster --name $cluster_name \<br>--query &quot;cluster.identity.oidc.issuer&quot; --output text | cut -d &#39;/&#39; -f 5)</pre><pre>echo $oidc_id</pre><pre># Check if IAM OIDC provider with your cluster&#39;s issuer ID <br>aws iam list-open-id-connect-providers | grep $oidc_id | cut -d &quot;/&quot; -f4</pre><pre># If not, create an OIDC provider<br>eksctl utils associate-iam-oidc-provider --cluster $cluster_name --approve</pre><pre># or use console<br># -&gt; To create a provider, go to IAM, choose Add provider.<br># -&gt; For Provider type, select OpenID Connect.<br># -&gt; For Provider URL, enter the OIDC provider URL for your cluster.<br># -&gt; For Audience, enter sts.amazonaws.com.<br># -&gt; (Optional) Add any tags, for example a tag to identify which cluster is for this provider.<br># -&gt; Choose Add provider.</pre><h4>Create IAM policy with necessary permissions for the Load Balancer Controller</h4><pre>curl -O https://raw.githubusercontent.com/kubernetes-sigs/aws-load-balancer-controller/v2.11.0/docs/install/iam_policy.json<br>aws iam create-policy \<br>    --policy-name AWSLoadBalancerControllerIAMPolicy \<br>    --policy-document file://iam_policy.json</pre><h4>Create IAM service account in Kubernetes with the policy attached</h4><pre># Use the account id for your account<br>eksctl create iamserviceaccount \<br>  --cluster=$cluster_name \<br>  --namespace=kube-system \<br>  --name=aws-load-balancer-controller \<br>  --role-name AmazonEKSLoadBalancerControllerRole \<br>  --attach-policy-arn=arn:aws:iam::163962758712:policy/AWSLoadBalancerControllerIAMPolicy \<br>  --approve</pre><pre># verify its creation <br>kubectl get serviceaccount -n kube-system | grep -i aws-load-balancer-controller</pre><h4>Installing the AWS Load balancer Controller with Helm</h4><pre># Install the AWS Load Balancer Controller</pre><pre>kubectl apply -k  \<br>&quot;github.com/aws/eks-charts/stable/aws-load-balancer-controller/crds?ref=master&quot;</pre><pre># install helm if haven&#39;t already<br>brew install helm # (for mac, google for other platforms)</pre><pre># Add helm repo for eks charts<br>helm repo add eks <a href="https://aws.github.io/eks-charts">https://aws.github.io/eks-charts</a><br>helm repo update</pre><pre>VPC_ID=$(aws eks describe-cluster --name rishaw-prd-cluster --region eu-west-1 --query &quot;cluster.resourcesVpcConfig.vpcId&quot; --output text)</pre><pre>helm install aws-load-balancer-controller eks/aws-load-balancer-controller \<br>  -n kube-system \<br>  --set clusterName=$cluster_name \<br>  --set serviceAccount.create=false \<br>  --set serviceAccount.name=aws-load-balancer-controller \<br>  --set vpcId=$VPC_ID \<br>  --set region=eu-west-1</pre><h4>Creating an Ingress class for alb and an Ingress resource to access the frontend service</h4><p>Configuring Ingress resources with appropriate annotations for routing rules</p><p>ingress.yaml</p><pre>apiVersion: networking.k8s.io/v1<br>kind: IngressClass<br>metadata:<br>  name: alb<br>  annotations:<br>    ingressclass.kubernetes.io/is-default-class: &quot;false&quot;<br>spec:<br>  controller: ingress.k8s.aws/alb<br>---<br>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: 3-tier-app-ingress<br>  namespace: 3-tier-app-eks<br>  annotations:<br>    alb.ingress.kubernetes.io/scheme: &quot;internet-facing&quot;<br>    alb.ingress.kubernetes.io/target-type: &quot;ip&quot;<br>    alb.ingress.kubernetes.io/healthcheck-path: &quot;/&quot;  # healthcheck path<br>spec:<br>  ingressClassName: &quot;alb&quot;<br>  rules:<br>  - http:<br>      paths:<br>      - path: /api<br>        pathType: Prefix<br>        backend:<br>          service:<br>            name: backend<br>            port:<br>              number: 8000<br>      - path: /<br>        pathType: Prefix<br>        backend:<br>          service:<br>            name: frontend<br>            port:<br>              number: 80<br># Create ingress class and resource<br>kubectl apply -f ingress.yaml</pre><pre># Check the ingress and load balancer controller logs<br>kubectl get ingress -n 3-tier-app-eks<br>kubectl describe ingress 3-tier-app-ingress -n 3-tier-app-eks</pre><pre># After ingress creation<br>kubectl logs -n kube-system -l app.kubernetes.io/name=aws-load-balancer-controller</pre><pre># delete ingress<br>kubectl delete ingress 3-tier-app-ingress -n 3-tier-app-eks </pre><pre># If above doesnt work, use this to force delete<br>kubectl patch ingress 3-tier-app-ingress -n 3-tier-app-eks -p &#39;{&quot;metadata&quot;:{&quot;finalizers&quot;:[]}}&#39; --type=merge<br>kubectl delete ingress 3-tier-app-ingress -n 3-tier-app-eks --grace-period=0 --force</pre><p>Before you create an ingress resource, make sure you apply the tag Key=kubernetes.io/role/internal-elb,Value=1 to public subnets for the application load balancer.</p><p><em>Note: if you are creating the network load balancers, then add</em> Key=kubernetes.io/role/internal-nlb,Value=1 <em>tag to the subnets where you want to get NLBs.</em></p><h4>List the public subnet for the EKS cluster, and apply the tag</h4><pre># VPC_ID for cluster<br>VPC_ID=$(aws eks describe-cluster --name rishaw-prd-cluster --region eu-west-1 --query &quot;cluster.resourcesVpcConfig.vpcId&quot; --output text)</pre><pre># verify the vpc id<br>echo $VPC_ID</pre><pre># Public subnets for the cluster<br>aws ec2 describe-subnets --filters &quot;Name=vpc-id,Values=$VPC_ID&quot; &quot;Name=map-public-ip-on-launch,Values=true&quot; \<br>--query &quot;Subnets[*].{SubnetId:SubnetId,AvailabilityZone:AvailabilityZone,PublicIp:MapPublicIpOnLaunch}&quot;</pre><pre># Get the list of subnets id&#39;s from above commands and run this<br># Update the correct subnet id&#39;s<br>aws ec2 create-tags --resources subnet-064aetfgh6741723 subnet-043gfd44yu3c \<br>subnet-0123rewsdsg974 --tags Key=kubernetes.io/role/elb,Value=1</pre><pre># Verify the tags<br>aws ec2 describe-subnets --subnet-ids subnet-064aetfgh6741723 subnet-043gfd44yu3c \<br>subnet-0123rewsdsg974 --query &quot;Subnets[*].{SubnetId:SubnetId,Tags:Tags}&quot;</pre><p>Once this is done we can deploy ingress resource and it should automatically spin up the ALB.</p><pre># Create ingress class and resource<br>kubectl apply -f ingress.yaml</pre><pre># Check the ingress and load balancer controller logs<br>kubectl get ingress -n 3-tier-app-eks<br>kubectl describe ingress 3-tier-app-ingress -n 3-tier-app-eks</pre><pre># After ingress creation<br>kubectl logs -n kube-system -l app.kubernetes.io/name=aws-load-balancer-controller</pre><p>Wait for few mins and then you can go to your AWS console where you will see an ALB there. Copy the DNS name for it and paste it in the browser, and you should be able to see your app there.</p><h4>Validate ALB provisioning and test the routing to backend services</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*z3V1sYAZurNmTtQW.png" /></figure><p>Now we need to map our domain to the application to access it publicly</p><ul><li>Create a public hosted zone for your registered domain</li></ul><pre>aws route53 create-hosted-zone \<br>  --name your-domain.com \<br>  --caller-reference $(date +%s) \<br>  --hosted-zone-config Comment=&quot;Public hosted zone for akhileshmishra.tech&quot;</pre><p>Copy the name servers from hosted zone and update them in your domain (godaddy/namecheap, etc).</p><p>Now create an alias route to point your domain/subdomain to the ALB.</p><pre># Get the ALB DNS name from the Ingress<br>ALB_DNS=$(kubectl get ingress 3-tier-app-ingress -n 3-tier-app-eks -o jsonpath=&#39;{.status.loadBalancer.ingress[0].hostname}&#39;)<br>echo &quot;ALB DNS Name: $ALB_DNS&quot;</pre><pre># Get the hosted zone ID for your domain<br>ZONE_ID=$(aws route53 list-hosted-zones-by-name --dns-name your-domain.com --query &quot;HostedZones[0].Id&quot; --output text | sed &#39;s/\/hostedzone\///&#39;)<br>echo &quot;Hosted Zone ID: $ZONE_ID&quot;</pre><pre># Create an A record alias pointing to the ALB<br>aws route53 change-resource-record-sets \<br>  --hosted-zone-id $ZONE_ID \<br>  --change-batch &#39;{<br>    &quot;Changes&quot;: [<br>      {<br>        &quot;Action&quot;: &quot;UPSERT&quot;,<br>        &quot;ResourceRecordSet&quot;: {<br>          &quot;Name&quot;: &quot;app.your-domain.com&quot;,<br>          &quot;Type&quot;: &quot;A&quot;,<br>          &quot;AliasTarget&quot;: {<br>            &quot;HostedZoneId&quot;: &quot;ZE2395QML12A&quot;,<br>            &quot;DNSName&quot;: &quot;&#39;$ALB_DNS&#39;&quot;,<br>            &quot;EvaluateTargetHealth&quot;: true<br>          }<br>        }<br>      }<br>    ]<br>  }&#39;</pre><p>It takes some time for the DNS change to reflect, try pasting the subdomain (app.your-domain.com) in your browser after some time, it should show you the application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04c321caf233" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Architecture Explained: How It All Fits Together]]></title>
            <link>https://rishaw-kumar.medium.com/kubernetes-architecture-explained-how-it-all-fits-together-d5ef1b8e4ed2?source=rss-45749c5ed508------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5ef1b8e4ed2</guid>
            <category><![CDATA[etcd]]></category>
            <category><![CDATA[kubernetes-cluster]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kube-proxy]]></category>
            <category><![CDATA[kubernetes-architecture]]></category>
            <dc:creator><![CDATA[Rishaw Kumar Singh]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 18:06:45 GMT</pubDate>
            <atom:updated>2025-07-02T18:06:45.850Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*wTnspbDEm1yY73jH4wgt0A.jpeg" /><figcaption>Kubernetes Logo</figcaption></figure><p><strong>Introduction</strong></p><p>The purpose of Kubernetes is to host your applications in the form of containers in an automated fashion so that you can easily deploy as many instances of your application as required and easily enable communication between different services within your application. In this article we will be looking into the key components of Kubernetes.</p><p><strong>Table of contents:</strong></p><ul><li><em>Etcd</em></li><li><em>Kube API Server</em></li><li><em>Kube Controller Manager</em></li><li><em>Kube Scheduler</em></li><li><em>Kubelet</em></li><li><em>Kube-proxy</em></li></ul><h3>Etcd</h3><p>It is a distributed, reliable, key-value store that is simple, secure, and fast. So let’s deep-dive more into it.</p><p>So what is a key-value store?</p><p>Traditionally, databases have been in a tabular format, you must have heard about SQL or relational databases. They store data in the form of rows and columns whereas A key-value store stores information in the form of documents or pages.</p><p>It’s easy to install and get started with ETCD. Download the relevant binary for your operating system from the GitHub Releases pages, extract it, and run the ETCD executable.</p><p>When you run ETCD, it starts a service that listens on port 2379 by default.</p><p>You can then attach any clients to the ETCD service to store and retrieve information. A default client that comes with ETCD is the ETCDCTL client. The ETCDCTL client is a command line client for ETCD.</p><p>You can use it to store and retrieve key-value pairs.</p><p>You might come across different versions of commands while exploring ETCD and related articles online, so it’s important to understand the history of ETCD releases so you know what changed, when.</p><p>The first version of ETCD, v0.1 was released in August, 2013. The official stable version, v2.0 was released in February, 2015 And in January, 2017, ETCD released v3.0 with a lot more optimizations and performance improvements. And finally in November, 2018, that’s when the ETCD project was incubated in CNCF.</p><h3><strong>Kube-Api Server</strong></h3><p>The kube-apiserver is the primary management component in Kubernetes. When you run a kubectl command, the kubectl utility reaches out to the kube-apiserver.</p><p>The kube-apiserver first authenticates the request and validates it. It then retrieves the data from the etcd cluster and responds back with the requested information.</p><p>You don’t really need to use the kubectl command line. Instead, you could also invoke the APIs directly by sending a POST request as well.</p><p>Let’s look at an example of creating a pod.</p><p>When you create a pod, the request is authenticated first and then validated. In this case, the API server creates a pod object without assigning it to a node. Updates the information in the etcd server, updates the user that the pod has been created. The scheduler continuously monitors the API server and realizes that there is a new pod with no node assigned. The scheduler identifies the right node to place the new pod on and communicates that back to the kube-apiserver. The API server then updates the information in the etcd cluster. The API server then passes that information to the kubelet in the appropriate worker node. The kubelet then creates the pod on the node and instructs the container runtime engine to deploy the application image. Once done, the kubelet updates the status back to the API server and the API server then updates the data back in the etcd cluster.</p><p>A similar pattern is followed every time a change is requested. The kube-apiserver is at the center of all the different tasks that needs to be performed to make a change in the cluster.</p><p>To summarize, the kube-apiserver is responsible for authenticating and validating requests, retrieving and updating data in the etcd data store.</p><p>In fact, kube-apiserver is the only component that interacts directly with the etcd data store. The other components, such as the scheduler, kube-controller-manager and kubelet uses the API server to perform updates in the cluster in their respective areas.</p><h3>Kube Controller Manager</h3><p>In the Kubernetes terms a controller is a process that continuously monitors the state of various components within the system and works towards bringing the whole system to the desired functioning state.</p><p>For example, the node controller is responsible for monitoring the status of the nodes and taking necessary actions to keep the applications running. It does that through the Kube API server. The node controller tests the status of the notes every five seconds. That way the node controller can monitor the health of the nodes. If it stops receiving heartbeat from a node the node is marked as unreachable but it waits for 40 seconds before marking it unreachable. After a node is marked unreachable it gives it five minutes to come back up. If it doesn’t, it removes the PODs assigned to that note and provisions them on the healthy ones if the PODs are part of a replica set.</p><p>The next controller is the replication controller.</p><p>It is responsible for monitoring the status of replica sets and ensuring that the desired number of PODs are available at all times within the set. If a POD dies, it creates another one. Now, those were just two examples of controllers. There are many more such controllers available within Kubernetes.</p><p>Now, how do you see these controllers and where are they located in your cluster?</p><p>They’re all packaged into a single process known as the Kubernetes Controller Manager. When you install the Kubernetes controller manager the different controllers get installed as well.</p><p>So how do you install and view the Kubernetes controller manager?</p><p>Download the Kube controller manager from the Kubernetes release page, extract it and run it as a service. When you run it, as you can see there are a list of options provided. This is where you provide additional options to customize your controller.</p><p>In short: A controller is a process that continuously monitors the state of various components within the system and works towards bringing the whole system to the desired functioning state</p><h3>Kube Scheduler</h3><p>In Kubernetes, the scheduler decides which nodes the pods are placed on depending on certain criteria. You may have pods with different resource requirements. You can have nodes in the cluster dedicated to certain applications.</p><p>So how does the scheduler assign these pods?</p><p>The scheduler looks at each pod and tries to find the best node for it.</p><p>They are dependent on various factors, such as resource requirements, limits, taints and tolerations, node selectors, affinity rules,etc.</p><h3>Kubelet</h3><p>An agent that runs on each <a href="https://kubernetes.io/docs/concepts/architecture/nodes/">node</a> in the cluster. It makes sure that <a href="https://kubernetes.io/docs/concepts/containers/">containers</a> are running in a <a href="https://kubernetes.io/docs/concepts/workloads/pods/">Pod</a>.</p><p>The kubelet in the Kubernetes worker node registers the node with a Kubernetes cluster. When it receives instructions to load a container or a pod on the node, it requests the container runtime engine, which may be Docker, to pull the required image and run an instance. The kubelet then continues to monitor the state of the pod and containers in it and reports to the kube API server on a timely basis.</p><p>You must always manually install the kubelet on your worker nodes.</p><h3>Kube-proxy</h3><p>Within a Kubernetes cluster, every pod can reach every other pod. This is accomplished by deploying a pod networking solution to the cluster. A pod network is an internal virtual network that spans across all the nodes in the cluster to which all the pods connect to. Through this network, they’re able to communicate with each other.</p><p>Kube-proxy is a process that runs on each node in the Kubernetes cluster. Its job is to look for new services, and every time a new service is created, it creates the appropriate rules on each node to forward traffic to those services to the backend pods. One way it does this is using iptables rules.</p><p><strong>Note:</strong> Kubeproxy it is deployed as a Daemon Set, so a simple POD is always deployed on each node in the cluster.</p><h3>Conclusion</h3><p>Kubernetes’ architecture is like a well-designed city: modular, resilient, and built to scale. The control plane keeps everything in check, while nodes handle the heavy lifting. By understanding how these pieces fit together, you’re better equipped to troubleshoot issues, optimize performance, and build robust systems.</p><p>Whether you’re just starting out or leveling up your Kubernetes skills, grasping this architecture lays the groundwork for success. Keep exploring, and you’ll be orchestrating containers like a pro in no time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5ef1b8e4ed2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Dockerized Application on VM with Jenkinsfile]]></title>
            <link>https://rishaw-kumar.medium.com/title-deploying-dockerized-application-on-ec2-or-azure-vm-with-jenkins-pipeline-jenkinsfile-dba5e294df?source=rss-45749c5ed508------2</link>
            <guid isPermaLink="false">https://medium.com/p/dba5e294df</guid>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[jenkins-automation]]></category>
            <category><![CDATA[jenkinsfile]]></category>
            <category><![CDATA[jenkins-pipeline]]></category>
            <category><![CDATA[deployment-pipelines]]></category>
            <dc:creator><![CDATA[Rishaw Kumar Singh]]></dc:creator>
            <pubDate>Thu, 22 Jun 2023 21:43:25 GMT</pubDate>
            <atom:updated>2025-07-03T17:24:33.924Z</atom:updated>
            <content:encoded><![CDATA[<p>Complete END-to-END deployment using declarative approach for deployment over any VMs. We use Jenkinsfile and Jenkins pipelines features in this.</p><h3>Introduction</h3><p>Using containerization to deliver programmes has many benefits in the current software development environment, including increased portability, scalability, and isolation. This technical article offers a thorough tutorial on using Jenkins Pipeline to deploy a Dockerized application on an Amazon EC2 instance or an Azure VM. In this blog we will see, how SSH, Git, and Docker are seamlessly integrated to speed up the deployment process using declarative approach (Jenkinsfile).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*R_3Ja2hhl8jOxnay-9W-Mw.png" /><figcaption>architecture of our setup</figcaption></figure><h3>Prerequisites</h3><ul><li>Azure VMs or EC2 instances.</li><li>docker installed on target instance.</li><li>Jenkins server already setup.</li><li>Setup a SMTP server for sending notifications.</li><li>Configure webhook on github (for e.g. http://&lt;your-jenkins-IP&gt;:8080/github-webhook/).</li><li>Install github plugin and email extension plugin on Jenkins.</li></ul><p>We can use the same instance as both Jenkins server and target instance.</p><h3>Contents:</h3><ol><li>Pipeline Structure: The pipeline is defined using the Jenkins Pipeline syntax, and it consists of a number of stages that each stand for a different deployment step.</li><li>Stage 1: Connect to VM: This step makes sure the connection to the EC2 instance works.If the IP address parameter is not there, it checks for it and throws an error.<br>In order to establish a secure connection, it configures the SSH key.<br>Finally, it establishes an SSH connection to the EC2 instance and checks the initialization of the SSH agent.</li><li>Stage 2: Source Code Checkout: This stage handles the retrieval of source code from a Git repository. It configures Git credentials for authentication. It creates necessary directories on the EC2 instance.It clones or updates the “test” repositories from GitHub.</li><li>Stage 3: This phase deals with pulling source code out of a Git repository. Git credentials are set up for authentication.<br>On the EC2 instance, it builds the necessary directories.<br>The “test” repository from GitHub is copied over or updated.</li><li>Stage 4: Stop Old Container: On the Azure VM or EC2 instance, this stage handles stopping and removing any running containers. If a previous container is detected, it stops or removes it. If no abandoned container is discovered, the pipeline keeps running as normal.</li><li>Stage 5: Run New Container: In this phase, the application is running in a fresh Docker container on the EC2 instance. First SSH connection is created. It use port 8000 when running the new container with the previously created Docker image.</li><li>Post-Build Actions: Regardless of success or failure, the steps that must be taken following the pipeline run are defined in this section.<br>Depending on the build status (success, failure, or abortion), it sends email messages to a specific recipient.</li></ol><pre>pipeline <br>{<br>  agent any<br>  parameters <br>  {<br>    string(name: &#39;IP_ADDRESS&#39;, defaultValue: &#39;172.190.129.18&#39;, description: &#39;Enter IP address of target EC2 instance or VM&#39;)<br>  }<br>  <br>  stages <br>  {<br>    stage(&#39;Connect to EC2&#39;) <br>    {<br>      steps <br>      {<br>        script <br>        {<br>            // Check if IP address was provided<br>            if (params.IP_ADDRESS == &#39;&#39;) <br>            {<br>              error &quot;IP address parameter is required&quot;<br>            }<br>  <br>            // Set the SSH key environment variable<br>            withCredentials([sshUserPrivateKey(credentialsId: &#39;my-ssh-credentials&#39;, keyFileVariable: &#39;SSH_KEY&#39;, passphraseVariable: &#39;&#39;, usernameVariable: &#39;SSH_USER&#39;)]) <br>            {<br>              env.SSH_KEY = readFile(env.SSH_KEY)<br>  <br>              // SSH into EC2 instance or VM<br>              sh &quot;ssh -o StrictHostKeyChecking=no -i ${env.SSH_KEY} ${env.SSH_USER}@${params.IP_ADDRESS} &#39;echo SSH Agent initialized&#39;&quot;<br>            }<br>        }<br>      }<br>    }<br><br>  <br><br>    stage(&#39;Source Code Checkout&#39;) {<br>      steps {<br>        script {<br>            withCredentials([sshUserPrivateKey(credentialsId: &#39;my-ssh-credentials&#39;, keyFileVariable: &#39;SSH_KEY&#39;, passphraseVariable: &#39;&#39;, usernameVariable: &#39;SSH_USER&#39;)]) {<br>              env.SSH_KEY = readFile(env.SSH_KEY)<br>          withCredentials([usernamePassword(credentialsId: &#39;my-git-credentials-id&#39;, usernameVariable: &#39;GIT_USERNAME&#39;, passwordVariable: &#39;GIT_PASSWORD&#39;)]) {<br>            sh &quot;git config --global credential.username ${env.GIT_USERNAME}&quot;<br>            sh &quot;git config --global credential.helper &#39;!echo password=${env.GIT_PASSWORD}; echo&#39;&quot;<br><br>            // SSH into frontend Docker EC2 instance or VM<br><br><br>              // Create frontend directory<br>              sh &quot;ssh -o StrictHostKeyChecking=no -i ${env.SSH_KEY} ${env.SSH_USER}@${params.IP_ADDRESS} &#39;mkdir -p frontend&#39;&quot;<br><br>              // Clone or update the frontend repository with the dev branch<br>              sh &quot;ssh -o StrictHostKeyChecking=no -i ${env.SSH_KEY} ${env.SSH_USER}@${params.IP_ADDRESS} &#39;cd frontend &amp;&amp; if [ -d \&quot;.git\&quot; ]; then git pull; else git clone -b dockerfile @github.com/github_test/frontend.git&quot;&gt;https://${GIT_USERNAME}:${GIT_PASSWORD}@github.com/github_test/frontend.git .; fi&#39;&quot;<br><br>              // Create dependent_repo directory<br>              sh &quot;ssh -o StrictHostKeyChecking=no -i ${env.SSH_KEY} ${env.SSH_USER}@${params.IP_ADDRESS} &#39;mkdir -p dependent_repo&#39;&quot;<br><br>              // Clone or update the dependent_repo repository<br>              sh &quot;ssh -o StrictHostKeyChecking=no -i ${env.SSH_KEY} ${env.SSH_USER}@${params.IP_ADDRESS} &#39;cd dependent_repo &amp;&amp; if [ -d \&quot;.git\&quot; ]; then git pull; else git clone @github.com/github_test/dependent_repo.git&quot;&gt;https://${GIT_USERNAME}:${GIT_PASSWORD}@github.com/github_test/dependent_repo.git .; fi&#39;&quot;<br>            }<br>          }<br>        }<br>      }<br>    }<br><br><br>    stage(&#39;Build Docker Image&#39;) {<br>      steps {<br>        script {<br>          // SSH into frontend Docker EC2 instance or VM<br>withCredentials([sshUserPrivateKey(credentialsId: &#39;my-ssh-credentials&#39;, keyFileVariable: &#39;SSH_KEY&#39;, passphraseVariable: &#39;&#39;, usernameVariable: &#39;SSH_USER&#39;)]) {<br>        env.SSH_KEY = readFile(env.SSH_KEY)<br><br>        // Verify if Dockerfile exists in the frontend repository<br>        if (!fileExists(&#39;frontend/Dockerfile&#39;)) {<br>          error &quot;Dockerfile not found in the frontend repository&quot;<br>        }<br><br>        // Build the Docker image using the Dockerfile in the frontend directory<br>        def dockerImageTag = sh(returnStdout: true, script: &quot;ssh -o StrictHostKeyChecking=no -i ${env.SSH_KEY} ${env.SSH_USER}@${params.IP_ADDRESS} &#39;cd frontend &amp;&amp; git rev-parse --short HEAD&#39;&quot;).trim()<br>        env.DOCKER_IMAGE_TAG = dockerImageTag // Store the tag in an environment variable<br>        sh &quot;ssh -o StrictHostKeyChecking=no -i ${env.SSH_KEY} ${env.SSH_USER}@${params.IP_ADDRESS} &#39;cd frontend &amp;&amp; docker build -t frontend:${dockerImageTag} .&#39;&quot;<br>          }<br>        }<br>      }<br>    }<br>  <br>    stage(&#39;Stop Old Container&#39;) <br>    {<br>      steps <br>      {<br>        script <br>        {<br>          try <br>          {<br>            withCredentials([sshUserPrivateKey(credentialsId: &#39;my-ssh-credentials&#39;, keyFileVariable: &#39;SSH_KEY&#39;, passphraseVariable: &#39;&#39;, usernameVariable: &#39;SSH_USER&#39;)]) <br>            {<br>              env.SSH_KEY = readFile(env.SSH_KEY)<br><br>              // SSH into EC2 instance or VM and stop the container<br>              sh &quot;ssh -o StrictHostKeyChecking=no -i ${env.SSH_KEY} ${env.SSH_USER}@${params.IP_ADDRESS} &#39;docker stop frontend &amp;&amp; docker rm frontend&#39;&quot;<br>            }<br>          } catch (Exception e) <br>          {<br>            echo &quot;No old container found. Proceeding with the pipeline.&quot;<br>          }<br>        }<br>      }<br>    }<br>  <br>    stage(&#39;Run New Container&#39;) <br>    {<br>      steps <br>      {<br>        script <br>        {<br>          withCredentials([sshUserPrivateKey(credentialsId: &#39;my-ssh-credentials&#39;, keyFileVariable: &#39;SSH_KEY&#39;, passphraseVariable: &#39;&#39;, usernameVariable: &#39;SSH_USER&#39;)]) <br>          {<br>            env.SSH_KEY = readFile(env.SSH_KEY)<br><br>            // SSH into EC2 instance or VM and run the new container<br>            sh &quot;ssh -o StrictHostKeyChecking=no -i ${env.SSH_KEY} ${env.SSH_USER}@${params.IP_ADDRESS} &#39;docker run -d -p 8000:8000 --name frontend frontend:${env.DOCKER_IMAGE_TAG}&#39;&quot;<br>          }<br>        }<br>      }<br>    }<br><br>    // Previous stages omitted for brevity<br>  }<br>  post {<br>    always {<br>      script {<br>        def buildStatus = currentBuild.currentResult<br><br>        if (buildStatus == &#39;SUCCESS&#39;) {<br>          emailext (<br>            subject: &quot;Application Build and Deployment Notification - Build #${env.BUILD_NUMBER} Successful&quot;,<br>            body: &quot;The application has been built and deployed on the servers.\n\nBuild Number: ${env.BUILD_NUMBER}\nJob Name: ${env.JOB_NAME}&quot;,<br>            to: &#39;rishaw.2k@gmail.com&#39;,<br>            mimeType: &#39;text/plain&#39;<br>          )<br>        } else if (buildStatus == &#39;FAILURE&#39;) {<br>          emailext (<br>            subject: &quot;Application Build and Deployment Notification - Build #${env.BUILD_NUMBER} Failed&quot;,<br>            body: &quot;Uh-oh! Something&#39;s wrong. The build failed.\n\nBuild Number: ${env.BUILD_NUMBER}\nJob Name: ${env.JOB_NAME}&quot;,<br>            to: &#39;rishaw.2k@gmail.com&#39;,<br>            mimeType: &#39;text/plain&#39;<br>          )<br>        } else if (buildStatus == &#39;ABORTED&#39;) {<br>          emailext (<br>            subject: &quot;Application Build and Deployment Notification - Build #${env.BUILD_NUMBER} Aborted&quot;,<br>            body: &quot;Looks like somebody aborted the build.\n\nBuild Number: ${env.BUILD_NUMBER}\nJob Name: ${env.JOB_NAME}&quot;,<br>            to: &#39;rishaw.2k@gmail.com&#39;,<br>            mimeType: &#39;text/plain&#39;<br>          )<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>Credentials should be setup before starting pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJco9aXF_mnfdJ2f9M3R6w.png" /></figure><p>SMTP server should be already configured:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kl9xI7JoCaRUzHS1zi3GXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4edsq8tZvst8e-1eRXOxhg.png" /></figure><p>Webhook must be setup on github:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CT5ehq3C4bZeUZEyVTr_eg.png" /></figure><p>Pipeline: Select the pipeline option and give it a name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSu-XRiXfybr2sNQW628EQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DwQYg1c7i64tWaJO6g1oXw.png" /></figure><p>Pass your github repo in pipeline from SCM option:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7n05tm0MNJmdbIlRc2hjyA.png" /></figure><p>Ouputs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pWVjru7n6n5XnuBkujCz6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kBJr81fjgwxalQB2v-HOrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z1Q4bhR66JCV5rTY_Hn4bw.png" /></figure><p>Hope you liked this blog. You can follow me on <a href="https://github.com/rishawsingh"><em>github</em></a><em> </em>or text me over at<em> </em><a href="https://www.linkedin.com/in/rishaw-singh/"><em>linkedin</em></a>.</p><p>Feel free to contact me with any doubts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dba5e294df" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>