<?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 Hamza Meehmood on Medium]]></title>
        <description><![CDATA[Stories by Hamza Meehmood on Medium]]></description>
        <link>https://medium.com/@hamza.meehmood?source=rss-5b0480abc79a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jdKMhBmu9gSDzHjZ</url>
            <title>Stories by Hamza Meehmood on Medium</title>
            <link>https://medium.com/@hamza.meehmood?source=rss-5b0480abc79a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 08:24:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hamza.meehmood/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[What is Kustomize?]]></title>
            <link>https://medium.com/@hamza.meehmood/what-is-kustomize-870a0a9f054c?source=rss-5b0480abc79a------2</link>
            <guid isPermaLink="false">https://medium.com/p/870a0a9f054c</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[pakistan]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Hamza Meehmood]]></dc:creator>
            <pubDate>Thu, 24 Oct 2024 18:08:48 GMT</pubDate>
            <atom:updated>2024-10-24T18:08:48.302Z</atom:updated>
            <content:encoded><![CDATA[<p>Kustomize is a configuration management tool that allows Kubernetes users to customize application deployment configurations without needing to modify original YAML files. It focuses on layering and patching configurations, which makes it a powerful alternative to Helm for customizing Kubernetes reso urces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*D0oGqvybvO25GRK40I5VPQ.png" /></figure><h4>Key Differences: Kustomize vs Helm</h4><ul><li><strong>Kustomize</strong>: No need for templating, works by patching YAML files and layering configurations. YAML-centric and declarative.</li><li><strong>Helm</strong>: A package manager for Kubernetes, uses Go templates to generate YAML files for deployments.</li></ul><blockquote>Folder Structure</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bccOUPOcGy_1PIiqi2-8gQ.png" /></figure><ul><li>so we may define kustomize as</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*zK4VjFhpVvdMe8-X2-zBKQ.png" /></figure><h3>Kustomization File (kustomization.yaml)</h3><p>The kustomization.yaml file is the heart of Kustomize. It is a configuration file used to define how resources should be customized, layered, and patched without modifying the original YAML files. The file follows a declarative syntax and supports various directives to manage Kubernetes objects, transformations, and more.</p><h4>Basic Structure of kustomization.yaml</h4><p>Every kustomization.yaml file starts with these two required fields:</p><pre>apiVersion: kustomize.config.k8s.io/v1beta1<br>kind: Kustomization</pre><p>and then we may define the resourc</p><h4>Defining Resources</h4><p>The <strong>resources</strong> field in the kustomization.yaml file is used to point to the Kubernetes manifests that Kustomize will manage. These resources could be in the same directory as the kustomization.yaml file or located elsewhere in the file structure.</p><p><strong>Example of Resources Field</strong></p><pre>resources:<br>  - deployment.yaml<br>  - service.yaml</pre><p>Here, Kustomize will load and manage the deployment.yaml and service.yaml files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zoTGQwFM8YSejYWqdr_9gg.png" /></figure><h3>kustomize build Command</h3><p>The kustomize build command is used to generate a final set of Kubernetes manifests based on the customizations defined in a kustomization.yaml file. This command processes all resources, patches, generators (ConfigMaps, Secrets), and transformations described in the kustomization.yaml file, and then outputs the customized YAML files, ready to be applied to a Kubernetes cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rrQk8doWswosk7PQfxUBfA.png" /></figure><h3>Transformers in Kustomize</h3><p>Transformers in Kustomize allow you to <strong>modify Kubernetes resources in a declarative way</strong> without directly editing the resource manifests. This ensures a <strong>non-intrusive, reusable, and flexible</strong> way to manage configurations. Transformers apply changes, such as adding labels, annotations, or setting namespaces, across multiple resources, ensuring consistency in your deployments.</p><p>Transformers in Kustomize are defined within the kustomization.yaml file, and they provide various ways to modify resources such as:</p><ul><li>Adding or modifying <strong>labels</strong> and <strong>annotations</strong></li><li>Changing the <strong>namespace</strong> for resources</li><li><strong>Name prefixing</strong> and <strong>suffixing</strong> to differentiate between environments</li><li><strong>Image transformations</strong> (e.g., changing container image versions)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o21bxC2BZcbF1-spwCpAkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vkFVFn41fm8Ury7UdigMaA.png" /></figure><h3>Common Labels Transformer</h3><p>Labels are key-value pairs used in Kubernetes for identifying and grouping resources. Kustomize lets you apply labels to all resources defined in your kustomization.yaml file using the commonLabels field.</p><h4>Example: Applying Common Labels</h4><p>define a property as common label in yours kustomization.yaml filr and it will replace the commonnlabels accross yours yaml file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnU5YPaEB-XMQY-Rsc5mqQ.png" /></figure><p>NameSpace Transformer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lnhSjcVzWxFm72x53jNPoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L8bzIke2ghZdixbmM9SnqA.png" /></figure><h3>Image Transformer in Kustomize</h3><p>The <strong>Image Transformer</strong> in Kustomize is a powerful feature that allows you to modify container images for Kubernetes resources without manually editing each resource file. This is particularly useful for <strong>changing image versions</strong> across different environments, such as <strong>development</strong>, <strong>staging</strong>, and <strong>production</strong>. With the Image Transformer, you can easily update an image tag, change the image repository, or even switch the full image name for all resources that reference it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZzJx4RXzPm03LZKQTVtSQ.png" /></figure><h3>Patches in Kustomize</h3><p>Patches in Kustomize allow you to <strong>override or modify specific fields</strong> in Kubernetes resource definitions without changing the original resource files. This is useful when you want to apply environment-specific or situation-specific changes, such as different replicas for production vs. development, or adjusting configuration for different clusters, all while keeping the original base resource files untouched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rUrfOykjj1CQQhkHNTrLPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YBwLZljzJLc7ziIpIykWSA.png" /></figure><p>one more example for patches below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PkuQ2Zxm4tyo6-U7oWl-OA.png" /></figure><h3>Overlays in Kustomize</h3><p><strong>Overlays</strong> in Kustomize allow you to manage different configurations for various environments (e.g., development, staging, production) without duplicating the base resource definitions. With overlays, you can define environment-specific modifications or adjustments on top of a common set of base resources. This helps maintain a <strong>clean separation</strong> between the <strong>shared base configuration</strong> and the <strong>environment-specific configuration</strong>.</p><p>Overlays allow you to customize resources such as:</p><ul><li><strong>Scaling replicas</strong> for production</li><li><strong>Changing image tags</strong></li><li><strong>Adding environment-specific labels</strong></li><li><strong>Applying different ConfigMaps or Secrets</strong></li></ul><h3>Key Concepts of Overlays</h3><ol><li><strong>Base</strong>: A set of common Kubernetes resources that remain unchanged across different environments. These resources can include Deployments, Services, ConfigMaps, etc.</li><li><strong>Overlay</strong>: An environment-specific modification to the base configuration. Overlays can adjust any part of the resources defined in the base, like changing image versions, updating the number of replicas, or applying specific environment labels.</li><li><strong>kustomization.yaml</strong>: Both base and overlays are controlled by kustomization.yaml files, which define what resources to include and how to patch or transform them.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=870a0a9f054c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a DevOps CI/CD Pipeline Locally: GitHub, Jenkins, Maven, SonarQube, Docker, DockerHub…]]></title>
            <link>https://medium.com/@hamza.meehmood/building-a-devops-ci-cd-pipeline-locally-github-jenkins-maven-sonarqube-docker-dockerhub-510c578886d0?source=rss-5b0480abc79a------2</link>
            <guid isPermaLink="false">https://medium.com/p/510c578886d0</guid>
            <dc:creator><![CDATA[Hamza Meehmood]]></dc:creator>
            <pubDate>Thu, 17 Oct 2024 10:17:05 GMT</pubDate>
            <atom:updated>2024-10-17T10:17:05.811Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a DevOps CI/CD Pipeline Locally: GitHub, Jenkins, Maven, SonarQube, Docker, DockerHub, ArgoCD, Helm, Kubernetes, Prometheus, Grafana, Filebeat, OpenSearch, and Kibana</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/0*-_9oxmAQgYr4z-Qh.gif" /></figure><h3>Project Introduction:</h3><p>This project implements a complete DevOps CI/CD pipeline in a local environment. The CI part is implemented using Docker and Docker Compose, providing isolated environments for Jenkins, SonarQube, and other necessary tools. DockerHub is used as the container registry for managing Docker images. For code quality analysis and build management, Maven and SonarQube are integrated with Jenkins, ensuring a smooth and efficient continuous integration process.</p><p>The CD part is managed with Kubernetes running in Minikube, allowing for local orchestration of containers. Deployment to Kubernetes is automated using ArgoCD, which facilitates smooth rollouts and rollbacks. Monitoring and logging are handled using Prometheus, Grafana, Filebeat, OpenSearch, and Kibana, all installed via Helm charts for ease of configuration. This setup provides comprehensive observability and logging capabilities, making it ideal for testing new features and fixes.</p><h3>Prerequisites:</h3><p>Before getting started with this DevOps CI/CD project, ensure the following tools are installed and properly configured:</p><ul><li><strong>Docker</strong>: For containerization.</li><li><strong>Docker Compose</strong>: To manage multi-container applications.</li><li><strong>DockerHub</strong>: For storing and managing Docker images.</li><li><strong>kubectl</strong>: For interacting with the Kubernetes cluster.</li><li><strong>Minikube</strong>: To set up a local Kubernetes environment.</li><li><strong>Helm</strong>: For managing Kubernetes applications.</li><li><strong>Git</strong>: For version control.</li><li><strong>ArgoCD CLI</strong>: (Optional) For managing deployments through the command line.</li><li><strong>GitHub Account</strong>: For repository management.</li></ul><h3>Implementation steps:</h3><ol><li><strong>Fork and Clone below Git repository:<br></strong><a href="https://github.com/deepakkr35/devops-demo-project">https://github.com/deepakkr35/devops-demo-project</a></li><li><strong>Open terminal, cd to project directory and use docker-compose to bring up CI environment:</strong></li></ol><pre>cd devops-demo-project/ci<br>docker-compose up -d</pre><p>3.<strong> Open below URL to access Jenkins:</strong><br><a href="http://localhost:8010/">http://localhost:8010/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OoLnb8Q_wUs2PaPw.png" /></figure><p>4. <strong>Access Jenkins password, login and install suggested plugins:</strong></p><pre>docker ps<br>docker exec -it jenkins bin/bash<br>cat /var/jenkins_home/secrets/initialAdminPassword</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GmXKStszfFfr1oQ8.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uccI22Z-773BN28l.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ip0h7sAPL3rPSMcv.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dAEL4_x4ynRnWWMX.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UmvrsJ2i3eXmi5TM.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uyflPoAiF-YPKnkO.png" /></figure><p>5. <strong>Install below suggested plugins and restart Jenkins container:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XeMtcF4GnHHtWzmg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WEpi8r08ZE1gKCtQ.png" /></figure><p>6. <strong>Open SonarQube using below URL and create token:</strong><br><a href="http://localcalhost:9000/">http://localcalhost:9000</a><br>username: admin<br>password: admin</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lLLyrfxnUB_7RdVI.png" /></figure><p>7. <strong>Login to your GitHub account and generate personal access token:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H6zzohCFVsILHo7m.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l8RqFnZRrrf9SbEv.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6SVdYWk6oZkmjDB-.png" /></figure><p>8. <strong>Add credentials for GitHub and SonarQube using secret text and DockerHub using username with password:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Re5H1agtplC7COW_.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s3u64O1Rao-AEggo.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z9jaooeodgPmI3UP.png" /></figure><p>9. <strong>Login to Jenkins and create new item:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K9aw5-NBZuksJPhV.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vqPKi7Nu0r4Mq41I.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DAs6CfoXEI-j1Xnx.png" /></figure><p>10. <strong>Build the pipeline with V1.0 parameter:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-MFjajKDDkGFr7hI.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RwGBeSmH35uH7Epp.png" /></figure><p>11. Docker image will be created and GitHub helm/app/values.yaml will be updated with appropriate tag:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iJ7NXIpwBKwYkLIt.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XT1E6Y2Pf4p06tfM.png" /></figure><p>12. <strong>Start Kubernets cluster (Minikube) in docker driver mode:</strong></p><pre>minikube start --driver=docker --cpus 4 --memory 10240</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AtFjnhzTThsVOcD6.png" /></figure><p>13. <strong>Create namespaces for installing application, logging and monitoring:</strong></p><pre>kubectl create ns app<br>kubectl create ns logging<br>kubectl create ns monitoring</pre><p>14. <strong>Edit app namespace and add following label for ArgoCD:</strong></p><pre>kubectl edit ns app</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/0*bR8n9XQ2sU-g247X.png" /></figure><p>15. <strong>Install Graphana and Promotheus in monitoring namespce using Helm: </strong>(port-forward is required to access UI, as minikube is running in Docker driver mode)</p><pre>helm repo add prometheus-community https://prometheus-community.github.io/helm-charts<br>helm install prometheus prometheus-community/prometheus -n monitoring<br>kubectl port-forward service/prometheus-server 9030:80 -n monitoring</pre><p><a href="http://localhost:9030/">http://localhost:9030/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lQg6kCaWXOnfTzKr.png" /></figure><pre>helm repo add grafana https://grafana.github.io/helm-charts<br>helm install grafana grafana/grafana -n monitoring<br>kubectl get secret --namespace monitoring grafana -o jsonpath=&quot;{.data.admin-password}&quot; | base64 --decode ; echo<br>kubectl port-forward service/grafana 9040:80 -n monitoring</pre><p><a href="http://localhost:9040/">http://localhost:9040/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d_wmGr78c3oQZE4W.png" /></figure><p>16. <strong>Configure Graphana to use Promoetheus as data source and import required dashhboards:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0LDBChGmbvJjU5hR.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HqZjDGZNu-UeS0S6.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HDgKYnPDNX-jOjyR.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-m3aSwJAKCqnDWrU.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tLmz08OzSMzOBZiC.png" /></figure><p>17.<strong> Install Elasticsearch, Kibana and Filebeat in logging namespace using Helm and port forward to access Elasticsearch and Kibana UIs:</strong></p><pre>cd devops-demo-project/helm<br>helm install elasticsearch ./logging/elasticsearch<br>helm install kibana ./logging/kibana<br>helm install filebeat ./logging/filebeat</pre><pre>kubectl port-forward service/es-master-service 9010:9200 -n logging<br>kubectl port-forward service/kibana-service 9020:5601 -n logging</pre><p><a href="http://localhost:9010/">http://localhost:9010/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fjpeKCm7_KlW4L0B.png" /></figure><p><a href="http://localhost:9020/">http://localhost:9020/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zkQ9bXPd3yRp2T50.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5rTbfv1Qm0prko6h.png" /></figure><p>18. <strong>Install ArgoCD in Kubernetes cluster:</strong></p><pre>cd devops-demo-project/cd/argocd<br>curl -sL https://github.com/operator-framework/operator-lifecycle-manager/releases/download/v0.28.0/install.sh | bash -s v0.28.0<br>kubectl get csv -n operators<br>kubectl create ns argocd<br>kubectl apply -f argocd-basic.yaml<br>echo $(kubectl get secret example-argocd-cluster -n argocd -o jsonpath=&quot;{.data.admin\.password}&quot; | base64 —decode)<br>minikube service example-argocd-server -n argocd</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mrKMm1UlGuaF5FLo.png" /></figure><p>19. <strong>Open ArgoCD URL and create application to deploy, using password retrieved earlier:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*77GsflmqEdqx4F2m.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j3h1HNg1WQDU1Eo-.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*do6wkPD5zWzd-Iea.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/0*cKmlAj039rj_6azQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Itb3SEuqVxk9C6uI.png" /></figure><p>20. <strong>port-forward app to access through UI:</strong></p><pre>kubectl port-forward service/demo-java-app-service 8080:80 -n app</pre><p><a href="http://localhost:8080/">http://localhost:8080/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CbWkY4S2KBlIMzAI.png" /></figure><p>21. <strong>Check application logs rolling in Kibana:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*suV6dVykC1Ib60nY.png" /></figure><p>22. <strong>Make code changes and commit (for testing CI/CD pipeline):</strong></p><p>demo-java-app/src/main/java/com/deepak/demo/DemoApplication.java</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FHT6MMgLJAoIZp8V.png" /></figure><p>demo-java-app/src/main/resources/templates/index.html</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9Em0GelYXxlkX70s.png" /></figure><p>23. <strong>Build pipeline in Jenkins:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gS5d1_a9l0-URxWi.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HZkj9YNfbgMsQOJz.png" /></figure><p>24. <strong>Once CI pipeline is complete, Dockerhub and GitHub will be update:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YQqDQUZu5t6rjuS7.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cPsTap4d4vMx_6cv.png" /></figure><p>25. <strong>ArgoCD will deploy application changes:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z45av6ste4RXX8i3.png" /></figure><p>26. <strong>Access updated application:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KT1KxEslmOvAHDjW.png" /></figure><p>27. <strong>Optional step</strong> (Cleanup of resources)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=510c578886d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DevSecOps for Node.js Application Project]]></title>
            <link>https://medium.com/@hamza.meehmood/devsecops-for-node-js-application-project-6718b596b69e?source=rss-5b0480abc79a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6718b596b69e</guid>
            <dc:creator><![CDATA[Hamza Meehmood]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 23:35:26 GMT</pubDate>
            <atom:updated>2024-10-15T23:35:26.958Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/951/0*ArTESVZmmbgKT55Z.jpeg" /></figure><blockquote>In this project we will create our Node.js application using Jenkins, security using SonarQube,OWASP and image scanning using Trivy.</blockquote><h4>Tool we will need in this project is :-</h4><ul><li>1.) AWS EC2</li><li>2.) Docker, Docker-compose and Docker</li><li>3.) Github</li><li>4.) Jenkins</li><li>5.) SonarQube</li><li>6.) OWASP DC</li><li>7.) Trivy</li><li>8.) Email</li></ul><h3>Prerequisites</h3><h4>Before starting the project you should have these things in your system :-</h4><ul><li>Account on AWS</li><li>Account on GitHub</li><li>Code (we will use code from this repository) : <a href="https://github.com/sudhajobs0107/Netflix">click here for code</a></li></ul><h3>Part 1 : Initial Setup and Deployment</h3><h3>STEP 1: Launch Instance</h3><ul><li>Create AWS EC2 instance (t2.large</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SxqJfhi7LwAb5LXv.PNG" /></figure><ul><li>Connect to instance through SSH client to my local.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u2p3kwGrkg-JnGPT.PNG" /></figure><ul><li>After successfully connecting to the EC2 instance, it will look like this</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/0*7JPQe2SUHmlCqZo1.PNG" /></figure><h3>Part 2 : Setup Jenkins</h3><ul><li>Now to install Jenkins, first we need Java install because Jenkins need Java so for to install Java use command :-</li></ul><pre>sudo apt upgrade &amp;&amp; sudo apt upgrade -y<br>sudo apt install fontconfig openjdk-17-jre</pre><ul><li>To check Java version use command :</li></ul><pre>java --version</pre><p>After installing Java, we will install Jenkins so for to install Jenkins use command :-</p><pre>sudo wget -O /usr/share/keyrings/jenkins-keyring.asc \<br>https://pkg.jenkins.io/debian-stable/jenkins.io-2023.key<br>echo deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc] \<br>https://pkg.jenkins.io/debian-stable binary/ | sudo tee \<br>/etc/apt/sources.list.d/jenkins.list &gt; /dev/null<br>sudo apt-get update<br>sudo apt-get install jenkins<br>sudo systemctl start jenkins<br>sudo systemctl enable jenkins<br></pre><pre>sudo service jenkins status</pre><ul><li>To check Jenkins status, use command :-</li></ul><pre>sudo service jenkins status</pre><ul><li>Now copy Public IPv4 address:8080 and we will be on Unlock Jenkins page.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/0*2xSGWKAT5Mruk9sO.PNG" /></figure><pre>To unlock jenkins, use command :-sudo cat /var/lib/jenkins/secrets/initialAdminPassword</pre><ul><li>And we will get our password. Copy and paste it to unlock Jenkins → Now click Install suggested plugins → Fill details → Welcome to Jenkins</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w5iP2WWuabcLzagU.PNG" /></figure><h3>Part 3 : Setup Docker and Docker-Compose</h3><ul><li>Now to install docker and docker-compose use command as follow :-</li></ul><pre>sudo apt-get update<br>sudo apt-get install docker.io docker-compose -y<br>sudo usermod -aG docker $USER</pre><ul><li>Also add jenkins to docker group for this use command as follow :-</li></ul><pre>sudo usermod -aG docker jenkins<br>sudo reboot</pre><ul><li>Check docker version use command :-</li></ul><pre>docker version</pre><ul><li>Now enable docker for this use command :-</li></ul><pre>sudo systemctl enable docker</pre><h3>Part 4 : Setup SonarQube</h3><ul><li>Now we will build SonarQube container for this use command :-</li></ul><pre>docker run -itd --name sonarqube -p 9000:9000 sonarqube:lts-community</pre><ul><li>Now if we will do docker ps so we will see our SonarQube container is running.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QrnI0j9-pC5gczth.PNG" /></figure><ul><li>Now open port no. 9000 and copy Public IPv4 address and paste in new tab Public IPv4 address:9000 and we will be on Unlock SonarQube page.</li><li>Now enter login and password=admin and it will give us screen to reset our password and we will be on SonarQube page.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nOkox7xapF5feYxD.PNG" /></figure><ul><li>Now to make devsecops pipeline, we have create user on sonarqube and this user will have acces given to jenkins. To add user in sonar, Go to SonarQube → Administrator → Security → Users → Tokens → Update Tokens → name “jenkins” → Generate.</li><li>Our sonarqube setup done. Now to put sonar into jenkins we have to Install Plugins. To install sonarqube plugins Go to Manage Jenkins → Plugins → Available Plugins → Search SonarQube Scanner → install this plugin.</li></ul><blockquote>Now SonarQube token put in Jenkins → Go to Manage Jenkins → click on Credentials → System → Global credentials → Add Credentials → Secret text → in Secret put the token that we copied from SonarQube → ID “Sonar” → Description “Sonar” → Create.</blockquote><blockquote>Same as Sonar add Docker Credentials in Jenkins → Go to Manage Jenkins → click on Credentials → System → Global credentials → Add Credentials → Username with password → in Secret put your username and password of dockerhub → ID “DockerHub” → Description “DockerHub” → Create.</blockquote><blockquote>Now we will link our SonarQube with Jenkins, for this Go to Manage Jenkins → System → Find SonarQube servers → Add SonarQube → Name “Sonar” → Server URL “<a href="http://52.205.89.152:9000/">http://52.205.89.152:9000</a>&quot; → Server authentication token “Sonar” → click on Apply and Save.</blockquote><h3>We added our SonarQube Server to Jenkins.</h3><blockquote>Now to enable Sonar Scanner Go to Manage Jenkins → Tools → Find SonarQube Scanner installations → Add SonarQube Scanner → name “Sonar” → Version “latest” → click on Apply and Save.</blockquote><blockquote>Now we will create sonar webhooks. Go to Sonar → Administrator → Webhooks → Create → Name “jenkins” → URL “<a href="http://52.205.89.152:8080/sonarqube-webhook/">http://52.205.89.152:8080/sonarqube-webhook/</a>&quot; → Create.</blockquote><h3>Part 5 : Setup Trivy</h3><h3>Now to install trivy use command :-</h3><pre>sudo apt-get install wget apt-transport-https gnupg lsb-release<br>wget -qO - https://aquasecurity.github.io/trivy-repo/deb/public.key | sudo apt-key add -<br>echo deb https://aquasecurity.github.io/trivy-repo/deb $(lsb_release -sc) main | sudo tee -a /etc/apt/sources.list.d/trivy.list<br>sudo apt-get update<br>sudo apt-get install trivy</pre><h3>Part 6 : Setup OWASP DC</h3><blockquote>Now same as SonarQube we have to install OWASP plugins Go to Manage Jenkins → Plugins → Available Plugins → Search OWASP Dependency-Check → install this plugin.</blockquote><blockquote>Now to enable Dependency-Check Go to Manage Jenkins → Tools → Find Dependency-Check installations → Add Dependency-Check → name “OWASP” → Install automatically → Install from github.com → click on Apply and Save.</blockquote><ul><li>Now build a pipeline click on Create a job → give name “node-app” → select “Pipeline” → click OK.</li><li>Now add the script in Pipeline Script.</li></ul><pre>pipeline {<br>    <br>    agent any<br>    environment{<br>        SONAR_HOME = tool &quot;Sonar&quot;<br>    }<br>    stages {<br>        <br>        stage(&quot;Code&quot;){<br>            steps{<br>                git url: &quot;https://github.com/sudhajobs0107/DevSecOps_ToDo_App.git&quot; , branch: &quot;main&quot;<br>                echo &quot;Code Cloned Successfully&quot;<br>            }<br>        }<br>        stage(&quot;SonarQube Analysis&quot;){<br>            steps{<br>               withSonarQubeEnv(&quot;Sonar&quot;){<br>                   sh &quot;${SONAR_HOME}/bin/sonar-scanner -Dsonar.projectName=node-todo-app -Dsonar.projectKey=node-todo-app -X&quot;<br>               }<br>            }<br>        }<br>        stage(&quot;SonarQube Quality Gates&quot;){<br>            steps{<br>               timeout(time: 5, unit: &quot;MINUTES&quot;){<br>                   waitForQualityGate abortPipeline: false<br>               }<br>            }<br>        }<br>        stage(&quot;OWASP&quot;){<br>            steps{<br>                dependencyCheck additionalArguments: &#39;--scan ./&#39;, odcInstallation: &#39;OWASP&#39;<br>                dependencyCheckPublisher pattern: &#39;**/dependency-check-report.xml&#39;<br>            }<br>        }<br>        stage(&quot;Build &amp; Test&quot;){<br>            steps{<br>                sh &#39;docker build -t devsecops-todo-app:latest .&#39;<br>                echo &quot;Code Built Successfully&quot;<br>            }<br>        }<br>        stage(&quot;Trivy&quot;){<br>            steps{<br>                sh &quot;trivy image devsecops-todo-app&quot;<br>            }<br>        }<br>        stage(&quot;Push to Private Docker Hub Repo&quot;){<br>            steps{<br>                withCredentials([usernamePassword(credentialsId:&quot;DockerHubCreds&quot;,passwordVariable:&quot;dockerPass&quot;,usernameVariable:&quot;dockerUser&quot;)]){<br>                sh &quot;docker login -u ${env.dockerUser} -p ${env.dockerPass}&quot;<br>                sh &quot;docker tag devsecops-todo-app:latest ${env.dockerUser}/devsecops-todo-app:latest&quot;<br>                sh &quot;docker push ${env.dockerUser}/devsecops-todo-app:latest&quot;<br>                }<br>                <br>            }<br>        }<br>        stage(&quot;Deploy&quot;){<br>            steps{<br>                sh &quot;docker-compose up -d&quot;<br>                echo &quot;App Deployed Successfully&quot;<br>            }<br>        }<br>    }<br>}</pre><h3>Now click Apply and Save → Build Now and our pipeline will build successfully.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nWTNgUAI_LNBtVEM.PNG" /></figure><h3>Our project on SonarQube.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*irKr0WYST085s6XI.PNG" /></figure><h3>Our run will run perfectly.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O17KHEBR88oNZyNW.PNG" /></figure><h3>Part 7 : Setup Email Integration With Jenkins</h3><blockquote>First we have to install email plugin.</blockquote><blockquote>Go to Manage Jenkins → Plugins → Available Plugins → Search Email Extension Template → install this plugin.</blockquote><blockquote>Now go to your Gmail → click on your profile → click on Manage Your Google Account –&gt; click on the Security tab on the left side panel → search App Passwords → Create a password → you will get page like image given below :-</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EtfcxFnF2PKPLarh.PNG" /></figure><blockquote>Now same as Sonar and Docker we will add Email Credentials in Jenkins → Go to Manage Jenkins → click on Credentials → System → Global credentials → Add Credentials → Username with password → in Secret put hamza.ramiish@gmail.com and password that we created earlier → ID “email” → Description “email” → Create.</blockquote><blockquote>Now Go to Manage Jenkins → System → Find E-mail notification → Add STMP=stmp.gmail.com → click Avanced → UserName=→ Password=put that we created → Tick Use SSL → SMTP Port=465 → click on Apply.</blockquote><blockquote>We have to add one more thing so in System → Find Extended E-mail Notification → Add STMP=stmp.gmail.com → SMTP Port=465 → click Avanced → Cedentials=select email that we creted we earlier → Tick Use SSL → Default Content Type=HTML → go down and find Default Triggers → Tick Always → click on Apply and Save.</blockquote><h3>Now in pipeline in the down add code that given below :-</h3><pre>post {<br>     always {<br>        emailext attachLog: true,<br>            subject: &quot;&#39;${currentBuild.result}&#39;&quot;,<br>            body: &quot;Project: ${env.JOB_NAME}&lt;br/&gt;&quot; +<br>                &quot;Build Number: ${env.BUILD_NUMBER}&lt;br/&gt;&quot; +<br>                &quot;URL: ${env.BUILD_URL}&lt;br/&gt;&quot;,<br>            to: &#39;postbox.aj99@gmail.com&#39;,  #change Your mail<br>            attachmentsPattern: &#39;trivyfs.txt,trivyimage.txt&#39;<br>        }<br>    }</pre><blockquote>Now build the pipeline and pipeline “SUCCES” or “FAILURE” we will get email like image given below :-</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ycr_EYVQvNjyUJzG.PNG" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jxRIRXDOIEvL2lfM.PNG" /></figure><h3>Our DevSecOps for Node.js Application Project is completed 😄.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6718b596b69e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deployment Strategies in
Kubernetes: A Hands-on Guide]]></title>
            <link>https://medium.com/@hamza.meehmood/deployment-strategies-in-kubernetes-a-hands-on-guide-809d7b391b7b?source=rss-5b0480abc79a------2</link>
            <guid isPermaLink="false">https://medium.com/p/809d7b391b7b</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[ekspedisi]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Hamza Meehmood]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 20:32:42 GMT</pubDate>
            <atom:updated>2024-10-15T20:32:42.415Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>By Default we are always using the rolling update stratagy in kubernates dont ever think youre not using any deployment strategy</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*oYRqbtMlAv9zfFe4EkTjYQ.png" /></figure><p>The 3 Main Kubernetes <strong>Deployment Strategies:</strong></p><ol><li><strong>Rolling Update</strong></li><li><strong>Canary Model Deployment</strong></li><li><strong>Blue/Green Deployment</strong></li></ol><p><strong>Why do we basically need the deployment strategy?</strong></p><p>Deployment strategy in kubernetes is used to update application running in kubernetes environment. <strong>These strategies play a crucial role in application lifecycle managemen</strong>t, directly influencing application availability, service continuity and the capacity to adapt to new requirements.During downtime a deployment strategy can help in reducing the downtime to even 0 yes you heard it right you will be all 364.9 days liveeeeeee</p><p>ys thats right</p><p>So lets dig up the things first strategy uis rolling update</p><p><strong>1. Rolling Update Strategy: The Default Approach</strong></p><p><strong>What is Rolling Update?</strong></p><p>Rolling updates are the <strong>default deployment strategy</strong> in Kubernetes, allowing you to update applications with minimal downtime. This method ensures some instances of the application are always running, reducing disruptions. During the update, Kubernetes uses <strong>readiness probes</strong> to confirm that new pods are ready before scaling down older ones. If something goes wrong, you can <strong>roll back</strong> without affecting the whole cluster.</p><p><strong>To initiate a rolling update, simply use kubectl set image to update your pod images. Key parameters include:</strong></p><p>• <strong>maxSurge</strong>: Number of extra pods allowed during the update.</p><p>• <strong>maxUnavailable</strong>: Maximum pods allowed to be unavailable during rollout.</p><p>Efficient, smooth, and safe!</p><p>only prerequiste is that you ahve insatlled the MINIKUBE ON YOURS EKS OR KUBENRETES CLUSTER</p><p>and run</p><pre>minikuve start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*vtwInrM9SjUyC6Gfyl4gGA.png" /></figure><p>after that crete a deployment with the image nginx and tag as nginx</p><pre>kubectl create deploy nginx --image=nginx<br></pre><pre><strong>after that you may inspect the deployment by using the describe command and referencing yours image name as i did in the image</strong></pre><pre>kubectl describe deployments.apps nginx</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*74KAH9ir9y_wFyM0loW3Ew.png" /></figure><p>as marked in the image you may look. that the RollingUpdate is the deployment strategy.</p><h4>1. Check if the Pods are Running</h4><p>First, let’s check the current status of the pods running in the deployment. This will give us a snapshot of our deployment and the number of replicas it has.</p><p>Run the following command:</p><pre>kubectl get pods</pre><p>You should see output that lists all the pods currently running in your deployment. For example in my case</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*Sv1Ref12Vg4myUVmRSSxlA.png" /></figure><h4>2. Increase the Replica Count</h4><p>Now, let’s scale up the deployment to ensure there are multiple replicas of our application running. In this example, we’ll increase the replica count to <strong>4</strong>.</p><p>To do this, we need to edit the deployment configuration. Run</p><pre>kubectl edit deploy nginx</pre><p>This will open the deployment YAML file in your default text editor. Locate the section that defines the number of replicas, which should look like thi</p><pre>spec:<br>  replicas: 1</pre><p>Change the replica count from 1 to 4, as shown below</p><pre>spec:<br>  replicas: 4<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*ljo_PrSMTDMKavtAtif-zg.png" /></figure><p>Once you’ve made the change, save the file and exit the editor. Kubernetes will automatically scale the deployment to the new replica count.</p><h4>3. Verify the Scaling</h4><p>To verify that the scaling was successful, check the status of the pods aga</p><pre>kubectl get pods</pre><p>You should now see 4 pods running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*EdLOWxMeWP2RJhqZgpvuDA.png" /></figure><p>All four pods are now up and running, ensuring high availability of your application.</p><h4>4. Monitor the Rolling Update</h4><p>Before initiating a rolling update, open a new terminal tab or window. In this new tab, run the following command to continuously watch the status of the pods:</p><pre>kubectl get pods -w</pre><p>This command will display real-time updates on the status of your pods, so you can observe the rolling update process as it happens.</p><h4>5. Perform the Rolling Update</h4><p>Now that you have a terminal monitoring the pods, switch back to the original terminal where we will initiate the rolling update. In Kubernetes, a rolling update replaces old versions of a container with new ones, one at a time, ensuring that your application remains available during the update.</p><p>To perform a rolling update, we’ll update the image used by the deployment. Let’s edit the deployment again:</p><pre>kubectl edit deploy nginx</pre><p>Locate the section where the container image is defined, which might look like this</p><pre>spec:<br>  containers:<br>  - name: nginx<br>    image: nginx:1.19</pre><p>Change the image version to a newer one, for example, from nginx:1.19 to nginx:1.21</p><pre>spec:<br>  containers:<br>  - name: nginx<br>    image: nginx:1.21</pre><p>Save the file and exit the editor. This triggers a rolling update where the new version of the container is rolled out one pod at a time.</p><h4>6. Observe the Rolling Update</h4><p>Switch back to the second terminal where you’re watching the pods with kubectl get pods -w. You should start to see the old pods terminating and new pods being created as Kubernetes rolls out the updated image:</p><p>This process will continue until all the old pods are replaced with new pods running the updated image.</p><h4>7. Verify the Update</h4><p>Once the rolling update is complete, you can verify that all the pods are running the new version of the applicatin</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*a_0gtKGxnq-80Dbzb6mUJQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*40hgQbChzJ45ane4i3e9OQ.png" /></figure><p><strong>When you create a service then kubernetes will see that only 3 pods are running, so it will forward to the request to only these pods since the other pod is not healthy.</strong></p><p>So in this way if you’re using a deployment strategy using rolling update, even if something goes wrong we still have old copies running. Hence user will not see any downtime. If you have provided a existing image, then one by one the pods will get updated to the new version and the application is deployed successfully</p><h3>Canary Model Deployment</h3><ul><li><strong>Canary strategy</strong>: Roll out a new version to a small subset of users first, limiting the impact of potential bugs.</li><li><strong>Feedback-driven</strong>: Based on feedback, either fully roll out or roll back the new version.</li><li><strong>Real-world testing</strong>: Ensures that new changes are tested in a real environment before widespread deployment.</li><li><strong>Gradual rollout</strong>: As confidence grows, the new version is slowly deployed to the entire infrastructure.</li></ul><h3>Blue Green Deployments</h3><ul><li><strong>Bue/green strategy</strong> involves running two identical environments: a <strong>new version (green)</strong> alongside an <strong>old version (blue)</strong>.</li><li>At any given time, only <strong>one version</strong> (blue or green) is <strong>live</strong>.</li><li>Traffic is initially routed to the <strong>blue (old) deployment</strong> while the <strong>green (new) deployment</strong> is created and tested.</li><li>After testing, <strong>traffic is switched</strong> to the <strong>green deployment</strong> (new version).</li><li>The <strong>blue deployment</strong> is kept for potential <strong>rollback</strong> if needed.</li></ul><p><strong>Advantages</strong>:</p><ul><li>Provides a <strong>smooth transition</strong> between versions with minimal downtime.</li><li>Allows for <strong>easy rollback</strong> in case of issues with the new deployment.</li></ul><p><strong>Disadvantages</strong>:</p><ul><li>Requires <strong>double resources</strong> to run both blue and green environments simultaneously, leading to <strong>higher costs</strong>.</li><li>Needs a mechanism to <strong>rapidly switch traffic</strong> between the two deployments for seamless operations</li></ul><p>Implementation</p><p><strong>Create a Blue-deployment.yaml file and fololw the code given below</strong></p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: blue<br>spec:<br>  selector:<br>    app: myapp<br>  ports:<br>    - protocol: TCP<br>      port: 80<br>      targetPort: 3000<br>  type: NodePort</pre><p>after that apply the deployment using</p><pre>kubectl apply -f blue-deployment.yaml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fm_Gw2sIUV6IRKwiDnsApw.png" /></figure><p>after that now we have to create the service for our blue deployment Create a Blue-service.yaml file and follow the code given below</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: blue<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: myapp<br>      env: blue<br>  template:<br>    metadata:<br>      labels:<br>        app: myapp<br>        env: blue<br>    spec:<br>      containers:<br>        - name: myapp<br>          image: your-image:tag  # Replace with your actual image name<br>          ports:<br>            - containerPort: 3000</pre><p>after that run</p><pre>kubectl apply -f blue-service.yaml</pre><p>since we have configured our blue service and deployment now we have to view our deployment view on browser simply run the</p><pre>minikube  service blue</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m2ZpJmyxIkddTiWazIWqWg.png" /></figure><p>it will fetch up the browser and you are gonna see the section on website as following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Trx-VPdPEnVp4ScWYRrvcA.png" /></figure><p>The next step is to create the green-deployment. Use the below code for the green-deployment.</p><p>as earlier done create the deployment and service for the green deployment as folling the service</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: green<br>spec:<br>  replicas: 0  # Set to 0 if you want to deploy but not run any instances initially<br>  selector:<br>    matchLabels:<br>      app: myapp<br>      env: green  # Match labels should include &quot;env: green&quot;<br>  template:<br>    metadata:<br>      labels:<br>        app: myapp<br>        env: green  # Ensure the labels match the selector<br>    spec:<br>      containers:<br>      - name: myapp<br>        image: balav8/green-env  # Use your specified image<br>        ports:<br>        - containerPort: 3000</pre><p><strong>here as you may see the replica are set to the 0 you may update them later and env for the image is green</strong></p><p>now run</p><pre>kubectl apply -f green-deployment.yaml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TacMUJwCZ8z_tvWFjDe36Q.png" /></figure><p>Check the pods if they are running. untill now it will be zero</p><p>move upto yours file and change the replicas to 3 it will take mode pods into the environemnt and we will be good enough to do our deployment</p><p>Now switch the traffic to green deployment. To do this, just edit your service file which you had created earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*b2__5TsUvBKl0GmczDT81Q.png" /></figure><p>Just change the env from blue to green, and apply the changes.</p><pre>kubectl apply -f Blue-service.yaml</pre><p>Once you have run the above command, go to your browser and refresh the page to see the new version deployed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*zrDH0mrP2wvi2IPCHsYIJw.png" /></figure><p>We have successfully deployed the green environment. This is how blue/green deployment strategy works</p><h3>CONCLUSION</h3><p>No single strategy fits all scenarios. The decision should come from thoroughly analyzing the application requirements, organizational context and capabilities. Conclusion: To sum up, there are different ways to deploy an application. Each strategy — Rolling Update, Canary Deployment, and Blue/Green Deployment — offers unique benefits and challenges. Rolling Update provides a smooth transition with minimal downtime, Canary Deployment allows for controlled testing with real users, and Blue/Green Deployment offers quick rollback capabilities. The key is to choose the strategy that best aligns with your application’s needs, your team’s expertise, and your organization’s goals.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=809d7b391b7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Real-Time Cloud Native Monitoring: Scalable Flask App Deployment with AWS and Docker”]]></title>
            <link>https://medium.com/@hamza.meehmood/real-time-cloud-native-monitoring-scalable-flask-app-deployment-with-aws-and-docker-ae670881ecbc?source=rss-5b0480abc79a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae670881ecbc</guid>
            <dc:creator><![CDATA[Hamza Meehmood]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 23:59:36 GMT</pubDate>
            <atom:updated>2024-10-14T23:59:36.813Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*araE1aYZx6Ws3SPE" /></figure><p>xBefore we start the project, make sure you have the following:</p><h3>1. AWS Account</h3><p>2. Programmatic Access and AWS CLI Configured</p><p>To configure AWS CLI for programmatic access, follow these steps:</p><ul><li><strong>Step 1: Install AWS CLI</strong></li><li>curl &quot;https://awscli.amazonaws.com/AWSCLIV2.pkg&quot; -o &quot;AWSCLIV2.pkg&quot; sudo installer -pkg AWSCLIV2.pkg -target /</li><li>On <strong>Windows</strong>, download the installer from here.</li><li><strong>Step 2: Create an IAM User</strong></li></ul><ol><li>Sign in to the <strong>AWS Management Console</strong>.</li><li>Go to <strong>IAM</strong> → <strong>Users</strong> → <strong>Add user</strong>.</li><li>Select <strong>Programmatic access</strong>.</li><li>Attach <strong>AdministratorAccess</strong> policy.</li><li>Download the <strong>Access Key ID</strong> and <strong>Secret Access Key</strong>.</li></ol><ul><li><strong>Step 3: Configure AWS CLI</strong> Open your terminal and run</li><li>aws configure</li><li>Enter your <strong>Access Key ID</strong>, <strong>Secret Access Key</strong>, region (e.g., us-east-1), and default output format (e.g., json).</li></ul><h3>3. Python 3 Installed</h3><p>Make sure Python 3 is installed on your system:</p><ul><li>On <strong>Mac/Linux</strong>, check if Python is installed</li><li>python3 --version</li><li>If not installed, use:</li></ul><blockquote>sudo apt install python3 # for Linux brew install python3 # for Mac</blockquote><ul><li>On <strong>Windows</strong>, download Python from <a href="https://www.python.org/downloads/">here</a>.</li><li>4. Docker and kubectl Installed</li><li><strong>Step 1: Install Docker</strong></li></ul><blockquote>sudo apt-get update sudo apt-get install docker-ce docker-ce-cli containerd.io</blockquote><ul><li><strong>Step 2: Install kubectl</strong></li><li>Follow the installation instructions for kubectl h</li></ul><h3>5. Code Editor (VSCode)</h3><p>Download and install Visual Studio Code from <a href="https://code.visualstudio.com/">here</a>.</p><h3>✨ Let’s Start the Project ✨</h3><h3>Part 1: Deploying the Flask Application Locally</h3><h3>Step 2: Clone the Code</h3><p>To begin, clone the code from the GitHub repository using the following command:</p><pre>git clone https://github.com/N4si/cloud-native-monitoring-a</pre><h3>Step 2: Install Dependencies</h3><p>The application requires several Python libraries such as psutil, Flask, Plotly, and boto3. Install these dependencies using the requirements.txt file</p><pre>pip3 install -r requirements.txt</pre><p>Navigate to the root directory of the project and run the Flask application using this command</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFbQGMDA2R3KDdU2XhTzlA.png" /></figure><p>Once the server is up, open your browser and go to <a href="http://localhost:5000/">http://localhost:5000/</a> to access the application.</p><h3>Part 2: Dockerizing the Flask application</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*araE1aYZx6Ws3SPE" /></figure><p>xBefore we start the project, make sure you have the following:</p><h3>1. AWS Account</h3><p>2. Programmatic Access and AWS CLI Configured</p><p>To configure AWS CLI for programmatic access, follow these steps:</p><ul><li><strong>Step 1: Install AWS CLI</strong></li><li>curl &quot;https://awscli.amazonaws.com/AWSCLIV2.pkg&quot; -o &quot;AWSCLIV2.pkg&quot; sudo installer -pkg AWSCLIV2.pkg -target /</li><li>On <strong>Windows</strong>, download the installer from here.</li><li><strong>Step 2: Create an IAM User</strong></li></ul><ol><li>Sign in to the <strong>AWS Management Console</strong>.</li><li>Go to <strong>IAM</strong> → <strong>Users</strong> → <strong>Add user</strong>.</li><li>Select <strong>Programmatic access</strong>.</li><li>Attach <strong>AdministratorAccess</strong> policy.</li><li>Download the <strong>Access Key ID</strong> and <strong>Secret Access Key</strong>.</li></ol><ul><li><strong>Step 3: Configure AWS CLI</strong> Open your terminal and run</li><li>aws configure</li><li>Enter your <strong>Access Key ID</strong>, <strong>Secret Access Key</strong>, region (e.g., us-east-1), and default output format (e.g., json).</li></ul><h3>3. Python 3 Installed</h3><p>Make sure Python 3 is installed on your system:</p><ul><li>On <strong>Mac/Linux</strong>, check if Python is installed</li><li>python3 --version</li><li>If not installed, use:</li></ul><blockquote><em>sudo apt install python3 # for Linux brew install python3 # for Mac</em></blockquote><ul><li>On <strong>Windows</strong>, download Python from <a href="https://www.python.org/downloads/">here</a>.</li><li>4. Docker and kubectl Installed</li><li><strong>Step 1: Install Docker</strong></li></ul><blockquote><em>sudo apt-get update sudo apt-get install docker-ce docker-ce-cli containerd.io</em></blockquote><ul><li><strong>Step 2: Install kubectl</strong></li><li>Follow the installation instructions for kubectl h</li></ul><h3>5. Code Editor (VSCode)</h3><p>Download and install Visual Studio Code from <a href="https://code.visualstudio.com/">here</a>.</p><h3>✨ Let’s Start the Project ✨</h3><h3>Part 1: Deploying the Flask Application Locally</h3><h3>Step 2: Clone the Code</h3><p>To begin, clone the code from the GitHub repository using the following command:</p><pre>git clone https://github.com/N4si/cloud-native-monitoring-a</pre><h3>Step 2: Install Dependencies</h3><p>The application requires several Python libraries such as psutil, Flask, Plotly, and boto3. Install these dependencies using the requirements.txt file</p><pre>pip3 install -r requirements.txt</pre><p>Navigate to the root directory of the project and run the Flask application using this command</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFbQGMDA2R3KDdU2XhTzlA.png" /></figure><p>Once the server is up, open your browser and go to <a href="http://localhost:5000/">http://localhost:5020/</a> to access the application.</p><h3>Step 3: Dockerizing the Flask application</h3><pre>FROM python:3.9-buster<br><br># Set the working directory<br>WORKDIR /app<br><br># Copy the requirements file to the container<br>COPY requirements.txt .<br><br># Install dependencies<br>RUN pip3 install --no-cache-dir -r requirements.txt<br><br># Copy the rest of the application code to the container<br>COPY . .<br><br># Set environment variables<br>ENV FLASK_RUN_HOST=0.0.0.0<br><br># Expose the port Flas k will run on<br>EXPOSE 5020<br><br># Define the command to start the Flask app<br>CMD [&quot;flask&quot;, &quot;run&quot;, &quot;--host=0.0.0.0&quot;, &quot;--port=5020&quot;]</pre><ol><li><strong>Open your terminal</strong> in the project directory and run the following command to build the Docker image:</li><li>docker run -d -p 5020:5020 flask-monitoring-app</li><li><strong>Running the Docker Container</strong></li><li>docker run -d -p 5020:5020 flask-monitoring-app</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LWBNDnaV5QVsDhDk3AMXzw.png" /></figure><p>Once the server is up, open your browser and go to <a href="http://localhost:5000/">http://localhost:5020/</a> to access the application</p><h3>Part 3: Pushing the Docker Image to ECR</h3><h3>Step 1: Create an ECR Repository</h3><p>To begin, we need to create an ECR repository where we can store our Docker images. We’ll use the boto3 library, which is the AWS SDK for Python, to interact with ECR.</p><p>First, make sure you have the boto3 library installed. You can install it using pip if you haven&#39;t done so already</p><pre>pip install boto3</pre><p>Now, let’s create an ECR repository with the following code</p><pre># Create an ECR client<br>ecr_client = boto3.client(&#39;ecr&#39;)</pre><pre># Create a new ECR repository<br>repository_name = &#39;my-ecr-repo&#39;<br>response = ecr_client.create_repository(repositoryName=repository_name)</pre><pre># Print the repository URI<br>repository_uri = response[&#39;repository&#39;][&#39;repositoryUri&#39;]<br>print(repository_uri)</pre><p>In this code, we create an ECR client and then create a repository named my-ecr-repo. The response from the AWS API contains the repository URI, which we print out. This URI will be used later when we push our Docker image.</p><h3>Step 2: Push the Docker Image to ECR</h3><p>After creating the repository, you can now push your Docker image to ECR. First, ensure that you have logged in to your ECR registry using the AWS CLI</p><pre>aws ecr get-login-password --region &lt;your-region&gt; | docker login --username AWS --password-stdin &lt;account-id&gt;.dkr.ecr.&lt;your-region&gt;.amazonaws.com</pre><p>Replace &lt;your-region&gt; and &lt;account-id&gt; with your AWS region and account ID, respectively. Once logged in, you can push your Docker image to ECR using the following command:</p><pre>docker push &lt;ecr_repo_uri&gt;:&lt;tag&gt;</pre><p>Replace &lt;ecr_repo_uri&gt; with the repository URI you obtained in the previous step, and &lt;tag&gt; with the specific tag you want to assign to your image (e.g., latest).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cOElqMkE9qmn4cUM3XnJlg.png" /></figure><h3>Part 4: Creating an EKS Cluster and Deploying the App Using Python</h3><h3>Step 1: Create a eks cluster</h3><p>Create an EKS cluster and add node groupStep 2: Create a node group</p><p>Create a node group in the EKS cluster. with atleast two nodes</p><h3>Part 5: Creating an EKS cluster and deploying the app using Python</h3><pre>from kubernetes import client, config<br><br># Load Kubernetes configuration<br>config.load_kube_config()<br><br># Create a Kubernetes API client<br>api_client = client.ApiClient()<br><br># Define the deployment<br>deployment = client.V1Deployment(<br>    metadata=client.V1ObjectMeta(name=&quot;my-flask-app&quot;),<br>    spec=client.V1DeploymentSpec(<br>        replicas=1,<br>        selector=client.V1LabelSelector(<br>            match_labels={&quot;app&quot;: &quot;my-flask-app&quot;}<br>        ),<br>        template=client.V1PodTemplateSpec(<br>            metadata=client.V1ObjectMeta(<br>                labels={&quot;app&quot;: &quot;my-flask-app&quot;}<br>            ),<br>            spec=client.V1PodSpec(<br>                containers=[<br>                    client.V1Container(<br>                        name=&quot;my-flask-container&quot;,<br>                        image=&quot;568373317874.dkr.ecr.us-east-1.amazonaws.com/my-cloud-native-repo:latest&quot;,  # Replace with your image URI<br>                        ports=[client.V1ContainerPort(container_port=5000)]<br>                    )<br>                ]<br>            )<br>        )<br>    )<br>)<br><br># Create the deployment<br>api_instance = client.AppsV1Api(api_client)<br>api_instance.create_namespaced_deployment(<br>    namespace=&quot;default&quot;,<br>    body=deployment<br>)<br><br># Define the service<br>service = client.V1Service(<br>    metadata=client.V1ObjectMeta(name=&quot;my-flask-service&quot;),<br>    spec=client.V1ServiceSpec(<br>        selector={&quot;app&quot;: &quot;my-flask-app&quot;},<br>        ports=[client.V1ServicePort(port=5000)]<br>    )<br>)<br><br># Create the service<br>api_instance = client.CoreV1Api(api_client)<br>api_instance.create_namespaced_service(<br>    namespace=&quot;default&quot;,<br>    body=service<br>)</pre><h3>Step 2: Running the Script</h3><p>Once the script is set up, you can run it to deploy your Flask app to EKS</p><pre>ypython3 eks.py</pre><p>The script will automatically create both the deployment and the service in your Kubernetes cluster.</p><h3>Step 3: Verify the Deployment and Service</h3><p>After running the script, verify that the deployment, pods, and service were created successfully by running these kubectl commands:</p><ol><li><strong>Check Deployment</strong></li></ol><ul><li>bash</li><li>Copy code</li><li>kubectl get deployment -n default</li></ul><ol><li>This will show the deployment and the number of replicas running.</li><li><strong>Check Service</strong></li></ol><ul><li>bash</li><li>Copy code</li><li>kubectl get service -n default</li></ul><ol><li>This lists the services running in the default namespace, including my-flask-service.</li><li><strong>Check Pods</strong></li></ol><ul><li>bash</li><li>Copy code</li><li>kubectl get pods -n default</li></ul><ol><li>This command lists the pods running in the default namespace. Ensure your pod is in a <strong>Running</strong> state.</li></ol><h3>Step 4: Expose the Flask App</h3><p>Since your service is only exposed internally within the cluster, you’ll need to forward the port to access it locally. Use kubectl port-forward to bind your local port to the service:</p><pre>bas</pre><pre>kubectl port-forward service/my-flask-service 5000:5000</pre><p>Now, you should be able to access your Flask application on <a href="http://localhost:5000!">http://localhost:5020!</a></p><h3>Step 5: Monitor and Scale the Application</h3><p>You can monitor the logs of your running Flask application by using the following command</p><pre>kubectl logs &lt;pod-name&gt; -n default</pre><p>To scale your application, you can edit the number of replicas directly in the Python script or by running</p><pre>kubectl scale deployment my-flask-app --replicas=3 -n default</pre><p>This will increase the number of running pods to 3.</p><p>Happy coding, and enjoy your newly deployed Flask app on EKS!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae670881ecbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive Monitoring Setup with Prometheus, Node Exporter, and Alert Manager]]></title>
            <link>https://medium.com/@hamza.meehmood/comprehensive-monitoring-setup-with-prometheus-node-exporter-and-alert-manager-d8c455d36d80?source=rss-5b0480abc79a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8c455d36d80</guid>
            <dc:creator><![CDATA[Hamza Meehmood]]></dc:creator>
            <pubDate>Mon, 07 Oct 2024 18:59:49 GMT</pubDate>
            <atom:updated>2024-10-08T10:30:09.709Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/765/0*Dn76dVhX0AjAI7vI" /></figure><p>In this blog, we will see how to set up and configure monitoring tools for a DevOps project such as Node Exporter, Blackbox Exporter and Alert Manager and send notification to the team via email.</p><p>Pre-requisites:</p><ol><li>AWS Account</li><li>Basic Monitoring Understanding</li></ol><p>Security Ports:</p><ol><li>Prometheus: Port 9090</li><li>Node Exporter: Port 9100</li><li>Blackbox Exporter: Port 9115</li><li>Alertmanager: Port 9093</li><li>Application: Port 8080</li></ol><p>Tools Overview:</p><ol><li>Prometheus</li><li>It is an open source application used for event monitoring and alerting. It records metrics in a time series database.</li><li>Node Exporter</li><li>It is an agent that gathers the system metrics such as CPU / Disk / Network and exposes them in a format which can be ingested by Prometheus.</li><li>Black Box Exporter</li><li>It is used for endpoint monitoring, allowing you to check endpoints and generate uptime and availability metrics.</li><li>Alert Manager</li><li>The Alertmanager handles the alerts sent by a client applications such as promethues server.</li></ol><p>Steps:</p><ul><li>Go to the AWS Console, and launch two Ubuntu instances with instance type as t3.medium and set the storage as 20GB and rest you can keep as the default.</li><li>One instance we will have our application and this application we need to monitor, the other application is where we install the tools such as the node exporter, blackbox exporter and alert manager.</li><li>Rename both the instances accordingly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iZ6mYcHaUEwaWrrT" /></figure><ul><li>Open the first instance using putty or mobaxterm, in which we will install all the tools starting with prometheus, node exporter and blackbox exporter.</li><li>Open <a href="http://prometheus.io/">prometheus.io</a> and click on download.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WniCqfX2TSlElzzx" /></figure><ul><li>In the next page, select the prometheus link for your OS. Right click on the link and select the copy link address.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YlDc3lVmk87GZYG_" /></figure><ul><li>Open your instance and first run the below command</li></ul><pre>sudo apt update</pre><ul><li>Paste the link address which you had copied earlier and run</li></ul><pre>wget https://github.com/prometheus/prometheus/releases/download/v2.53.2/prometheus-2.53.2.linux-amd64.tar.gz</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XN4V9OnaCs8LX9LA" /></figure><ul><li>Once downloaded, extract using tar the file which you had downloaded.</li></ul><pre>tar -xvf prometheus-2.53.2.linux-amd64.tar.gz</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/0*xcWSTqiY1gEVK0KA" /></figure><ul><li>Next we will install the blackbox exporter which you can find below in the same documentation.</li><li>Select the link address and go to your terminal and paste it and download the package with wget like earlier.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yv9VWSPEQcMWm0oW" /></figure><ul><li>Install and extract the same way you did for Prometheus.</li><li>Next, Install the alert manager which is also available in the same documentation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A4ALYUSYQTN13pXc" /></figure><ul><li>Install and extract the same way you have done for earlier tools.</li><li>Now, Go to your second VM and update using below command.</li></ul><pre>sudo apt update</pre><ul><li>Install node exporter in this VM, go to the same Prometheus documentation and you can find node exporter package, copy link address and paste and extract in your VM using the same method.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mINwteSorZdOwKOp" /></figure><ul><li>Open the node exporter folder, where you can find the node exporter file which is executable.</li><li>Run the file using below command.</li></ul><pre>./node_exporter &amp;</pre><ul><li>This &amp; will run the service in background, and now access the node exporter using the Public IP of your instance with port 9100. Open the port 9100 in the security group.</li><li>Clone the java application and go inside the application.</li><li>Install java using command below command</li></ul><pre>sudo apt install openjdk-17-jre-headles</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*98CC71C3ojTMv76C" /></figure><ul><li>Now install maven using below command</li></ul><pre>sudo apt install maven -y</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u49CDGm59ePpqz5Z" /></figure><ul><li>Build the project of your application using the command</li></ul><pre>mvn package</pre><p>Once the build is completed, go inside the target folder and run the jar file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ikf1vXex8Yt6JkDI" /></figure><ul><li>To run the application use the below command</li></ul><pre>java -jar database_service_project-0.0.2.jar</pre><ul><li>Open a new browser and copy the public Ip with the port 8080 to see the application running successfully.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c1ZJ_hS9qsKcKX_P" /></figure><ul><li>Now we need to monitor this website. Go to the monitoring instance in which we have installed all the required tools.</li><li>Open the Prometheus folder and run the Prometheus file using the below command.</li></ul><pre>./prometheus &amp;</pre><ul><li>Copy the Public IP with Port 9090 and Prometheus is running.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uhWMQLngrzweHID0" /></figure><ul><li>Go to the Prometheus folder and create a new file called alert_rules.yaml and copy the below contents.</li></ul><pre>  ---<br>  groups:<br>    - name: alert_rules<br>      rules:<br>        - alert: InstanceDown<br>          expr: up == 0<br>          for: 1m<br>          labels:<br>            severity: critical<br>          annotations:<br>            summary: Endpoint {{ $labels.instance }} down<br>            description: &quot;{{ $labels.instance }} of job {{ $labels.job }} has been down for<br>              more than 1 minute.&quot;<br>        - alert: WebsiteDown<br>          expr: probe_success == 0<br>          for: 1m<br>          labels:<br>            severity: critical<br>          annotations:<br>            description: The website at {{ $labels.instance }} is down.<br>            summary: Website down<br>        - alert: HostOutOfMemory<br>          expr: (node_memory_MemAvailable / node_memory_MemTotal) * 100 &lt; 25<br>          for: 5m<br>          labels:<br>            severity: warning<br>          annotations:<br>            summary: Host out of memory (instance {{ $labels.instance }})<br>            description: |-<br>              Node memory is filling up (&lt; 25% left)<br>               VALUE = {{ $value }}<br>               LABELS: {{ $labels }}<br>        - alert: HostOutOfDiskSpace<br>          expr: (node_filesystem_avail{mountpoint=&quot;/&quot;} * 100) /<br>            node_filesystem_size{mountpoint=&quot;/&quot;} &lt; 50<br>          for: 1m<br>          labels:<br>            severity: warning<br>          annotations:<br>            summary: Host out of disk space (instance {{ $labels.instance }})<br>            description: |-<br>              Disk is almost full (&lt; 50% left)<br>               VALUE = {{ $value }}<br>               LABELS: {{ $labels }}<br>        - alert: HostHighCpuLoad<br>          expr: (100 - (avg by (instance)<br>            (irate(node_cpu_seconds_total{mode=&quot;idle&quot;}[5m]))) * 100) &gt; 80<br>          for: 5m<br>          labels:<br>            severity: warning<br>          annotations:<br>            summary: Host high CPU load (instance {{ $labels.instance }})<br>            description: |-<br>              CPU load is &gt; 80%<br>               VALUE = {{ $value }}<br>               LABELS: {{ $labels }}<br>        - alert: ServiceUnavailable<br>          expr: up{job=&quot;node_exporter&quot;} == 0<br>          for: 2m<br>          labels:<br>            severity: critical<br>          annotations:<br>            summary: Service Unavailable (instance {{ $labels.instance }})<br>            description: |-<br>              The service {{ $labels.job }} is not available<br>               VALUE = {{ $value }}<br>               LABELS: {{ $labels }}<br>        - alert: HighMemoryUsage<br>          expr: (node_memory_Active / node_memory_MemTotal) * 100 &gt; 90<br>          for: 10m<br>          labels:<br>            severity: critical<br>          annotations:<br>            summary: High Memory Usage (instance {{ $labels.instance }})<br>            description: |-<br>              Memory usage is &gt; 90%<br>               VALUE = {{ $value }}<br>               LABELS: {{ $labels }}<br>        - alert: FileSystemFull<br>          expr: (node_filesystem_avail / node_filesystem_size) * 100 &lt; 10<br>          for: 5m<br>          labels:<br>            severity: critical<br>          annotations:<br>            summary: File System Almost Full (instance {{ $labels.instance }})<br>            description: |-<br>              File system has &lt; 10% free space<br>               VALUE = {{ $value }}<br>               LABELS: {{ $labels }}</pre><ul><li>Save the file and now open prometheus.yaml file</li><li>Go to the alert files section and provide the name of the alert file which you had just created in the previous step.</li><li>Run the alert manager by going inside the alert manager folder and run using command.</li><li>./alertmanager &amp;</li><li>Copy the Public IP with Port 9093 and see if the alert manager is running.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eYgUJkfZW6JvBdU6" /></figure><ul><li>Restart the Prometheus service to see if the rules are populated.</li><li>To restart we will kill the prometheus service using command which will give the PID of the prometheus</li></ul><pre>pgrep prometheus</pre><ul><li>Kill “PID” to kill the process and again start it using command “./prometheus &amp;”</li><li>Reload the Prometheus page again and go to rules to see all the rules displayed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oMv4ieYCMYii-rkr" /></figure><ul><li>Open the Prometheus,yml file and set the target for the alert manager. Just uncomment the alertmanager and provide the IP of the alert manager.</li><li>Inside the scrape metrics, add the following lines as the node exporter targets and save the file.</li></ul><pre>  scrape_configs:<br>    # The job name is added as a label `job=&lt;job_name&gt;` to any timeseries scraped from this config.<br>    - job_name: &quot;prometheus&quot;<br><br>      # metrics_path defaults to &#39;/metrics&#39;<br>      # scheme defaults to &#39;http&#39;.<br><br>      static_configs:<br>        - targets: [&quot;localhost:9090&quot;]<br>    - job_name: node_exporter<br>      static_configs:<br>        - targets:<br>            - 13.201.170.34:9100<br><br>    - job_name: blackbox<br>      metrics_path: /probe<br>      params:<br>        module:<br>          - http_2xx<br>      static_configs:<br>        - targets:<br>            - http://prometheus.io<br>            - https://prometheus.io<br>            - http://13.201.170.34:8080<br>      relabel_configs:<br>        - source_labels:<br>            - __address__<br>          target_label: __param_target<br>        - source_labels:<br>            - __param_target<br>          target_label: instance<br>        - target_label: __address__<br>          replacement: 15.206.188.156:911</pre><ul><li>Restart the Prometheus service again as we did earlier.</li><li>Once the prometheus site is up, go to targets and you can see the node exporter is up and running.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DM42wsCBRE01dR1S" /></figure><ul><li>Now we need to add the black box exporter, go to the official documentation of Prometheus and scroll down to black box exporter and click on the <a href="https://github.com/prometheus/blackbox_exporter">github</a> link provided along with it.</li><li>Scroll down in the github repo and you will find the scrape configs, copy it and paste it in yaml lint site as we need to modify it.</li></ul><pre>  scrape_configs:<br>    - job_name: &#39;blackbox&#39;<br>      metrics_path: /probe<br>      params:<br>        module: [http_2xx]  # Look for a HTTP 200 response.<br>      static_configs:<br>        - targets:<br>          - http://prometheus.io    # Target to probe with http.<br>          - https://prometheus.io   # Target to probe with https.<br>          - http://example.com:8080 # Target to probe with http on port 8080.<br>      relabel_configs:<br>        - source_labels: [__address__]<br>          target_label: __param_target<br>        - source_labels: [__param_target]<br>          target_label: instance<br>        - target_label: __address__<br>          replacement: 127.0.0.1:9115</pre><ul><li>Replace your application IP address in the targets section, and also the black box IP(VM) in the last line which states replacement IP.</li><li>Restart again the Prometheus service.</li><li>Check the targets section in Prometheus site, and you will see black box is added but service is down</li><li>Let us start the black box exporter using command</li></ul><pre>./blackbox _exporter </pre><ul><li>Copy the public Ip with port 9115 and run it in the new browser to see black box exporter running.</li><li>We can see that the black box exporter is running and the target is fetched successfully.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LmiW6OB-OR2hAdV3" /></figure><ul><li>Now all the service is running once you refresh.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qI8MuecvZ7D_2AE3" /></figure><ul><li>Let us configure the email notification for the services, for that first we need to generate an app password from our account.</li><li>Before that you need to turn on “Two step verification” from the security section in <a href="https://myaccount.google.com/">https://myaccount.google.com/</a></li><li>Now create an app password and copy and use it in your file.</li><li>Create a file alertmanager.yml inside the alert manager folder and paste the content for the email notification.</li></ul><pre>  ---<br>  route:<br>    group_by:<br>      - alertname<br>    group_wait: 30s<br>    group_interval: 5m<br>    repeat_interval: 1h<br>    receiver: email-notifications<br>  receivers:<br>    - name: email-notifications<br>      email_configs:<br>        - to: example@gmail.com<br>          from: monitoring@example.com<br>          smarthost: smtp.gmail.com:587<br>          auth_username: example@gmail.com<br>          auth_identity: example@gmail.com<br>          auth_password: wdmg ndpc xweb copp<br>          send_resolved: true<br>  inhibit_rules:<br>    - source_match:<br>        severity: critical<br>      target_match:<br>        severity: warning<br>      equal:<br>        - alertname<br>        - dev<br>        - instance</pre><ul><li>Restart alert manager using command “./alertmanager.yml &amp;”</li><li>Restart Prometheus again.</li><li>Now everything is set, just check the targets in the Prometheus site for confirmation.</li><li>Check the alerts in the Prometheus site for all the configured alerts.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gHhA6a3BpG7rDppU" /></figure><ul><li>Now to test, just stop your website and check the Prometheus server, it will show the site is down and in a few mins you will also get an email stating the website is down.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PCKuDIWWHIlIsUms" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D2thlNcWntTLb_zs" /></figure><ul><li>Also the mail has been fired to the given recipient mail address</li><li>Now stop the node exporter and you can see the service is unavailable and the second mail has been received.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*03Fl3aDZqSS9TBpq" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BQQnsXODDboPPVN6.png" /></figure><ul><li>Once the instance and node exporter is down, we can see that the alerts have been active and the mail has been fired.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zYI9k0ctkUWog3lX" /></figure><ul><li>This covers everything about the monitoring project.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8c455d36d80" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>