<?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 Yahya sghiouri on Medium]]></title>
        <description><![CDATA[Stories by Yahya sghiouri on Medium]]></description>
        <link>https://medium.com/@yahyasghiouri1998?source=rss-926c8b21d31f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BhyHTEgefa0gWvWQPYM4ew.jpeg</url>
            <title>Stories by Yahya sghiouri on Medium</title>
            <link>https://medium.com/@yahyasghiouri1998?source=rss-926c8b21d31f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 19:20:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yahyasghiouri1998/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[A Structured Approach to Linux Troubleshooting]]></title>
            <link>https://medium.com/@yahyasghiouri1998/a-structured-approach-to-linux-troubleshooting-2e7ecfa4c6a6?source=rss-926c8b21d31f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e7ecfa4c6a6</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[troubleshooting]]></category>
            <category><![CDATA[itil]]></category>
            <category><![CDATA[system-administration]]></category>
            <dc:creator><![CDATA[Yahya sghiouri]]></dc:creator>
            <pubDate>Sat, 16 May 2026 05:46:20 GMT</pubDate>
            <atom:updated>2026-05-16T05:46:29.800Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stAvwRMO28mcV4pB2SPZRw.png" /><figcaption>Observe. Analyze. Isolate. Resolve.</figcaption></figure><p>Linux troubleshooting is more than running commands or restarting services. In production environments, every action can impact applications, users, and critical infrastructure. A strong troubleshooting approach is therefore based on observation, analysis, and controlled decision-making.</p><p>Production environments also require more than technical knowledge alone. Recruiters and hiring managers often look for engineers who can communicate clearly, troubleshoot methodically, and follow a logical diagnostic path under pressure. The objective is not to jump rapidly between multiple hypotheses or actions, but to isolate the problem step by step, minimize risk, and explain reasoning in a structured way.</p><p>This is important because production teams need to trust that an engineer can handle operational pressure without creating additional risk. In critical environments, calm analysis, structured troubleshooting, and controlled actions are often valued more than reacting quickly without a clear diagnostic path.</p><p>Rather than trying multiple fixes at once, effective troubleshooting focuses on isolating the issue layer by layer — whether it is related to the network, services, operating system, security, storage, or application logic. The goal is not only to restore functionality, but also to understand the root cause while minimizing operational impact.</p><p>This article explores a structured approach to Linux troubleshooting, emphasizing methodical analysis, incident isolation, log investigation, and production-oriented troubleshooting habits.</p><h3>Reflexes to adopt In a production Setup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwGAhn2MKm0lo6poYdn0NQ.png" /><figcaption>Mindset to adopt in production</figcaption></figure><h4>1/Structured Troubleshooting</h4><ul><li>Avoid jumping between multiple hypotheses at once</li><li>Follow a consistent diagnostic sequence:<br>observe → isolate → verify → act.</li></ul><p><strong>Example scenario</strong></p><p>“A server cannot reach an IP address through a specific interface.”</p><ol><li>Observe</li></ol><p>First, clarify the scope of the issue.</p><p>Questions:</p><ul><li>Which server is affected?</li><li>Which destination IP is unreachable?</li><li>Which interface should be used?</li><li>Did it work before?</li><li>Is the issue isolated or affecting multiple systems?</li></ul><p>Initial checks:</p><pre>ip addr<br>ip link<br>systemctl status networking</pre><p>Goal:<br>Confirm the interface exists, is UP, and has the correct IP address.</p><ol><li><strong>Isolate</strong></li></ol><p>Test whether the issue is local connectivity, routing, firewall, or external network related.</p><p>Check connectivity to the gateway:</p><pre>ping -I &lt;interface&gt; &lt;gateway_ip&gt;</pre><p>Examples:</p><pre>ping -I eth0 192.168.1.1</pre><p>If the gateway is unreachable, possible causes include:</p><ul><li>wrong subnet,</li><li>interface issue,</li><li>VLAN/network problem,</li><li>switch/link issue.</li></ul><p>Check routing:</p><pre>ip route<br>ip route get &lt;destination_ip&gt;</pre><p>Example:</p><pre>ip route get 8.8.8.8</pre><p>Goal:<br>Verify Linux is using the expected interface and route.</p><p><strong>2. Verify</strong></p><p>Check firewall</p><pre>sudo ufw status verbose</pre><p>Check logs:</p><pre>journalctl -u networking<br>dmesg | grep -i eth</pre><p>Verify packets leave the interface:</p><pre>sudo tcpdump -i &lt;interface&gt; host &lt;destination_ip&gt;</pre><p>Example:</p><pre>sudo tcpdump -i eth0 host 8.8.8.8</pre><p>Goal:<br>Determine whether traffic leaves the server and whether replies come back.</p><p><strong>3. Act</strong></p><p>Only after identifying the likely cause,<strong> apply controlled corrective</strong> actions.</p><p>The next actions need to be done with approval with your manager, or request a change.</p><p><strong><em>Examples:</em></strong></p><p>Restart interface carefully:</p><pre>sudo ifdown eth0 &amp;&amp; sudo ifup eth0</pre><p>Or:</p><pre>sudo systemctl restart networking</pre><p>Only if justified and after evaluating impact.</p><p>Add a missing route:</p><pre>sudo ip route add &lt;network&gt; via &lt;gateway_ip&gt; dev &lt;interface&gt;</pre><p>Example:</p><pre>sudo ip route add 10.10.20.0/24 via 192.168.1.1 dev eth0</pre><p>Avoid broad actions such as:</p><ul><li>disabling firewall,</li><li>changing multiple configs at once,</li><li>rebooting,</li><li><strong>or restarting services blindly.</strong></li></ul><p><strong>4. Escalate with evidence</strong></p><p>If unresolved, escalate with structured information:</p><ul><li>affected server,</li><li>interface,</li><li>destination IP,</li><li>routing results,</li><li>firewall status,</li><li>tcpdump observations,</li><li>logs collected,</li><li>suspected network layer.</li></ul><p>Example of responses of escalation motif :</p><p>“Interface eth0 is UP with the expected IP configuration. The route to the destination is correct, and packets are leaving the interface according to tcpdump, but no replies are received. Local firewall rules do not show drops. This may indicate an upstream routing, VLAN, or remote-side filtering issue.”</p><h4>2. Production Risk Awareness</h4><ul><li>Avoid disruptive actions too early:<br>- service restarts,<br>- disabling SELinux,</li><li>broad permission changes,firewall modifications.</li></ul><h4>3. Security-First Mindset</h4><ul><li>Diagnose security mechanisms before bypassing them.</li><li>Prefer understanding SELinux denials over disabling enforcement.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v7C_OeoAaEY96plu7ZM8fg.png" /><figcaption>General Guidelines For network ops in a production environment.</figcaption></figure><h4>4. Escalation Discipline</h4><ul><li>Escalate with evidence and scope analysis.</li><li>Clearly identify:<br>what was checked,<br>current impact,<br>suspected layer,<br>and remaining blockers.</li></ul><p><strong>5. Critical Environment Operational Reflexes</strong></p><ul><li>Improve calmness and prioritization under uncertainty.</li><li>Think in terms of impact minimization and controlled actions.</li></ul><p><strong>6. Layer-Based Approach Incident Isolation</strong></p><ul><li>Better separation of:<br>network,DNS,firewall,application,OS,storage,permissions,security layers.</li></ul><p><strong>7. Production Communication</strong></p><ul><li>Present troubleshooting steps in a clearer and more ordered way during interviews and incidents.</li></ul><h3>“Why Random Troubleshooting Is Dangerous”</h3><p>This would be VERY valuable because it explains <em>why</em> production engineers avoid random actions.</p><p>Why Random Troubleshooting Is Dangerous</p><p>In production environments, random troubleshooting can create more problems than the original incident itself.</p><p>Restarting services blindly, changing multiple configurations at once, or disabling security mechanisms without understanding the root cause may:</p><ul><li>interrupt active users,</li><li>destroy useful debugging evidence,</li><li>create cascading failures,</li><li>increase downtime,</li><li>or make root cause analysis significantly harder.</li></ul><p>This is why experienced operators generally follow one important principle:</p><p>Change one thing at a time, verify the impact, then continue.</p><p>Controlled troubleshooting is often slower at the beginning, but far safer and more efficient during critical incidents.</p><h3>“Logs Are Your Best Friend”</h3><p>Because right now you mention logs, but you do not emphasize their importance enough.</p><p>Logs Are Your Best Friend</p><p>One of the most important troubleshooting habits in Linux environments is learning how to read logs effectively.</p><p>Before restarting services or modifying configurations, logs often provide valuable clues about:</p><ul><li>authentication failures,</li><li>network issues,</li><li>permission denials,</li><li>service crashes,</li><li>hardware problems,</li><li>kernel events,</li><li>or dependency failures.</li></ul><p>Common commands:</p><p>journalctl -xe<br>journalctl -u <br>dmesg<br>tail -f /var/log/syslog</p><p>Good troubleshooting is often less about “trying fixes” and more about collecting evidence and understanding what the system is trying to communicate.</p><p><strong><em>Conclusion</em></strong></p><p>Linux troubleshooting is not only a technical skill — it is also an operational discipline.</p><p>Strong troubleshooters are not necessarily the people who react the fastest, but often the ones who remain methodical, minimize risk, communicate clearly, and isolate problems logically under pressure.</p><p>Production environments require trust, structured thinking, and controlled actions. Developing these reflexes takes time, repetition, and experience gained through real incidents and continuous learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e7ecfa4c6a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a real monitoring stack in my homelab — what broke, what I fixed, and what I learned]]></title>
            <link>https://medium.com/@yahyasghiouri1998/building-a-real-monitoring-stack-in-my-homelab-what-broke-what-i-fixed-and-what-i-learned-9aa99b234056?source=rss-926c8b21d31f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9aa99b234056</guid>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[system-administration]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[grafana]]></category>
            <dc:creator><![CDATA[Yahya sghiouri]]></dc:creator>
            <pubDate>Sat, 25 Apr 2026 13:04:14 GMT</pubDate>
            <atom:updated>2026-04-25T13:04:14.870Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EiwQal_X3jMNRo_UKqqJFA.png" /><figcaption>Prometheus, Grafana, and Nginx working together to provide full-stack observability in a homelab environment.</figcaption></figure><h3>🚀 I Thought Monitoring Was Easy… Until Nothing Worked</h3><p>I decided to build a monitoring stack in my homelab.</p><p>At first, it seemed simple:</p><ul><li>Install Prometheus</li><li>Install Grafana</li><li>Import a dashboard</li></ul><p>Done.</p><p>…or at least, that’s what I thought.</p><h3>❌ When “Everything Is Running” But Nothing Works</h3><p>At some point, I had:</p><ul><li>Prometheus running</li><li>Grafana accessible</li><li>Exporters deployed</li></ul><p>But:</p><ul><li>Grafana dashboards were empty</li><li>Prometheus showed no useful metrics</li><li>Nginx monitoring simply didn’t exist</li></ul><p>Everything <em>looked</em> correct.</p><p>But there was no data.</p><h3>📉 Empty dashboards (at the beginning)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TBV9oo__oAwWBwjN7IWpA.png" /><figcaption>Empty grafana dashboard</figcaption></figure><p>At this stage, all services were running, but nothing meaningful was being collected. This is one of the most confusing moments when starting with Prometheus — everything is “up”, but nothing is actually working.</p><p>That’s when I realized something important:</p><blockquote><em>Monitoring is not about installing tools.<br>It’s about understanding how data flows between systems.</em></blockquote><h3>🧠 What I Wanted to Build</h3><p>I wanted a setup that reflects real-world monitoring, not just a demo:</p><ul><li><strong>System metrics</strong> → CPU, memory, disk usage</li><li><strong>Container metrics</strong> → Docker resource consumption</li><li><strong>Application metrics</strong> → nginx traffic and connections</li></ul><p>Because in production, you need <strong>visibility across multiple layers</strong>, not just one.</p><h3>🧱 Architecture — Simple… but Misleading</h3><pre>Node Exporter  ─┐<br>cAdvisor       ─┼──→ Prometheus ───→ Grafana<br>nginx-exporter ─┘</pre><p>Let’s break this down.</p><h3>🔹 Exporters</h3><p>Exporters are responsible for <strong>exposing metrics</strong> in a format Prometheus understands.</p><ul><li>Node Exporter → system metrics</li><li>cAdvisor → container metrics</li><li>Nginx Exporter → nginx metrics</li></ul><h3>🔹 Prometheus</h3><p>Prometheus uses a <strong>pull model</strong>.</p><p>This means:</p><ul><li>It does NOT receive metrics</li><li>It does NOT push data</li><li>It actively <strong>scrapes endpoints</strong></li></ul><h3>🔹 Grafana</h3><p>Grafana does not collect data.</p><p>It:</p><ul><li>Queries Prometheus</li><li>Displays metrics</li><li>Builds dashboards</li></ul><h3>⚙️ Implementation</h3><p>👉 Full project:<br><a href="https://github.com/SpaaceCadet/-Observability-Stack-Prometheus-Grafana-Nginx-Monitoring">https://github.com/SpaaceCadet/-Observability-Stack-Prometheus-Grafana-Nginx-Monitoring</a></p><h3>🔹 Docker Compose</h3><pre>version: &quot;3.8&quot;</pre><pre>services:<br>  prometheus:<br>    image: prom/prometheus<br>    ports:<br>      - &quot;9091:9090&quot;<br>    extra_hosts:<br>      - &quot;host.docker.internal:host-gateway&quot;</pre><pre>  grafana:<br>    image: grafana/grafana<br>    ports:<br>      - &quot;3000:3000&quot;</pre><pre>  node-exporter:<br>    image: prom/node-exporter<br>    network_mode: host</pre><pre>  cadvisor:<br>    image: gcr.io/cadvisor/cadvisor<br>    ports:<br>      - &quot;8081:8080&quot;</pre><pre>  nginx-exporter:<br>    image: nginx/nginx-prometheus-exporter<br>    command:<br>      - -nginx.scrape-uri=http://host.docker.internal:8082/nginx_status<br>    ports:<br>      - &quot;9113:9113&quot;</pre><h3>🔹 Prometheus Configuration</h3><pre>global:<br>  scrape_interval: 5s</pre><pre>scrape_configs:<br>  - job_name: &quot;node&quot;<br>    static_configs:<br>      - targets: [&quot;host.docker.internal:9100&quot;]</pre><pre>  - job_name: &quot;cadvisor&quot;<br>    static_configs:<br>      - targets: [&quot;cadvisor:8080&quot;]</pre><pre>  - job_name: &quot;nginx&quot;<br>    static_configs:<br>      - targets: [&quot;nginx-exporter:9113&quot;]</pre><h3>🔥 Problem #1 — “localhost” Lied to Me</h3><p>I initially used:</p><pre>targets: [&quot;localhost:9100&quot;]</pre><p>It didn’t work.</p><h3>Why?</h3><p>Inside Docker:</p><blockquote><em>localhost refers to the container itself — not your host machine.</em></blockquote><p>So Prometheus was scraping… nothing useful.</p><h3>💡 Fix</h3><p>Use:</p><pre>host.docker.internal</pre><h3>🧠 Lesson</h3><blockquote><em>In containerized environments, networking assumptions break.</em></blockquote><h3>🔥 Problem #2 — SELinux Blocked Nginx</h3><p>When I exposed nginx metrics on port 8082, nginx failed to start:</p><pre>bind() failed (13: Permission denied)</pre><p>The configuration was correct.</p><p>The port was free.</p><p>So what was wrong?</p><p>👉 SELinux.</p><h3>💡 Fix</h3><pre>semanage port -a -t http_port_t -p tcp 8082</pre><h3>🧠 Lesson</h3><blockquote><em>Security layers can silently break your system.</em></blockquote><h3>🔥 Problem #3 — The “Fake Success”</h3><p>Everything seemed fine:</p><ul><li>Exporter running</li><li>Prometheus scraping</li><li>Grafana connected</li></ul><p>But nginx metrics were missing.</p><p>Instead, I saw only:</p><pre>go_memstats_alloc_bytes<br>go_gc_duration_seconds</pre><h3>What was happening?</h3><p>The exporter was alive.</p><p>But nginx wasn’t reachable.</p><p>So it exposed only its <strong>internal metrics</strong>, not nginx metrics.</p><h3>🔥 The Real Fix</h3><p>My nginx config was:</p><pre>listen 127.0.0.1:8082;</pre><p>This made it accessible <strong>only from the host</strong>, not from Docker containers.</p><h3>💡 Fix</h3><pre>server {<br>    listen 0.0.0.0:8082;</pre><pre>    location /nginx_status {<br>        stub_status;<br>        allow 127.0.0.1;<br>        allow 172.17.0.0/16;<br>        deny all;<br>    }<br>}</pre><p>Finally… Real Data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XuKxv0y_9YWc8YQK93itaw.png" /><figcaption>System metrics</figcaption></figure><h3>📊 System monitoring working</h3><p>Once Prometheus was correctly scraping Node Exporter, I started seeing real-time CPU, memory, and disk usage.</p><h3>🌐 Nginx monitoring in Grafana</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*02eiSwCYsfAuLbzagCLrsQ.png" /><figcaption>Nginx metrics</figcaption></figure><p>This dashboard shows nginx connections and traffic — finally proving that the exporter and Prometheus were correctly integrated.</p><h3>🐳 Container monitoring (cAdvisor)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bs22ZtdJQh6KZ2a8kMxnqw.png" /><figcaption>Docker metrics</figcaption></figure><p>cAdvisor provided visibility into container-level resource usage, which is essential in a Docker-based environment.</p><h3>🧠 What I Learned</h3><h3>1. Observability is about data flow</h3><p>Not dashboards.</p><p>Not tools.</p><p>But:</p><ul><li>where metrics come from</li><li>how they are exposed</li><li>how they are collected</li></ul><h3>2. Exporters are critical</h3><p>Without exporters:</p><ul><li>Prometheus has nothing to scrape</li><li>Grafana has nothing to display</li></ul><h3>3. Networking is the hidden complexity</h3><p>Most issues were not about tools — <br>they were about connectivity.</p><h3>4. Security matters</h3><p>SELinux was not a bug.</p><p>It was doing its job.</p><h3>🚀 What This Project Includes</h3><p>✔ System monitoring (Node Exporter)<br>✔ Container monitoring (cAdvisor)<br>✔ Nginx monitoring<br>✔ Real-time dashboards</p><h3>🔜 What’s Next</h3><ul><li>Add alerting (Grafana / Alertmanager)</li><li>Add logging (Loki or ELK)</li><li>Extend to Kubernetes</li></ul><h3>💬 Final Thought</h3><p>This project completely changed how I see monitoring.</p><p>It’s not about installing tools.</p><p>It’s about understanding:</p><blockquote><em>how systems communicate — and how to debug when they don’t.</em></blockquote><p>👉 Full project &amp; configs:<br><a href="https://github.com/SpaaceCadet/-Observability-Stack-Prometheus-Grafana-Nginx-Monitoring">https://github.com/SpaaceCadet/-Observability-Stack-Prometheus-Grafana-Nginx-Monitoring</a></p><p>If your dashboard ever showed nothing…</p><p>You were probably closer to understanding observability than you thought.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9aa99b234056" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a High Availability Cluster with HAProxy, Keepalived, and Docker: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@yahyasghiouri1998/building-a-high-availability-cluster-with-haproxy-keepalived-and-docker-a-step-by-step-guide-9325f4ac8aa7?source=rss-926c8b21d31f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9325f4ac8aa7</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[haproxy]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[keepalived]]></category>
            <dc:creator><![CDATA[Yahya sghiouri]]></dc:creator>
            <pubDate>Fri, 30 Aug 2024 09:44:32 GMT</pubDate>
            <atom:updated>2024-08-30T09:44:32.086Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qGOZWP0mzHb2II-vrNx7Bg.jpeg" /><figcaption>High availability</figcaption></figure><p>High availability (HA) is essential for ensuring that web applications remain accessible, even in the face of hardware or software failures. An HA architecture distributes traffic across multiple servers, preventing any single point of failure from disrupting service. In this article, we’ll explore how to build a high availability cluster using HAProxy and Keepalived, two powerful tools for load balancing and failover.</p><p>To enhance flexibility and simplify deployment, we’ll leverage Docker to containerize HAProxy, Keepalived, and our web applications. Docker allows us to create a portable and easily manageable HA setup that can be deployed across different environments, whether on-premises or in the cloud.</p><p>Throughout this guide, we’ll walk you through the entire process — from setting up Docker networks and building Dockerfiles to configuring HAProxy and Keepalived for seamless failover. By the end, you’ll have a fully functional HA cluster that ensures your web applications are always available, all within a Dockerized environment.</p><h3>I-/ General Concepts</h3><p>Before diving into the different configurations, it’s helpful to understand the core components of the architecture.</p><h4>I-1/HAproxy</h4><p><strong>HAProxy</strong>, as its name suggests, stands for High Availability Proxy. It is a robust and versatile tool designed to provide high availability and efficient load balancing for network traffic.</p><p>HAProxy is a widely used tool for distributing incoming requests across multiple backend servers to enhance both reliability and performance. It performs continuous health checks on these servers to ensure that traffic is routed only to those that are healthy and responsive.</p><p>The tool employs various algorithms, such as round-robin and least connections, to effectively balance the load. Supporting both TCP and HTTP traffic, HAProxy operates at Layer 4 (the transport layer) and Layer 7 (the application layer) of the OSI model.</p><p>There are two main components when configuring HAproxy , a frontend and a backend section.</p><ul><li><strong>Frontend section:</strong> It is the entry point for incoming client requests. It defines how HAProxy listens for incoming traffic and how it should handle these requests, here we specify the address and port on which HAProxy should listen, as well as any rules or conditions for routing the traffic to the appropriate backend by inspecting the incoming packets.</li><li><strong>Backend section: </strong>it represents the servers that will handle the requests forwarded by the frontend. we define how HAProxy should route traffic to the backend servers and how it should manage these servers basically we specify also load balancing algorithms, and health checks. In summary we control how requests will be distributed among the servers and how we are going to handle server failures or maintenance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*EiySIeb5Kzf6luig8UiIJw.png" /><figcaption>HA proxy load balancer</figcaption></figure><h4>I-2/Keepalived &amp; VRRP</h4><p><strong>VRRP (Virtual Router Redundancy Protocol)</strong> is designed to create a virtual router that represents a group of physical routers, allowing them to work together to present a single virtual IP address (VIP) to the network. This VIP is used as the default gateway by clients.</p><p>In a VRRP setup, one router is elected as the master. The master router handles traffic directed to the VIP, while the other routers in the group act as backups and monitor the master router’s health. If the master router fails, one of the backup routers takes over as the new master, ensuring the continuity of service.</p><p><strong>Keepalived</strong> is a widely used implementation of VRRP with additional features. It assigns a priority to each node in the group, and based on these priorities, it elects a new master if a failure occurs. Keepalived enhances VRRP with advanced health checks and failover capabilities, making it ideal for high-availability setups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*NUi_6mEaRaIXi64siJ2yTQ.png" /><figcaption>Virtual IP assignment</figcaption></figure><h3>II-/ Deployment architecture</h3><p>After understanding the foundational concepts of HAProxy and Keepalived, it’s crucial to see how these components come together to form a high availability cluster.</p><figure><img alt="Deployment Architecture" src="https://cdn-images-1.medium.com/max/1024/1*nSEqrpGJR60jh6Wd9d6UQw.png" /><figcaption>Deployment architecture</figcaption></figure><p>The architecture I’ve implemented leverages Docker to create a resilient and scalable environment, ensuring continuous service availability. The visual representation above illustrates how traffic is routed through HAProxy instances and managed by Keepalived to provide redundancy and failover capabilities.</p><p>To interconnect all components, I set up a Docker bridge network, which ensures seamless communication between the HAProxy instances, Keepalived, and the backend servers. This network allows the HAProxy instances to effectively distribute incoming traffic across multiple backend servers while monitoring their health and performance.</p><p>In this setup, there is a primary HAProxy instance (the master) and a secondary instance (the backup) ready to take over if the master fails. Keepalived, installed on both machines, manages the virtual IP (VIP) that clients connect to. This VIP ensures that, even in the event of a failure, traffic is automatically redirected to the backup HAProxy instance, maintaining service availability without interruption.</p><p>The backend comprises three cloned instances of a server running a simple Flask application that serves static content. This setup is an example of a stateless application deployment, where each instance operates independently without relying on session persistence or shared state. In the case of stateful applications, additional architectural considerations would be necessary, such as implementing shared storage, session replication, sticky sessions, or database clustering to ensure consistency and availability. Following best practices in system design is crucial to address these challenges and optimize the architecture based on the application’s specific requirements and context.</p><h3>III-/Step by step guide</h3><ul><li>The first thing we’re going to do is create our stateless app a simple Python application that doesn’t store any session information. To get started, we need to create a virtual environment, so make sure you have Python installed on your machine.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*6rnOOSwuJMbZj5GIzMLPNA.png" /><figcaption>Virtual environment creation</figcaption></figure><ul><li>Activate the virtual environment, and then install Flask.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*G1V6zoscdsOMLl6EO-mhQw.png" /><figcaption>Installing Flask</figcaption></figure><ul><li>Now Flask is installed in our virtual environment, we are going to create a simple Flask App with hello world!content, for me I’ll use nano editor, you can use whatever editor you want for that purpose.</li></ul><pre>nano app.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*WZlKOzXIcsWC8BSlwzMkkA.png" /><figcaption>Flask webapp</figcaption></figure><p>Copy paste the following content or create your own:</p><pre>from flask import Flask<br>app = Flask(__name__)<br><br>@app.route(&#39;/&#39;)<br>def hello_world():<br>    return &#39;Hello, World!&#39;<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=False)</pre><p>Flask apps run by default in port 5000, you can test the webapp by running: python app.py</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*LZofDS6Y0H3OKhPDGWEtYg.png" /><figcaption>Running Flask app</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*3RydS1s3SacPyZndJsdEFQ.png" /><figcaption>Accessing web app on the browser</figcaption></figure><p>The app is up and running Now we should get the dependencies used in our app, we will save them on requirements.txt .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*18q0XhVH-PcLfuj2ZrUwgw.png" /><figcaption>Saving requirements in a file</figcaption></figure><pre>pip freeze &gt; requirements.txt</pre><p>- We will need these requirements so we can create the Dockerfile of our webapp, then run the following command to create a Dockerfile of the webapp.</p><pre>nano Dockerfile.webapp</pre><p>copy and paste the following:</p><pre><br>FROM python:3.12.5<br>Expose 5000<br>ENV FLASK_app=app.py<br>WORKDIR /app<br>COPY ./app.py .<br>COPY ./requirements.txt .<br>RUN pip install -r requirements.txt<br>RUN pip install gunicorn<br>CMD gunicorn -w 4 -b :5000 app:app</pre><p>Note that we added Gunicorn in our Dockerfile to run our Python web app because using development servers is not suitable for production environments.</p><p>Let’s create our first image , it’ll be saved locally.</p><pre>docker build -f Dockerfile.webapp -t webapp_test .</pre><p>After finalizing the Dockerfile for our web app, it’s time to create our Docker Compose YAML file, which will define our entire architecture. We’ll break it down step by step.</p><p>Here is the docker compose file.</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  haproxy1:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    container_name: haproxy1<br>    networks:<br>      yahya_prive:<br>        ipv4_address: 10.0.0.150<br>    cap_add:<br>      - NET_ADMIN<br>    ports:<br>      - &quot;8888:80&quot;<br>      - &quot;8404:8404&quot;<br>    volumes:<br>      - C:\Users\John macmillan\Desktop\python_project\haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro<br>      - C:\Users\John macmillan\Desktop\python_project\keepalived_primary.conf:/etc/keepalived/keepalived.conf:ro<br>    depends_on:<br>      - web1<br>      - web2<br>      - web3<br>    entrypoint: [&quot;/bin/sh&quot;, &quot;-c&quot;, &quot;keepalived -D -f /etc/keepalived/keepalived.conf &amp;&amp; haproxy -f /usr/local/etc/haproxy/haproxy.cfg&quot;]<br><br>  haproxy2:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    container_name: haproxy2<br>    networks:<br>      yahya_prive:<br>        ipv4_address: 10.0.0.155<br>    cap_add:<br>      - NET_ADMIN<br>    ports:<br>      - &quot;8800:80&quot;<br>      - &quot;8405:8404&quot;<br>    volumes:<br>      - C:\Users\John macmillan\Desktop\python_project\haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro<br>      - C:\Users\John macmillan\Desktop\python_project\keepalived_bck.conf:/etc/keepalived/keepalived.conf:ro<br>    depends_on:<br>      - web1<br>      - web2<br>      - web3<br>    entrypoint: [&quot;/bin/sh&quot;, &quot;-c&quot;, &quot;keepalived -D -f /etc/keepalived/keepalived.conf &amp;&amp; haproxy -f /usr/local/etc/haproxy/haproxy.cfg&quot;]<br><br>  web1:<br>    image: webapp_test<br>    container_name: web1<br>    networks:<br>      - yahya_prive<br><br>  web2:<br>    image: webapp_test<br>    container_name: web2<br>    networks:<br>      - yahya_prive<br><br>  web3:<br>    image: webapp_test<br>    container_name: web3<br>    networks:<br>      - yahya_prive<br><br>networks:<br>  yahya_prive:<br>   driver: bridge<br>   #specify the driver <br>   ipam:  <br>    config : <br>       - subnet: 10.0.0.0/24<br>         gateway: 10.0.0.1</pre><p>let’s break this down:</p><p>First thing we did is to create a network bridge . This Network bridge is called yahya_privethen we specified the CIDR notation: 10.0.0.0/24with the following gateway: 10.0.0.1</p><p>it’ll be our private network in which all the containers will be assigned an ip address from the ip address range 10.0.0.0/24 .</p><pre>networks:<br>  yahya_prive:<br>   driver: bridge<br>   #specify the driver <br>   ipam:  <br>    config : <br>       - subnet: 10.0.0.0/24<br>         gateway: 10.0.0.1</pre><p>It’s advisable to use a custom network rather than the default network provided by Docker Compose. This approach enhances security and allows you to use domain names instead of IP addresses in configurations.</p><p>Then there is a section for our webapps, they’re called respectively: web1, web2 and web3, all three of them is now attached to yahya_privenetwork.</p><p>Each one was provided a name, and the base image was created previously, and it was saved locally which is webapp_test</p><pre>web1:<br>    image: webapp_test<br>    container_name: web1<br>    networks:<br>      - yahya_prive<br><br>  web2:<br>    image: webapp_test<br>    container_name: web2<br>    networks:<br>      - yahya_prive<br><br>  web3:<br>    image: webapp_test<br>    container_name: web3<br>    networks:<br>      - yahya_prive</pre><p>After this we’ve created the service for our HAProxy load balancer.</p><pre>haproxy1:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    container_name: haproxy1<br>    networks:<br>      yahya_prive:<br>        ipv4_address: 10.0.0.150<br>    cap_add:<br>      - NET_ADMIN<br>    ports:<br>      - &quot;8888:80&quot;<br>      - &quot;8404:8404&quot;<br>    volumes:<br>      - C:\Users\John macmillan\Desktop\python_project\haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro<br>      - C:\Users\John macmillan\Desktop\python_project\keepalived_primary.conf:/etc/keepalived/keepalived.conf:ro<br>    depends_on:<br>      - web1<br>      - web2<br>      - web3<br>    entrypoint: [&quot;/bin/sh&quot;, &quot;-c&quot;, &quot;keepalived -D -f /etc/keepalived/keepalived.conf &amp;&amp; haproxy -f /usr/local/etc/haproxy/haproxy.cfg&quot;]</pre><p>The Master HAProxy is called haproxy1, and it was assigned the ip address:</p><p>10.0.0.150from the private network yahya_prive.</p><p>To enable Keepalived, which uses VRRP for failover, the container requires additional network capabilities. Therefore, we grant the container NET_ADMIN privileges, allowing it to manage network settings necessary for VRRP operations.</p><p>The necessary configuration files for HAProxy and Keepalived are mounted as read-only volumes from the host machine to ensure that both services are properly configured.</p><p>The entrypoint directive ensures that Keepalived starts in the background and monitors the HAProxy service, providing the high availability setup.</p><p>And obviously, there is the configuration Dockerfile that contains our Keepalived and HAProxy.</p><pre>FROM ubuntu:22.04<br><br># Install Keepalived and HAProxy<br>RUN apt-get update &amp;&amp; apt-get install -y \<br>    nano \<br> net-tools \<br>    keepalived \<br>    haproxy<br> <br>EXPOSE 80<br>EXPOSE 8444<br></pre><p>The configuration for both load balancers is exactly the same (haproxy.cfg)</p><pre>global<br>  stats socket /var/run/api.sock user haproxy group haproxy mode 660 level admin expose-fd listeners<br>  log stdout format raw local0 info<br><br>defaults<br>  mode http<br>  timeout client 10s<br>  timeout connect 5s<br>  timeout server 10s<br>  timeout http-request 10s<br>  log global<br><br>frontend stats<br>  bind *:8404<br>  stats enable<br>  stats uri /<br>  stats refresh 10s<br><br>frontend myfrontend<br>  bind :80<br>  default_backend webservers<br><br>backend webservers<br>server s1 web1:5000 check<br>server s2 web2:5000 check<br>server s3 web3:5000 check</pre><p>What we’ve done here is configure our load balancer to listen for requests on port 80. We’ve also defined our web servers in the backend webservers section, allowing us to route traffic to them effectively.</p><p>On the other hand, we had different configurations of Keepalived daemons for both nodes.</p><p>here is the configuration for the master node (keepalived_primary.conf):</p><pre>vrrp_instance VI_1 {<br>    state MASTER<br>    interface eth0<br>    virtual_router_id 33<br>    priority 255<br>    advert_int 1<br>    unicast_src_ip 10.0.0.50<br>    <br>    authentication {<br>        auth_type PASS<br>        auth_pass letmein<br>    }<br>    <br>    virtual_ipaddress {<br>        10.0.0.50/24 dev eth0<br>    }  <br>}</pre><p>This is a basic configuration where we’ve assigned a priority of 255, which is higher than the priority set on the backup machine. As a result, this machine will be assigned the virtual IP address first. We’ve defined the state as MASTER for this machine and specified eth0 as the interface, as it’s connected to the private network through this interface.</p><p>The most critical part of this configuration is the virtual_ipaddress section, where we define the virtual IP address (10.0.0.50/24) that will be managed by the VRRP protocol. This IP address will be assigned to the master machine, ensuring that it handles traffic as long as it remains in the master state. The authentication section provides basic security by requiring a password for VRRP communications, adding an extra layer of protection to the setup.</p><p>The configuration for the backup node will be different a little bit (keepalived_bck.conf):</p><pre>vrrp_instance VI_1 {<br>    state BACKUP<br>    interface eth0<br>    virtual_router_id 33<br>    priority 150<br>    advert_int 1<br>    unicast_src_ip 10.0.0.50<br>    <br>    authentication {<br>        auth_type PASS<br>        auth_pass letmein<br>    }<br>    <br>    virtual_ipaddress {<br>        10.0.0.50/24 dev eth0<br>    }  <br>}</pre><p>We’ve set a priority of 150, which is lower than that of the master, and designated the state as BACKUP. Both the master and backup nodes share the same virtual IP address (VIP). In the event of the master node failing, the backup node will detect this through ARP checks and automatically take over the VIP, ensuring continued service availability.</p><p>Note that the Docker Compose file includes a depends_on section that specifies the order in which containers are started. In this case:</p><pre>depends_on:<br>      - web1<br>      - web2<br>      - web3</pre><p>This configuration ensures that the web applications (web1, web2, and web3) start before the load balancers are initialized. This order is crucial to ensure that the web servers are up and running before the load balancers begin routing traffic to them.</p><p>After completing the necessary configurations, you can run the entire setup with the following command:</p><pre>docker-compose -p high_availability_cluster up -d</pre><p>Now, your setup is up and running.</p><figure><img alt="Accessing webapp" src="https://cdn-images-1.medium.com/max/1024/1*aTZ2S3WfdfYJcsNjnjSpsg.png" /><figcaption>Accessing webapp</figcaption></figure><p>The haproxy1 container will receive the virtual IP address on its eth0 interface. You can verify this by running the following command inside the container: ip a.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*L_B3ZgQXT-ikW5_RaSxzyA.png" /><figcaption>Virtual Ip address assigned</figcaption></figure><p>We can try sending an HTTP request using the curl command from a node inside the yahya_prive network. For example, we can use web1 for this purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*IyOws179aa5Hu5lS8D_DOA.png" /><figcaption>Getting web content from using VIP</figcaption></figure><h3>IV-/Conclusion</h3><p>In conclusion, building a high availability cluster with HAProxy, Keepalived, and Docker is an effective way to ensure continuous service availability and reliability. Through this guide, we’ve explored the fundamental concepts of high availability, examined how HAProxy and Keepalived work together to manage traffic and failover, and demonstrated how to set up this architecture in a Docker environment. By following these steps, you can create a resilient infrastructure that can handle disruptions and maintain service continuity, making it an essential setup for any robust and scalable application deployment.</p><p><strong>Equipped with this understanding, you’ll now be able to enhance your network infrastructure and deploy more resilient, scalable applications with confidence.</strong></p><p><strong>We invite you to share your experiences and insights in the comments below. We’re eager to hear your feedback and thoughts. Happy networking!</strong></p><p><strong>References</strong></p><p>For more detailed information :</p><ol><li><a href="https://docs.docker.com/reference/compose-file/networks/">Networks top-level elements | Docker Docs</a></li><li><a href="https://docs.haproxy.org/2.9/intro.html">HAProxy version 2.9.9–41 — Starter Guide</a></li><li><a href="https://community.fs.com/article/understanding-virtual-router-redundancy-protocol-vrrp.html">Understanding Virtual Router Redundancy Protocol (VRRP) | FS Community</a></li><li><a href="https://www.redhat.com/sysadmin/keepalived-basics">Setting up a Linux cluster with Keepalived: Basic configuration | Enable Sysadmin (redhat.com)</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9325f4ac8aa7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering IP Masquerading on Red Hat-Based Systems: A Comprehensive Guide to Enhancing Network…]]></title>
            <link>https://medium.com/@yahyasghiouri1998/mastering-ip-masquerading-on-red-hat-based-systems-a-comprehensive-guide-to-enhancing-network-7e9c12536e11?source=rss-926c8b21d31f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e9c12536e11</guid>
            <category><![CDATA[redhat-linux]]></category>
            <category><![CDATA[network-administration]]></category>
            <category><![CDATA[network-security]]></category>
            <category><![CDATA[firewalld]]></category>
            <category><![CDATA[firewall]]></category>
            <dc:creator><![CDATA[Yahya sghiouri]]></dc:creator>
            <pubDate>Sat, 17 Aug 2024 07:07:27 GMT</pubDate>
            <atom:updated>2024-08-17T07:07:27.483Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering IP Masquerading on Red Hat-Based Systems: A Comprehensive Guide to Enhancing Network Privacy and Control</h3><figure><img alt="masquerading" src="https://cdn-images-1.medium.com/max/1024/1*TYaTDwBoeDMniR2lUPX2-w.png" /><figcaption>Masquerading</figcaption></figure><p>In today’s interconnected world, managing network traffic and maintaining security are more crucial than ever. Whether you’re running a small business network or managing a complex system of virtual machines, understanding how to control and mask IP addresses can significantly enhance both privacy and efficiency. One powerful tool at your disposal is IP masquerading, a technique that allows you to disguise the internal IP addresses of devices behind a single, external IP address.</p><p>In this article, we dive into the world of IP masquerading on RHEL based systems, a popular and robust Linux distribution. Through a practical project involving virtual machines (VMs), we’ll explore how to set up IP masquerading, its benefits, and the impact it can have on your network management. Whether you’re a network administrator looking to streamline operations or a Linux enthusiast keen on expanding your skill set, this guide will provide you with the knowledge and hands-on experience needed to leverage IP masquerading effectively. Join us as we unravel the steps to secure and optimize your network with this essential technique.</p><h3>I-/What’s IP Masquerading ?</h3><p><strong>IP masquerading</strong> is a network technique where a single device, often referred to as a gateway or router, manages traffic for multiple devices on a local network. This gateway acts as an intermediary between the internal network and the broader internet.</p><p>IP masquerading is often referred to as <strong>Source NAT (SNAT).</strong></p><p>When devices on the internal network send data packets to the internet, the gateway replaces the source IP address of each packet with its own public IP address.</p><p>This process effectively masks the internal IP addresses of the devices, making all external communications appear as though they originate from the gateway itself. IP masquerading not only helps in conserving IP addresses but also enhances security by concealing the internal network structure from external observers.</p><figure><img alt="Source network address translation" src="https://cdn-images-1.medium.com/max/1024/1*Npq4v6TQMvo6J2kCPnpgKg.png" /><figcaption>Source network address translation</figcaption></figure><p>In this article, we will delve into a hands-on demonstration of configuring IP masquerading in a Red Hat-based Linux environment. We will explore each step of the setup process, providing practical insights and tips to help you effectively manage network traffic and enhance security.</p><h3>II-/Setting up the environment</h3><figure><img alt="Network Architecture of the IP Masquerading Setup" src="https://cdn-images-1.medium.com/max/1024/1*LmjWgHsoceVGZ-4HhmWwTw.png" /><figcaption>Network Architecture of the IP Masquerading Setup</figcaption></figure><p>This image details the configuration of virtual machines, highlighting the NAT router and the flow of traffic between internal and external networks.</p><p>IP masquerading is effectively implemented through the configuration of firewall zones within the network architecture. To achieve this, we will partition our network into distinct zones, each identified by static IP addresses. These zones are managed by firewall rules tailored to control the flow of traffic between them.</p><ol><li><strong>Network Segmentation</strong>: The network is divided into multiple zones, each serving a specific function or role. This segmentation helps in organizing and managing network resources more efficiently.</li><li><strong>Static IP Address Assignment</strong>: Each zone is assigned a static IP address, which ensures consistent and predictable addressing within the network. This facilitates easier management and troubleshooting of network communications.</li><li><strong>Firewall Zones and Rules</strong>: Different firewall zones are established to regulate traffic between the segments. The firewall rules applied to these zones govern both inbound and outbound traffic.</li></ol><p>Based on the previous explanation, we have three machines in the setup:</p><ul><li>Machines A and B will be placed in a private zone that is isolated from external networks. These two machines will communicate with each other, each equipped with two network interfaces: one connected to the private zone and the other to the internal network. The internal interface allows them to reach the gateway or NAT device, which is Machine C.</li><li>Machine C will handle network address translation (NAT) tasks. It has two network interfaces: one connected to the external (public) network and the other to the internal network. The internal interface enables communication with Machines A and B in the private zone, allowing Machine C to perform NAT functions.</li></ul><blockquote>Note that each network interface is assigned to a specific zone, and appropriate firewall rules are configured accordingly. For a practical understanding of zone configuration in a Linux environment, I recommend the book <em>Linux Cookbook</em> by Carla Schroder.</blockquote><h3>III-/From Theory to Practice: Configuring IP Masquerading in Your Linux Environment</h3><ol><li><strong>Create the Machines</strong></li></ol><ul><li>Set up three separate virtual machines (VMs) for the environment. In this setup, we will use CentOS as our operating system, which is a Red Hat-based distribution.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*fm5QA3JjrhMqvzKW9EVUXw.png" /></figure><p><strong>2. Establish a private network between machine A and B</strong></p><ul><li>The machines created do not have any network interfaces configured yet; they currently only have the loopback address interface. Our task now is to set up a network so that the two machines can communicate with each other.</li></ul><figure><img alt="loopback address" src="https://cdn-images-1.medium.com/max/958/1*O7LEOXxHLEotelnk_8xTaQ.png" /><figcaption>Network configuration(loopback address)</figcaption></figure><ul><li>The first step is to create a private virtual network with the subnet 192.168.224.0/24. We have disabled DHCP settings on this network to assign static IP addresses to the machines, ensuring that these addresses remain consistent over time.</li></ul><figure><img alt="Private network 192.168.224.0/24" src="https://cdn-images-1.medium.com/max/700/1*dVGddRYNF-5BUyhB0L-h2g.png" /><figcaption>Private network 192.168.224.0/24</figcaption></figure><ul><li><strong>Connect VMs A and B to the Network</strong>: Next, connect VM A and VM B to the private network and assign them IP addresses. You can achieve this using either the <strong>nmtui</strong> utility or by configuring network scripts directly.</li><li>we will be using <strong>nmtui</strong>utility which is the simplest method which provides an easy-to-use text-based interface for network configuration.</li></ul><figure><img alt="Adding Network adapters for internal network" src="https://cdn-images-1.medium.com/max/891/1*jSTyVLGHQRNDxg5CnHtqNQ.png" /><figcaption>Adding Network adapters for internal network</figcaption></figure><ul><li><strong>Add Network Adapters</strong>: We added a network adapter (VMnet10, Host-only) to both Machine A and Machine B.</li><li><strong>Start and Configure the Machines</strong>: Next, start both machines and configure their network settings.</li><li><strong>Machine A</strong>: Assign the following network address to Machine A: 192.168.224.5.</li><li><strong>Machine B</strong>: Assign the following network address to Machine B: 192.168.224.6.</li><li>Using The command nmtui you’ll access a simple graphical interface that facilitates the necessary network configurations. Here is the private network config of Machine A .</li></ul><figure><img alt="nmtui UI utility for machine A" src="https://cdn-images-1.medium.com/max/802/1*-2BU2V8tm73_x5hydZJ3-Q.png" /><figcaption>nmtui UI utility for machine A</figcaption></figure><p>We set the IPv4 configuration to ‘Manual’ and assigned the desired IP address to Machine A. The same process was followed for Machine B,Now we are able to ping the two machines with each other.</p><figure><img alt="Ping from machine 192.168.224.6 to 192.168.224.5" src="https://cdn-images-1.medium.com/max/591/1*a0__hZsL7lngAxmj3239BQ.png" /><figcaption>Ping from machine 192.168.224.6 to 192.168.224.5</figcaption></figure><p>As you can see the ping is succesful .</p><p><strong>3. Configure Firewall Rules for machine A and B</strong></p><p>After configuring the private network, the next question is: What will be the default zone assigned to our network interface? Is this zone suitable for our setup?</p><blockquote>Note that Red Hat-based systems manage their firewall rules using firewalld, not ufw.</blockquote><p>As a best practice for an internal network, it is advisable to use the ‘block’ or ‘drop’ zone. This approach helps ensure that any added network interface is not exposed to the internet, which is considered an untrusted network,we’ll use the following command on both machines.</p><p>sudo firewall-cmd --set-default-zone=block</p><p>The changes must take effect immediately.</p><figure><img alt="Setting default firewall zone" src="https://cdn-images-1.medium.com/max/1024/1*ZBNiOVkq9v_xODGTN6pVHg.png" /><figcaption>Setting default firewall zone</figcaption></figure><p>With the ‘block’ or ‘drop’ zone applied, any interaction between the two machines will be prohibited. Basic requests, such as ping requests, will be blocked by default, as this zone blocks all incoming traffic to the machines.</p><figure><img alt="ping request failure" src="https://cdn-images-1.medium.com/max/637/1*yIpc_bxK6zKH1bHAgiQaCA.png" /><figcaption>Ping request failure</figcaption></figure><p>So now any added network interface will be assigned to the block zone by default. Given that Machines A and B trust each other, we can assign them to the ‘public’ or ‘internal’ zone without any issues.</p><p>sudo firewall-cmd --add-interface=ens35 --zone=public --permanent</p><figure><img alt="public zone for machine A" src="https://cdn-images-1.medium.com/max/716/1*H5fR-57LcRkvVppg-G8CVg.png" /><figcaption>Public zone for machine A</figcaption></figure><p>We made changes immediately by adding — permanent flag, and you should consider using the right network interface for me it was ens35.</p><p>The same process was done to machine B.</p><p>Let’s consider a scenario where we install a PostgreSQL database on Machine B and want to make it accessible from Machine A. In this setup, we will install the PostgreSQL server on Machine B and the PostgreSQL client on Machine A.</p><p>For detailed instructions on how to install PostgreSQL, please refer to the official PostgreSQL documentation.</p><p><a href="https://www.postgresql.org/download/linux/redhat/">PostgreSQL: Linux downloads (Red Hat family)</a></p><p>After doing the necessary installation we should do the following:</p><p><strong>1/Enable Remote Access</strong>: It is mandatory to enable remote access at the database level by editing two configuration files: pg_hba.conf and postgresql.conf. We will not delve into the details of these configurations here.</p><p><strong>2/ Configure Firewall on Machine B</strong>: On Machine B, add the PostgreSQL service to the public zone to allow communication with Machine A. This configuration will enable TCP port 5432, allowing remote access to the PostgreSQL service.</p><p>sudo firewall-cmd --add-service=postgresql --zone=public --permanent</p><figure><img alt="adding PostgreSQL service to firewall rules" src="https://cdn-images-1.medium.com/max/801/1*aZ0XttS8kyq_vP1fdw3SSA.png" /><figcaption>Adding PostgreSQL service to firewall rules</figcaption></figure><blockquote>It’s practical to manage Firewall rules through services rather than managing them using individual ports</blockquote><p>After doing this we will be able to access the database remotely from machine A or any machine from the private zone.</p><p>psql -h 192.168.224.6 -U alfresco -d alfresco</p><figure><img alt="Access database remotely" src="https://cdn-images-1.medium.com/max/802/1*FTWCzO5tYnDWo-ZrEoNW_Q.png" /><figcaption>Accessing Database remotely</figcaption></figure><blockquote>Note that we have created a user with their own database. This is a good practice because it limits remote access to specific users and their associated databases, enhancing security.</blockquote><p><strong>4. Set Up Machine C as a gateway</strong></p><p>After configuring the internal network, it’s time to set up external access to the network, we will add an additional network interface to connect machines A and B with C.</p><p>The challenge lies in configuring firewall zones, such as those from the internal network to C, and from C to the external network.</p><p>Now what we’re going to do is to create an internal network that connects machine A and B and C, so they can ping each other first.</p><figure><img alt="Adding Network adapters for network translation task" src="https://cdn-images-1.medium.com/max/700/1*YDhUqLJdTJiBuNQsfIZMkA.png" /><figcaption>Adding Network adapters for network translation task</figcaption></figure><p>As usual, we will add the internal network VMnet13 to machines A and B so that they can ping machine C.</p><ul><li>The internal network has the following subnet: 192.168.214.0/24.</li><li>We will assign machine C the address: 192.168.214.1.</li><li>Machine A will have the address: 192.168.214.2.</li><li>Machine B will have the address: 192.168.214.3.</li><li>We will configure these static IP addresses using the nmtui utility, as before.</li></ul><p>Now, we need to configure firewall rules for communication between the machines in the internal network and the gateway.</p><p>For machine A and B we should modify the zone associated with the new added interface. and set it to <strong>internal.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*IFfjqbCRdt-tzLyi72nT0g.png" /></figure><p>Another important aspect to consider is the management of unnecessary services:</p><ul><li>It’s good practice to configure the firewall to only allow the services that are needed. This approach reduces the attack surface and enhances system security.</li><li>For example, we can disable services such as Samba, DHCP, and SSH in the firewall if they are not required for this operation.</li></ul><p>we can list firewall rules for a specific zone using the following command: sudo firewall-cmd --zone=internal --list-all</p><figure><img alt="listing details about the internal zone" src="https://cdn-images-1.medium.com/max/636/1*1Shy0CAu-WcqG1sSW8AHDQ.png" /><figcaption>Listing details about the internal zone</figcaption></figure><p>We will remove unnecessary services such as SSH, DHCP, and Samba client from the internal network.</p><pre>sudo firewall-cmd --remove-service=ssh --zone=internal --permanent<br>sudo firewall-cmd --remove-service=dhcp --zone=internal --permanent<br>sudo firewall-cmd --remove-service=dhcpv6-client --zone=internal --permanent<br>sudo firewall-cmd --remove-service=samba-client --zone=internal --permanent<br>sudo firewall-cmd --reload</pre><figure><img alt="Removing unnecessary services from the firewall" src="https://cdn-images-1.medium.com/max/804/1*0K2gA-xl4v_d1i9su-Mvzg.png" /><figcaption>Removing unnecessary services from the internal zone</figcaption></figure><p>The same process should be applied to machine B.</p><p>Before configuring IP masquerading, we need to expose the gateway to external networks. To achieve this, we will add another network adapter and use a bridged adapter for this purpose.</p><figure><img alt="Adding bridged adapter to the gateway" src="https://cdn-images-1.medium.com/max/883/1*WWh4YaZvSwryfKZsRg4A1g.png" /><figcaption>Adding bridged adapter ro the gateway</figcaption></figure><p>The machine C will obtain an Ip address, that can access external networks.</p><p>The Machine C now have the following config:</p><ul><li>use the ifconfigcommand</li></ul><figure><img alt="Network configuration of the Gateway" src="https://cdn-images-1.medium.com/max/802/1*ncl3XP43GMUHYGAY7ZSJ3A.png" /><figcaption>Network configuration of the Gateway</figcaption></figure><p>We need to enable IP forwarding on this machine. To give you an idea, IP forwarding (or routing) allows a device, such as a router or gateway, to pass network packets from one network interface to another.</p><p>we should modify the file sysctl.conf .</p><p>sudo nano /etc/sysctl.conf</p><p>And then define the following variable: <em>`net.ipv4.ip_forward = 1`</em></p><p>After setting this, we need to: enable IP Masquerading on the machine, configure Routing Rules as required and define the Zone associated with this machine for proper firewall configuration.</p><p><strong><em>Configuring zone for machine C :</em></strong></p><p>The default zone of machine C is configured as public. We need to change the zones associated with the network interfaces to meet our requirements.</p><pre>sudo firewall-cmd --zone=external --add-interface=ens36 --permanent<br>sudo firewall-cmd --zone=internal --add-interface=ens35 --permanent<br>sudo firewall-cmd --reload</pre><p>And also we need to add masquerading to our machine in order to perform address translation.</p><pre>sudo firewall-cmd --zone=external --add-masquerade --permanent<br>sudo firewall-cmd --reload</pre><p><strong><em>Add forwarding rules to the machine</em></strong></p><pre>sudo firewall-cmd --direct --add-rule ipv4 nat POSTROUTING 0 -o ens36 -j MASQUERADE<br><br>sudo firewall-cmd --direct --add-rule ipv4 filter FORWARD 0 -i ens35 -o ens36 -j ACCEPT<br><br>sudo firewall-cmd --direct --add-rule ipv4 filter FORWARD 0 -i ens36 -o ens35 -m state --state RELATED,ESTABLISHED -j ACCEPT</pre><p>- These commands are used to set up a Linux machine as a router that forwards traffic between two network interfaces (`ens35` and `ens36`).</p><ul><li>1. <strong>First Command</strong> : Sets up NAT on the output interface `ens36` so that all outgoing packets have their source IP address changed to the IP address of `ens36`. This is necessary for routing internet traffic from one network to another.</li><li>2. <strong>Second Command</strong>: Allows packets to be forwarded from `ens35` to `ens36`.</li><li>3. <strong>Third Command</strong>: Allows packets that are part of an established connection or are related to an existing connection to be forwarded from `ens36` to `ens35`.</li></ul><p>This will allow us to provide internet access to a network behind the `ens35` interface by routing traffic through the `ens36` interface, which is connected to the internet.</p><p>in the end we need to configure the default gateway for machine A and B to so they can reach the public internet.</p><p><strong><em>Configuring default gateway for machine A and B</em></strong></p><p>We need to configure the default gateway in machine A and B to: 192.168.214.1</p><p>using the following command:</p><pre>ip route add default via 192.168.214.1</pre><p>we can see available routes using the following command:</p><p>ip route</p><figure><img alt="Listing default routes" src="https://cdn-images-1.medium.com/max/673/1*nfUsMMtXTztleSD2v-Y9dQ.png" /><figcaption>Listing default routes</figcaption></figure><p>Now we will be able to reach the internet.</p><figure><img alt="pinging google.cm from machine A" src="https://cdn-images-1.medium.com/max/833/1*xQ9uQndrMPCCcLMBJXyFMA.png" /><figcaption>pinging google.cm from machine A</figcaption></figure><p>The traceroute command is used to trace the path that packets take from your computer to a destination host across a network. It provides information about each hop (router or gateway) that the packets pass through, as well as the time taken to reach each hop.</p><h3>IV- Conclusion</h3><p>In this article, we explored IP masquerading, its benefits for network address translation, and its role in enhancing security and efficiency. We proposed an architecture using interconnected VMs with virtualized networks to implement network translation tasks effectively. By outlining best practices for configuring firewall rules and zones on Red Hat-based systems, and including a practical exercise with configurations and screenshots, we demonstrated how to manage and secure network environments efficiently. This approach helps optimize network performance and safeguard against potential threats.</p><p><strong>Equipped with this understanding, you’ll be able now to enhance your network configurations and optimize your NAT setups!</strong></p><p><strong>We invite you to share your experiences and insights in the comments below.</strong></p><p><strong>We’re eager to hear your feedback and thoughts. Happy networking!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e9c12536e11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FBprophet forecasting with Anomalies detection]]></title>
            <link>https://medium.com/@yahyasghiouri1998/fbprophet-forecasting-with-anomalies-detection-6a1a94752b2a?source=rss-926c8b21d31f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a1a94752b2a</guid>
            <category><![CDATA[isolation-forests]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[seasonality]]></category>
            <category><![CDATA[fbprophet]]></category>
            <category><![CDATA[anomaly-detection]]></category>
            <dc:creator><![CDATA[Yahya sghiouri]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 19:16:53 GMT</pubDate>
            <atom:updated>2023-10-05T19:16:53.031Z</atom:updated>
            <content:encoded><![CDATA[<h3>FBprophet forecasting with anomalies detection</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pvi7T1g6v4fTfLPv3zIKwg.jpeg" /></figure><p>Time series forecasting is like peering into a crystal ball, attempting to unveil future trends and patterns through the lens of historical data. In today’s data-centric world, the ability to anticipate future developments is a crucial skill. Time series data, which unfolds in a chronological sequence and is influenced by time intervals, holds immense importance across various domains — be it predicting stock prices, analyzing temperature fluctuations, forecasting sales trends, or understanding website traffic patterns.</p><p>Analyzing historical data allows us to discver hidden patterns, trends, and behaviors that can be valuable for making informed predictions about what lies ahead. Time series forecasting involves employing a combination of statistical and machine learning techniques, an interplay between mathematical algorithms and domain expertise. It’s a nuanced blend of analytical science and contextual understanding that provides profound insights, empowering precise decision-making and strategic planning.</p><p>In this article, we embark on a journey through the realm of time series forecasting, with a specific focus on Facebook Prophet — a remarkable open-source forecasting tool developed by Facebook’s Data Science team. Our aim is to unravel its intricate capabilities, understand how to wield it effectively, and present a tangible real-world project as an illustration. This project will showcase how Facebook Prophet has played a pivotal role in rendering precise predictions, ultimately revolutionizing the decision-making landscape. Join us in this exploration as we decode the captivating intricacies of time series forecasting and its vital applications in this era dominated by data.</p><h3>I-Overview of Facebook Prophet</h3><p>Prophet was specifically crafted to handle business forecasting tasks effectively, particularly those with the following characteristics:</p><ul><li>Time series data captured at different levels (hourly, daily, or weekly), ideally spanning at least a year of historical data .</li><li>Pronounced seasonality effects occurring daily, weekly, and/or yearly .</li><li>Irregular occurrences of holidays and unique events that do not follow typical seasonality patterns .</li><li>Presence of missing data points and outliers .</li><li>Significant shifts in trends, often coinciding with the introduction of new features or products .</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*MLaaNg94Fb2n2_7aqgofwQ.png" /><figcaption>Seasonal data with exponential trend</figcaption></figure><p>Prophet operates as an additive regression model, meaning it combines several (optional) components, including:</p><ul><li>A linear or logistic growth trend curve .</li><li>Annual ,Weekly and daily seasonality curves .</li><li>Holidays and other special events .</li><li>Additional user-defined seasonality curves, such as hourly or quarterly patterns .</li></ul><p>This can be summarized in the following formula :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*pTFjOhW41b46axvmdjccHA.png" /><figcaption>General Forecasting formula of Fbprophet</figcaption></figure><p>Prophet optimizes its parameters using the Pystan package, which is employed for Bayesian inference. Essentially, it assumes prior distributions about parameters related to the trend, seasonal components, the noise, etc. This assumption is essential, as in any process involving Bayesian inference, prior knowledge about what we aim to model is necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*vNTUNq4k5hwXJmW1ZhTOUg.png" /><figcaption>Process of parameters estimation</figcaption></figure><p>It achieves consistently better results comparable to more intricate forecasting techniques but with significantly reduced complexity. It caters to a wide range of users so beginners can quickly build highly accurate models with just a few lines of code, without delving into the inner workings, while experts can delve deep, adding more features and fine-tuning hyperparameters to attain incremental performance improvements.</p><h3>II- Fourier transforms and seasonal components</h3><p>Time series data can be understood as a collection of signal frequencies with varying amplitudes, phases, and frequencies contributing to the main signal. We can decompose them using a Fourier transformation to study the characteristics of this signal.</p><p>The next image provides an intuitive representation of this decomposition :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*vx3z8vxd8VVdKcSlbziL1A.png" /><figcaption>Signal Decomposition</figcaption></figure><p>The red signal is decomposed to many sub signals with different amplitudes and frequencies .</p><blockquote>What is the main concept behind this decomposition ?</blockquote><ul><li>The Fourier transform in time series problems can be considered a smoothing technique. It smooths out the signal into different components, revealing the underlying structure and patterns within the data. This process is similar to how other smoothing techniques aim to extract essential information from noisy or complex data by reducing noise or irrelevant details. The common base concept among these techniques is <strong>convolutions</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*O5X0XsnSgwtKn9l7Im70Sw.png" /><figcaption>Smoothing using weighted moving average</figcaption></figure><ul><li>For example, when using moving average smoothing across various time periods, you’re essentially employing convolutions. This is why Convolutional Neural Networks (CNNs), for instance, are utilized in combination with other neural networks like LSTMs, resulting in a hybrid model. The objective is to capture significant patterns in the data using kernels of varying sizes .</li></ul><blockquote>Relationship of Fourier transforms with FBprophet ?</blockquote><p>Seasonality lies at the core of how Prophet operates. This is the reason why Prophet excels in handling time series data with strong seasonal components.</p><p>Prophet utilizes Fourier transforms to break down the time series into several sine waves, each with distinct phases, periods, and amplitudes. These sine waves form the fundamental components of the signal. A Fourier order of 4 implies decomposing the signal into four sine waves.</p><p>By default, Prophet fits yearly seasonality if present, employing an order of 10, and weekly seasonality using an order of 3. Additionally, it considers daily seasonality (or sub-daily for relevant data) with an order of 4. Generally, these default orders work effectively, but they can be adjusted based on the specific case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*K3ZGo2zRPTJPAlUstCYQtQ.png" /><figcaption>Time series decomposition</figcaption></figure><p>The last plot represents the individual estimated components of the forecast: trend, seasonality, and holidays. It offers a clear and intuitive visualization of how each component contributes to the overall forecast .</p><p>The yearly plot appears quite wavy, indicating the utilization of a higher Fourier order for the yearly seasonality. However, this situation may lead to overfitting. To mitigate this risk, we should consider lowering the Fourier order, preventing the model from capturing excessive noise over the general pattern.</p><p>These orders can be adjusted during the instantiation of the Prophet object. Our objective is to find a model with appropriate Fourier orders that effectively capture the essential characteristics of our data while avoiding overfitting.</p><p>Now that we’ve introduced the basic concepts of FBProphet, let’s delve into a practical example: creating a time series model using FBProphet on the NYC taxi passenger dataset, which can be found <a href="https://github.com/numenta/NAB/tree/master/data/realKnownCause">here</a>.</p><p><a href="https://github.com/SpaaceCadet/FBprophet_seasonal_time_series">Source code link</a></p><h3>III- Understanding seasonalities in the data</h3><p>In any data science project it’s important to examine and understand the characteristics, patterns of the data ,so it’s a critical and foundational step before modeling .</p><p>In our case we tried to catch the seasonality in different levels of granularities , such as weekly , and monthly seasonalities using aggregations and unstacked plots .</p><p>The data ranges from “2014–07–01” to “2015–01–31” ,Observations are recorded every 30 min , so to simplify our exploration and modeling we reduced the frequency to hourly one using the mean for aggregation .</p><pre><br>df = df.set_index(&quot;timestamp&quot;).resample(&quot;H&quot;).mean().reset_index()<br></pre><p>Resampled dataframe</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*6pBuJWC1Ey4xnckA8HmQew.png" /><figcaption>Resampled dataframe</figcaption></figure><p>Now, we’re ready to visualize our data. In my opinion, one of the best ways to start and gain a general understanding of the time series data is by using a line plot with a range slider. It allows us to view data in different time periods without overwhelming visuals. For this purpose, we’ll be utilizing Plotly.</p><pre>fig = px.line(df, x=&quot;timestamp&quot; , y =&quot;value&quot; , title = &quot;New york taxi passengers serie&quot;)<br><br>fig.update_xaxes(rangeslider_visible=True)<br>fig.update_layout(height=600, width=1000)<br>fig.show()</pre><p>This is one of the snapshots after zooming on the plot .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*roKA_niBGnV6AVMBSTgTpA.png" /><figcaption>zoomed plot</figcaption></figure><p>We’ve come to a few key conclusions:</p><ul><li>The data exhibits strong seasonal components, notably a daily seasonality.</li><li>Anomalies, indicated by outliers, are present in the dataset. For instance, an uncommon peak can be observed on November 2.</li><li>The time series appears to follow an additive pattern rather than a multiplicative one. This is evident as the magnitude of each season is not proportional to the trend.</li><li>Although there is no strong trend component, the data does display a pronounced seasonal effect.</li></ul><p>Here’s a helpful tip: when dealing with count data in a time series, a multiplicative model is often more suitable.</p><p>To grasp the overall behavior of our data across various time periods, we augmented the dataset by adding new columns related to the datetime object in Pandas. This enhancement enabled us to generate plots illustrating aggregated data.</p><pre>df[&quot;hour&quot;] = df.timestamp.dt.hour<br><br>df[&quot;month&quot;]  = df[&quot;timestamp&quot;].dt.month<br><br>df[&quot;weekday&quot;]  = pd.Categorical(df.timestamp.dt.strftime(&quot;%A&quot;) , categories = [&quot;Monday&quot; ,&quot;Tuesday&quot;,&quot;Wednesday&quot;,&quot;Thursday&quot;,&quot;Friday&quot;,&quot;Saturday&quot;,&quot;Sunday&quot;]</pre><h4>III-1/Hourly Unstacked plot</h4><pre>df.groupby([&quot;hour&quot;,&quot;weekday&quot;]).mean()[&quot;value&quot;].unstack().plot();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*StQyamxirOMKxRi1EDjG4w.png" /><figcaption>Unstacked plot</figcaption></figure><ul><li>On average the taxi demands are the lowest in 5 AM or mornings in general , and highest in 7 pm . this is because most people finish their work around 7 pm or 6 pm , so taxi demands are highest in these times</li><li>The saturday and sunday have different behaviours than normal days , and they exhibit similar pattern in some way .this not our worry right now , this can be diagnosed in further analysis , to improve our forecast .</li></ul><h4>III-2/ Daily aggregated plot</h4><pre>df[[&quot;value&quot;,&quot;weekday&quot;]].groupby(&#39;weekday&#39;).mean().plot();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vS2duLLglq5Cvm1ekUgT3g.png" /></figure><ul><li>The taxi demands , are the highest in saturdays , so there is some kind of weekly seasonality , we can always dig deeper in the behaviour of weekdays each month using an unstacked plot but let’s just stick with this right now .</li></ul><h3>IV- Modeling with FBprophet</h3><p>The previous step was necessary in order to have an idea about the seasonalities of our data , because sometimes we can have complexe seasonalities in time series ,this needs further digging in order understand them , such as conditional seasonalities , seasonalities with different time periods (quarters as an example) , anomalies..</p><p>Sometimes some seasonalities are not important in the data they may add just noise so it’s better not to include them . we can adjust these things the way we want to improve our forecast .</p><p>Before Modeling we should do a small transformation to our original dataframe ,because there is a coonventional form of the data used by fbprophet we should respect .</p><pre><br>df = pd .read_csv(&quot;https://raw.githubusercontent.com/numenta/NAB/master/data/realKnownCause/nyc_taxi.csv&quot; , parse_dates = True)<br><br>df[&quot;timestamp&quot;] = pd.to_datetime(df[&quot;timestamp&quot;])<br><br>df = df.set_index(&quot;timestamp&quot;).resample(&quot;H&quot;).mean().reset_index()<br><br>df.columns  = [&quot;ds&quot;,&quot;y&quot;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*yXBfnj7423CcQc4SOn44aQ.png" /><figcaption>FBprophet format</figcaption></figure><p>When Prophet was initially released, it operated under the assumption that all data would be at a daily scale, equating to one data point per day. Over time, it has evolved to handle various granularities of data. However, due to its historical conventions, there are important considerations when dealing with non-daily data.</p><p>By default, Fbprophet is configured to use daily data, and adjustments are necessary for different granularities. Additionally, we need to determine whether our time series is multiplicative or additive. As we previously mentioned, our visual analysis indicates an additive time series, as the magnitude of seasonal components remains consistent with the trend.</p><pre>from prophet import Prophet<br><br># Initialize the prophet object , by default  Prophet is configured<br># with additive seasonality mode <br><br>model = Prophet(seasonality_mode=&#39;additive&#39;)<br>model.fit(df)</pre><p>Prophet analyzed the data and isolated both the seasonality <br>and trend without requiring us to specify any additional parameters.</p><p>To make some forecasts, we need to first make a DataFrame of future dates <br>and then call the predict method. The <strong>make_future_dataframe</strong> method requires us to specify <strong>the number of days </strong>we intend to forecast out ,we confine ourselves with the original dataframe , so we’ll set the horizon to zero , and the we plot our forecast .</p><pre># Creating a future object , inform the frequency of data <br>future = model.make_future_dataframe(periods=0,freq=&#39;H&#39;)<br># Call the predict method <br>forecast = model.predict(future)<br># Call the plot method <br>fig = model.plot(forecast, xlabel=&#39;Date&#39;, <br>                 ylabel=r&#39;Average passengers&#39;)<br>plt.title(&#39;Nyc taxi passengers predictions&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*4fB0tkwpTenIr3YlS-oSeg.png" /></figure><p>The plot represents predictions versus actuals in our dataset, highlighting anomalous data points and a confidence interval. When incorporating test data, the confidence intervals widen as we forecast further ahead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pd4G_NI4fE4lY_GHIZNo2Q.png" /><figcaption>zoomd plot</figcaption></figure><p>The model effectively captures the underlying pattern in the data; however, it is sensitive to anomalies caused by outliers. This sensitivity is particularly evident on January 27, 2015, coinciding with the North American blizzard event.</p><p>In our evaluation of the model using MAE and RMSE metrics, a significant discrepancy between the two emerged due to the presence of outliers. To further analyze the situation, we compared the additive and multiplicative models. The results leaned in favor of the additive model, showcasing lower errors and providing additional support for our choice of an additive approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*9FMfEVxPgNC2-eJffyYCJQ.png" /><figcaption>Evaluation metrics</figcaption></figure><h3>V- Anomalies Detection</h3><p>An anomaly in time series data occurs when a data point deviates significantly from the overall distribution of the dataset.</p><p>In our forecast, it’s evident that the seasonal pattern was disrupted at specific timestamps in our data — particularly on January 26–27, 2015, coinciding with the North American blizzard. This event had a notable impact on traffic, causing a deviation in the seasonal pattern.</p><p>A prudent approach would be to focus on detecting such anomalies, as doing so can significantly enhance the accuracy of our forecasts.</p><p>There are other events affecting our data. Upon further investigation, we can summarize the following events that influence the behavior of our time series data :</p><ul><li>NYC Marathon : 2014–11–02</li><li>Christmas -2014–12–25</li><li>New Years — 2015–01–01</li><li>Snow Blizzard — 2015–01–26 and 2015–01–27</li><li>Thanksgiving — 2014–11–27</li></ul><p>To gain a closer understanding of these significant days, we aggregated our data by ‘hour’ and ‘weekday.’ We then calculated the average values of our time series to observe its general behavior during these special days.</p><pre>df_final = df.join(df.groupby([&#39;hour&#39;,&#39;weekday&#39;])[&quot;value&quot;].mean() , on = [&quot;hour&quot;,&quot;weekday&quot;] , rsuffix = &quot;_avg&quot;)<br><br>#NYC Marathon : 2014-11-02<br><br>df_final.set_index(&#39;timestamp&#39;).loc[&#39;2014-11-02&#39;]</pre><p>The median value of our data is 16,913. Notably, during the NYC Marathon event, there are significant drops, with values plummeting to as low as 3,837 in the morning. Such sharp declines are highly unusual and warrant further investigation.</p><h4>V-1/ Isolation Forest</h4><p>The Isolation Forest algorithm is an ensemble regressor that leverages the concept of isolation to detect and separate anomalies. Unlike algorithms like k-means that rely on point-based distances or spatial proximity, Isolation Forest constructs an ensemble of random trees specific to a given dataset. Anomalies, in this context, are identified as points with the shortest average path length within the forest.</p><p>Isolation Forest can function both as a supervised and an unsupervised classifier. It is readily available in the scikit-learn package. However, it’s important to note that when using Isolation Forest, time distribution is not inherently considered. To address this, feature engineering is necessary, allowing the algorithm to incorporate contextual information. In our case, we included day and hour features to enhance the algorithm’s performance.</p><pre>df_final[&#39;day&#39;] = df.timestamp.dt.weekday<br>data = df_final[[&quot;value&quot;,&quot;hour&quot;,&quot;day&quot;]]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*tOL97xfpdf33wyLgToR_1Q.png" /><figcaption>Isolation Forest</figcaption></figure><pre>from sklearn. ensemble import IsolationForest<br><br>model = IsolationForest(contamination = 0.005 , max_features = 3 , max_samples = 0.8 , n_estimators = 200)<br><br>model.fit(data)</pre><p>We won’t delve into the details of its parameters in this blog; however, we may provide a thorough explanation in future blog posts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*IxtdjLN-tGXuTO0aRA0VEA.png" /><figcaption>Anomalous data points</figcaption></figure><p>As evident, the Isolation Forest proved to be highly effective in identifying anomalies, especially with the aid of feature engineering. Even when dealing with multiple time series data, the Isolation Forest demonstrates strong anomaly detection capabilities.</p><p>Given the abundance of anomalies identified, to obtain a broader perspective of these outliers, we will establish a threshold. This threshold allows us to focus on the most significant anomalies, avoiding unnecessary inclusion of minor deviations. By assigning scores, we can pinpoint the top 5 or top 10 anomalies, providing a clearer understanding of the most influential data points.</p><pre># we can do a cutoff in -0.05 , these are some anomalous points<br><br>df_final[&quot;scores&quot;] = score<br><br>df_final.query(&quot;scores&lt;-0.04&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*pc-CaWHRIzQk5738Wp9UAA.png" /><figcaption>Detected anomalies</figcaption></figure><p>This strongly confirms that the events we highlighted indeed create anomalous data points in our time series. Our immediate objective is to integrate this information into the Prophet model, aiming to enhance the accuracy of our forecasts. For a detailed reference, you can always access the <a href="https://github.com/SpaaceCadet/FBprophet_seasonal_time_series">source code</a> .</p><h3>VI- Adding custom holidays</h3><p>Prophet provides robust capabilities to integrate holiday effects into forecasts. In our case, we will incorporate custom holidays into our dataset.</p><pre># Create dataframe of holidays <br><br>Snow_Blizzard = pd.DataFrame({&#39;holiday&#39;: &#39;Snow_Blizzard&#39;,<br>                              &#39;ds&#39;: pd.to_datetime(<br>                                  [&#39;2015-01-26&#39;]),&#39;lower_window&#39;: 0,&#39;upper_window&#39;: 1,&#39;prior_scale&#39;: 4.861680615112172})<br><br>Snow_Blizzard = Snow_Blizzard[[&quot;ds&quot;,&quot;holiday&quot;,&quot;lower_window&quot;,&quot;upper_window&quot;]]<br><br><br><br><br>Thanksgiving = pd.DataFrame({&#39;holiday&#39;: &#39;Thanksgiving&#39;,<br>                                  &#39;ds&#39;: pd.to_datetime(<br>                                      [&#39;2014-11-27&#39;]),&#39;prior_scale&#39;:2.0820778020028414})<br><br><br><br><br>new_year = pd.DataFrame({&#39;holiday&#39;: &#39;new_year&#39;,<br>                                  &#39;ds&#39;: pd.to_datetime(<br>                                      [&#39;2015-01-01&#39;]),&#39;prior_scale&#39;:3.0272349876751266})<br><br><br><br><br><br>Christmas = pd.DataFrame({&#39;holiday&#39;: &#39;Christmas&#39;,<br>                                  &#39;ds&#39;: pd.to_datetime(<br>                                      [&#39;2014-12-25&#39;]),&#39;prior_scale&#39;:0.9932792600906482})<br><br>Christmas = Christmas[[&quot;ds&quot;,&quot;holiday&quot;]]<br><br><br># Concatenate holidays <br><br>holidays = pd.concat([Snow_Blizzard,<br>                          Thanksgiving,new_year,Christmas]).sort_values(&#39;ds&#39;)\<br>                         .reset_index(drop=True)<br><br># inform holidays in Prophet object <br><br>model = Prophet(seasonality_mode=&#39;additive&#39;,holidays=holidays)</pre><p>We should begin by creating dataframes containing the holidays we wish to incorporate. Within each dataframe, it’s essential to specify key-value pairs such as the holiday name and a list of timestamps when the holiday occurs. Additionally, we need to specify if the holiday appears once or multiple times in the data and forecast.</p><p>An optional parameter is the ‘prior scale,’ which allows us to regulate the impact of a particular holiday on the predicted values.</p><p>In cases where a holiday spans multiple days, we need to define the upper and lower windows. For example, if a holiday starts on 01–01–2023 and lasts for 3 days, the corresponding code would be:</p><pre>&#39;ds&#39;: pd.to_datetime([&#39;2023-01-01&#39;]),&#39;lower_window&#39;: 0,&#39;upper_window&#39;: 3</pre><p>And then we concatenate the holidays in a single Dataframe to feed it to our prophet object .</p><pre># Concatenate dataframes<br>holidays = pd.concat([Snow_Blizzard,<br>                          Thanksgiving,new_year,Christmas]).sort_values(&#39;ds&#39;)\<br>                         .reset_index(drop=True)<br><br># Feed the holidays to the prophet object <br>model = Prophet(seasonality_mode=’additive’ ,holidays = holidays`</pre><p>So now we are ready to make some forecasts , this new model resulted in better performance surpassing the first Model .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*aQjy2cKH73IY6THCGziobQ.png" /><figcaption>Performance metrics for the new model</figcaption></figure><p>Optimal performance can be attained through additional fine-tuning. In this discussion, we didn’t delve into seasonalities, trends changepoints, or leveraging additional regressors. However, these aspects will be explored in upcoming posts to deepen our understanding and enhance forecasting accuracy.</p><h3>VII- Conclusion</h3><p>Facebook Prophet emerges as a robust tool for time series forecasting, offering insights into holiday effects and anomaly detection. Through a real-world example, we highlighted the accuracy of predictions by factoring in holidays. Additionally, we emphasized tips to comprehend seasonalities in the data. The integration of Facebook Prophet and similar tools enhances our ability to analyze data effectively, extract meaningful insights, and make informed predictions.</p><p><strong>Equipped with this newfound knowledge, you’re prepared to enhance your forecasting using Facebook Prophet, unlocking better predictions and insights!</strong></p><p><strong>Feel free to share your experiences and thoughts. Your engagement is essential, and we’re eager to hear from you.</strong></p><p><strong>Happy forecasting!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a1a94752b2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerize Your Dash App]]></title>
            <link>https://medium.com/@yahyasghiouri1998/dockerize-your-dash-app-f502275475fa?source=rss-926c8b21d31f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f502275475fa</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[dash]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Yahya sghiouri]]></dc:creator>
            <pubDate>Wed, 12 Jul 2023 17:08:43 GMT</pubDate>
            <atom:updated>2023-07-12T17:08:43.063Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wUSz0mGLUYN_8M-qstzzzA.png" /><figcaption>Dashboard</figcaption></figure><p>In today’s world of software development, containerization has become a game-changer. Docker, a popular containerization platform, has revolutionized the way applications are deployed, scaled, and managed. If you’re working with Dash, a powerful Python framework for building interactive web applications, you might be wondering how to containerize your Dash app to streamline the deployment process and ensure consistent execution across different environments.</p><p>In this article, we will dive into the world of Docker and explore how to Dockerize a Dash app that you have already built. Whether you’re a beginner looking to containerize your first application or an experienced developer seeking best practices, this comprehensive guide will walk you through the process step-by-step.</p><p>Before we delve into Dockerizing your Dash app, it’s essential to have a solid understanding of the app’s structure. We highly recommend reviewing the app’s repository, which can be found in this<a href="https://github.com/SpaaceCadet/Dash-app-"> Repository.</a> Familiarizing yourself with the app’s components, dependencies, and overall architecture will greatly assist you in successfully containerizing it.</p><p>Throughout this guide, we will provide detailed explanations, code snippets, and practical examples to help you grasp the concepts effectively. By the end of this article, you will have a firm grasp of Docker fundamentals, understand the necessary steps to Dockerize your Dash app, and be equipped with the knowledge to confidently deploy your containerized application.</p><p>So, let’s embark on this Dockerization journey and unlock the benefits of containerization for your Dash app!</p><h3>I- What are Dash apps and what is their architecture ?</h3><ul><li>Before Containerizing our App it would be a great idea to grasp Dash apps architecture before Containerizing it .</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z1kEGE24mesAtIzjzsfm0w.png" /><figcaption>Dash app architecture</figcaption></figure><p>Dash apps are web servers that run Flask and communicate JSON packets via HTTP requests. We can therefore create interactive web applications by<br>Python. Its architecture is based on several components:</p><p><strong><em>1. Flask: </em></strong>Dash is built on the Flask framework, which is a lightweight web framework for Python. Flask allows to manage HTTP requests, routes, sessions and HTML templates . Dash uses Flask to manage interactions between the browser and Python backend .</p><p><strong><em>2. React.js:</em></strong> Dash uses React.js, a popular JavaScript library for authoring interactive user interfaces. React.js makes it easy to create reusable components and the effective updating of the user interface according to the interactions of the user. Dash components are translated into React components which are rendered in the browser using Dash renderer .</p><p><strong><em>3. Plotly.js:</em></strong> Dash uses Plotly.js, a JavaScript library based on D3.js, for the creating interactive charts. Plotly.js provides a wide range of chart types and interactive features. Graphs created with Plotly.js can be integrated into Dash applications.</p><p><strong><em>4. Dash Core Components (dcc): </em></strong>Dash provides a library of reusable components called “Dash Core Components”. These components allow you to create elements user interface such as buttons, drop-down menus, tables, etc. the Dash Core Components are written in Python but translated to React components when rendered in the browser.</p><p><strong><em>5. Communication aspect between the Back-end and the Front-end:</em></strong> Dash uses an architecture of communication based on the HTTP protocol and web-sockets to exchange data .</p><h3>II- Development servers and Production servers what’s the difference ?</h3><p>Let’s make some points clear ,Before deploying a web app written in any language you should make a difference between <strong>development servers and production servers .</strong></p><p><strong>Development servers</strong> are web servers that are used to run web applications during development. they are typically simple servers that are not as powerful as <strong>production servers.</strong></p><p><strong>Development servers </strong>are often used to test web applications locally before they are deployed to a production server. A <strong>production server </strong>instead it is a web server that is used to run web applications in a live environment. It is typically a more<strong> powerful and scalable server than a development server. Production servers</strong> are often used to host websites and web applications that are accessible to the public.</p><p>In the context of a <strong>Flask app</strong> when you hit flask run in your terminal to run your flask app , it’ll load the necessary tools just to render your web app and make it run , this server doesn’t come with additional features that a robust server have , just to simplify the development process nothing else . Some of the benefits of using a <strong>development servers</strong> are :</p><ul><li><strong>Easy to set up: </strong>Development servers are typically easy to set up and use. This makes them a good choice for developers who are new to web development.</li><li><strong>Fast: </strong>Development servers are typically very fast. This allows developers to test their web applications quickly.</li><li><strong>Flexible: </strong>Development servers are typically very flexible. This allows developers to experiment with different settings and configurations.</li></ul><p>But this comes with a cost , here are some of the limitations of using a <strong>developement server</strong> :</p><ul><li><strong>Not as powerful as a production server:</strong> Development servers are typically not as powerful as production servers. This means that they may not be able to handle as many concurrent requests.</li><li><strong>Not as secure as a production server: </strong>Development servers are typically not as secure as production servers. This means that they may be more vulnerable to attacks.</li></ul><p>Here are some Examples of production servers :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*kn1PWXEL8tGrixQm8oldJA.png" /><figcaption>Production Servers</figcaption></figure><ul><li><strong>Apache:</strong> Apache is a popular open-source web server. It is very powerful and scalable.</li><li><strong>Nginx: </strong>Nginx is a high-performance web server. It is often used for load balancing and reverse proxying.</li><li><strong>Amazon Web Services (AWS) Elastic Beanstalk,Google Cloud Platform (GCP) App Engine :</strong> these are managed platform that makes it easy to deploy and scale web applications.</li></ul><h3>III- WSGI interface, Gunicorn ,Nginx : how they can be used together to run dash apps , or python web apps in general</h3><p>To understand how python web apps work we should clarify some concepts .</p><h4>III-1/ WSGI</h4><p>Python web applications leverage the power of the WSGI (Web Server Gateway Interface) standard, enabling them to seamlessly operate on any WSGI server. WSGI serves as a common ground for communication between web servers and applications. While originally tailored for Python, it also boasts compatibility with various other programming languages. The WSGI interface encompasses a collection of functions, granting web servers the ability to effortlessly interact with web applications. Among its functionalities are handling HTTP requests, generating responses, and managing errors with utmost efficiency and reliability.</p><h4>III-2/ Gunicorn , Nginx ,…</h4><p>A traditional web server does not understand or have any way to run Python applications , that why we need web servers that are WSGI based that is to say they are supporting interactions with python web apps using that interface . for more informations about WSGI servers : <a href="https://www.fullstackpython.com/wsgi-servers.html">follow this link</a></p><blockquote><strong>So what are exactly gunicorn , Nginx , .. waitress servers ?? , and why do we need them ?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*P-dPYY3u5Jf81TDIK4fnLw.png" /><figcaption>WSGI interface</figcaption></figure><ul><li>Gunicorn , Nginx.. etc are <strong>production servers </strong>, so in order to deploy your web app it is important to look for a production server ,These production servers mentioned before , support the standard of WSGI interface , that mean they can be used to deploy and and serve our python web apps online .</li><li>So in order to deploy a flask app , Dash , Django or whatever python app supporting WSGI , you need to look after these kind of production servers .</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*hadsq_Q8yj7EC-XrXkmiXQ.png" /><figcaption>Interaction with python web app</figcaption></figure><h3>IV- Common architecture of deployement of python web apps</h3><p>There is a common combination , used to deploy python web apps , which is using gunicorn along with nginx , this combination will make your web app more robust .<br>Here are some key features why you might want to use nginx with gunicorn:</p><ul><li><strong>Load balancing:</strong> Nginx can be used to load balance multiple gunicorn workers. This can help to improve the performance of your web app by distributing traffic across multiple servers.</li><li><strong>Reverse proxying:</strong> Nginx can be used to reverse proxy requests to gunicorn. This means that nginx can handle the initial request from the client, and then pass the request on to gunicorn. This can help to improve the security of your web app by preventing direct access to gunicorn.</li><li><strong>Static file serving:</strong> Nginx can be used to serve static files, such as images, CSS, and JavaScript files. This can help to improve the performance of your web app by offloading the static file serving from gunicorn.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*CoQROwNSfR0ufPXVTxF4tQ.png" /><figcaption>Common architecture of deployment</figcaption></figure><h3>V- Containerize your Dash app</h3><h4>V-1/ What is docker first ?</h4><ul><li>Docker is a powerful platform that revolutionizes software deployment by providing containers. These containers, similar to virtual machines, create isolated computing environments that package software components together. However, the key difference lies in their scale and portability. Docker containers are lightweight and measured in megabytes, while virtual machines are larger and measured in gigabytes.</li><li>The significance of Docker containers lies in solving a long-standing pain point in software management. Traditionally, managing software across different platforms required dealing with various dependencies, interpreters, and binaries. Docker brings consistency to software deployment by providing a unified platform that simplifies maintenance and deployment processes.</li><li>Major tech giants like Google, Azure, and AWS recognize the value of Docker in simplifying application deployment across different operating systems. They leverage Docker to streamline app deployment for all users, regardless of their chosen operating system.</li><li>By understanding Docker, you gain access to a technology that has transformed the way we deploy software. Its portability, efficiency, and ease of use make it a game-changer in the world of software development and deployment.</li></ul><h4>V-2/ Writing Your base Image</h4><p>Before writing your Base image consider creating a requirements.txt file , which contains all the necessary librarires to run your app :</p><pre>pip freeze &gt;requirements.txt</pre><p>Paste this to your terminal <br>Then add manually <strong>“gunicorn” </strong>to your requirements.txt if it’s not installed in your virtual environment .</p><p>Then to containerize your app you should first , write a <strong>Dockerfile </strong>, <br> A <strong>Dockerfile</strong> serves as a blueprint for instructing Docker on how to construct your container. It encompasses details such as the base image to be used as the foundation for your Docker container, any supplementary steps required for installation or configuration, and directives on how to execute your application.<br>Below, we have presented a sample Dockerfile that you can utilize as a starting point to create your own Dockerfile with the appropriate specifications:</p><pre><br>#Using python<br>FROM python:3.9-slim<br># Using Layered approach for the installation of requirements<br>COPY requirements.txt ./requirements.txt<br>RUN pip install -r requirements.txt<br>#Copy files to your container<br>COPY . ./<br>#Running your APP and doing some PORT Forwarding<br>CMD gunicorn -b 0.0.0.0:80 app:server</pre><p>To Clarify more this syntaxe ,We used here a layered approach to create our <strong>Dockerfile </strong>, because Docker uses layers to build images ,This has some caching benefits to avoid unnecessary computations and downloads when we deal with some changes in our source code .</p><p><strong>Docker layers </strong>are a fundamental concept in Docker images. Each layer represents a change or modification made to the image during the build process. Layers are created based on the instructions specified in the Dockerfile.</p><p>So first we copied Requirements.txt , and we installed it the necessary librairies ,And then we copied all the files in the container .</p><p>Basically if we do a change to to our app files , it won’t affect our image , rebuilding it won’t take so much time , because Docker cached the previous build .</p><p>After this we run the command gunicorn to serve our webapp in port 8080 .</p><h4>V-3/ Building Image</h4><p>To build your base image , change your directory to ../../app , This folder has your app.py,Dockerfile,requirements.txt</p><p>Run the following command :</p><pre>docker build -t my-app . </pre><p>After this you can run an instance of your image which is a container,But you must pay attention to ports .</p><p>Port of the application in which it is running (you can always check the <a href="https://github.com/SpaaceCadet/Dash-app-">repo in github</a>)</p><pre>if __name__ == &#39;__main__&#39;:<br> app.run_server(debug=True, host=&quot;0.0.0.0&quot;, port=8080, use_reloader=False)</pre><p>The application is running on port 8080 , we’ll perform some port forwarding after this . so it’ll run on a specific port , to avoid any conflict with other ports , so we are exposing port 4500 for our host machine , You can use the following command</p><pre>docker run -p 4500:8080 --name frst-dash my-app </pre><p>The -p stands for port , and –name for the name if your container , and then you provide the name or hash of your base image .</p><p>Now we are good to go we can access our localhost using port 4500 and use our app .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qevH-83FGTrkgnAsYQzDYQ.png" /><figcaption>Running web app</figcaption></figure><h3>VI- Conclusion</h3><p>In conclusion, understanding the architecture of a Dash app, differentiating between production and development servers, and mastering the process of containerization are crucial steps towards deploying efficient and scalable applications. By leveraging containerization with Docker and adopting <strong>best practices</strong>, you can streamline deployment and ensure consistent execution across environments.</p><p><strong>Empowered with this knowledge, you are ready to take your Dash apps to new heights of performance and reliability !!</strong></p><p><strong>Feel free to share your thoughts and insights with us by leaving a comment below! We look forward to hearing from you.</strong></p><p><strong>Happy coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f502275475fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Setup Lamp stack]]></title>
            <link>https://medium.com/@yahyasghiouri1998/how-to-setup-lamp-stack-2839f5d16454?source=rss-926c8b21d31f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2839f5d16454</guid>
            <category><![CDATA[lamp]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Yahya sghiouri]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 11:21:44 GMT</pubDate>
            <atom:updated>2023-07-04T11:27:45.591Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*fz84_1AS0T14JjarqcNaug.png" /><figcaption>LAMP stack</figcaption></figure><p>Setting up a local development environment is essential for web developers and enthusiasts alike. One critical aspect of this environment is the integration of a relational database management system (RDBMS) and a web server. In this blog post, we will guide you through the process of configuring MySQL, a popular RDBMS, with Apache, a widely used web server, on your localhost.</p><p>By following this step-by-step guide, you’ll learn how to seamlessly connect MySQL with Apache, enabling you to store and retrieve data from databases within your web applications. Whether you’re a beginner taking your first steps in web development or an experienced developer looking to refine your local setup, this tutorial will provide you with the knowledge and confidence to configure MySQL and Apache efficiently.</p><p>We will cover everything from the initial installation and setup of MySQL and Apache to the integration of PHP, a server-side scripting language commonly used with this stack. By the end of this tutorial, you’ll have a fully functional local environment, allowing you to develop and test database-driven web applications with ease.</p><p>So let’s dive in and explore the process of configuring MySQL with Apache on your localhost!</p><h3>I- How this Architecture works</h3><h4>I-1 Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*jJ7ExQ067uI7pzzI6F947A.png" /><figcaption>LAMP architecture</figcaption></figure><p>In this architecture, when a user requests a PHP webpage, the Apache web server receives the request. The Apache server utilizes PHP modules to interpret the PHP code and generate HTML content as a response. If the webpage requires interaction with a database, the PHP modules handle the necessary queries. Finally, the Apache server returns the results to the user as HTML.</p><p>The goal of using PHP alongside with Apache is to enable the creation of dynamic web pages and web applications. PHP is a server-side scripting language specifically designed for web development, while Apache is a popular web server software .</p><h4>I-2 PHP ecosystem</h4><p>When PHP is combined with Apache, the following benefits can be achieved:</p><ul><li>Dynamic Content Generation: PHP allows you to embed PHP code directly into HTML files, making it possible to generate dynamic content on the server-side. This means that the web pages can be customized and personalized based on user input, database queries, or any other logic.</li><li>Seamless Integration: Apache provides a reliable and robust web server environment. By configuring Apache to work with PHP, it can seamlessly process PHP code within web pages, enabling the execution of PHP scripts and generating dynamic content.</li><li>Scalability and Performance: Apache is known for its scalability and ability to handle a large number of simultaneous connections. PHP, when properly optimized, can also deliver efficient performance. The combination of Apache and PHP allows for the development of high-performance web applications that can handle heavy traffic loads.</li><li>Popular Ecosystem: PHP has a vast community and a rich ecosystem of frameworks, content management systems (CMS), and libraries. Popular PHP frameworks like Laravel, Symfony, and CodeIgniter, along with CMS platforms like WordPress, rely on Apache to serve PHP-based applications and content.</li></ul><h3>II- Installation process</h3><h4>Step 1:Installing Apache</h4><ul><li>The first thing you have to do is to update the package manager .</li></ul><pre>sudo apt update <br>sudo apt install apache2</pre><ul><li>Enable your firewall so that your apache accepts web traffic , on Port 80</li></ul><pre>sudo ufw allow in &quot;Apache&quot;</pre><p>Enabling a firewall for port 80 when installing Apache is an important security measure. Here are a few reasons why it is recommended:</p><ul><li>Protecting against unauthorized access: Opening port 80 on a server allows incoming web traffic, which makes the server accessible from the internet. By enabling a firewall, you can control which IP addresses or networks are allowed to access the server on port 80. This helps prevent unauthorized access or potential attacks from malicious users or bots.</li><li>Filtering incoming traffic: A firewall allows you to filter and block incoming traffic based on specific criteria. With port 80, you can specify rules to allow legitimate web traffic while blocking suspicious or malicious requests. This helps to protect your server from common web-based attacks like DDoS, SQL injection, or cross-site scripting.</li><li>Limiting exposure to vulnerabilities: Even well-configured web servers like Apache can have security vulnerabilities that may be exploited by attackers. By enabling a firewall, you add an extra layer of defense that can prevent potential exploits from reaching the server and compromising its security.</li><li>Compliance with best practices: Implementing a firewall is considered a best practice for securing servers and networks. It demonstrates a proactive approach to security and aligns with industry standards and guidelines.</li></ul><p>- After this you can check if it’s sucesfully installed by typinng ; <br><a href="http://127.0.0.1/">http://127.0.0.1/</a> (localhost address)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*5ImjAeXxkXXdwE4dNip5dQ.png" /><figcaption>Running Apache</figcaption></figure><h4>Step 2:Installing MySQL</h4><ul><li>First install mysql server</li></ul><pre>sudo apt install mysql-server</pre><ul><li>Then after installing login to MySQL using default credentials <br>‘root’ and no skip password,</li></ul><pre>sudo mysql -u root -p</pre><ul><li>Then create a new user , because it’s not practical to create tables and work with root user directly .</li></ul><pre>CREATE USER &#39;USER_TEST&#39;@&#39;localhost&#39; IDENTIFIED BY &#39;password&#39;;</pre><ul><li>Create a new database , and create a table in it for example , and then grant permissions for this users to use allowed tables :</li></ul><pre>GRANT ALL privileges on `DB_NAME`.`TABLE` TO `USER_TEST`@`localhost` ;</pre><ul><li>You can replace the Table with `*` if you have many tables and you want to include them all . <br>after this , use the exit command, to exit from the MySQL editor .</li></ul><h4>Step 3: Installing PHP</h4><ul><li>You have Apache installed to serve your content and MySQL installed to store and manage your data. PHP is the component of our setup that will process code to display dynamic content to the final user.</li><li>Run the following command :</li></ul><pre>sudo apt install php libapache2-mod-php php-mysql</pre><ul><li>In addition to PHP , you are installing libapache2-mod-php ,so the apache server can handle php file extensions . And then php-mysql which is a module that permit to php to interact with MySQL databases .</li><li>Once the installation is done youc an check your installed php version : with `php -v` command .</li></ul><h4>Step 4: Check the setup of LAMP</h4><ul><li>Before finishing make sure that everything is well setup , we’ll provide a code to do a quick check ,Run the following command to access the directory of yout web projects :</li></ul><pre>cd /var/www/html</pre><ul><li>Then create a php file in it :</li></ul><pre>sudo nano test.php</pre><ul><li>Then paste the following php code , This will just show some content from your created tables .</li></ul><pre>&lt;?php<br>$user = &quot;username&quot;;<br>$password = &quot;password&quot;;<br>$database = &quot;db_name&quot;;<br>$table = &quot;table_name&quot;;<br><br>try {<br>  $db = new PDO(&quot;mysql:host=localhost;dbname=$database&quot;, $user, $password);<br>  echo &quot;&lt;h2&gt;TODO&lt;/h2&gt;&lt;ol&gt;&quot;; <br>  foreach($db-&gt;query(&quot;SELECT  username  FROM $table&quot;) as $row) {<br>    echo &quot;&lt;li&gt;&quot; . $row[&#39;username&#39;] . &quot;&lt;/li&gt;&quot;;<br>  }<br>  echo &quot;&lt;/ol&gt;&quot;;<br>} catch (PDOException $e) {<br>    print &quot;Error!: &quot; . $e-&gt;getMessage() . &quot;&lt;br/&gt;&quot;;<br>    die();<br>}<br>?&gt;</pre><ul><li>Replace user , password, database and table , with your informations , if this runs correctly and render data in webpage that means your LAMP stack is setup .</li><li>After this , try to access this php file using yout browser localhost/directory../file.php</li><li>For my case it’s running perfectly :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*xkaStFedt8r1XqAwLQWfEg.png" /><figcaption>Check LAMP stack</figcaption></figure><ul><li>Now we are good to goo .</li></ul><h3>III-Conclusion:</h3><p>In this blog post, we explored how to set up the LAMP stack (Linux, Apache, MySQL, and PHP) for local web development. While the LAMP stack is a reliable choice, it’s essential to consider alternative options.</p><p>NGINX, a lightweight and high-performance web server, provides efficient resource utilization and advanced load balancing. For Python applications, Gunicorn is often recommended, while Java applications are better suited for Tomcat or other application servers.</p><p>Choosing the right web server depends on specific project requirements. Factors like scalability, performance, compatibility, and community support should be considered.</p><p>With this knowledge, you can confidently configure the appropriate web server for your project and begin your web development journey.</p><p><strong>Happy coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2839f5d16454" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up your ssh keys for git]]></title>
            <link>https://systemweakness.com/setting-up-your-ssh-keys-for-git-a63e4e0fb91?source=rss-926c8b21d31f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a63e4e0fb91</guid>
            <category><![CDATA[key-management]]></category>
            <category><![CDATA[ssh-keys]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[cryptography]]></category>
            <dc:creator><![CDATA[Yahya sghiouri]]></dc:creator>
            <pubDate>Sun, 02 Jul 2023 17:46:20 GMT</pubDate>
            <atom:updated>2023-07-11T11:51:12.048Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*003eTZDr33Ws2O8dXSFXeQ.jpeg" /><figcaption>Locks</figcaption></figure><p>Cryptography is the practice of securing communication in the presence of adversaries. It encompasses various techniques and algorithms used to encrypt and decrypt information, ensuring its confidentiality, integrity, and authenticity. Before delving deeper into the subject, it’s helpful to gain an understanding of some cryptographic concepts. Feel free to skip this section if necessary, although comprehending these concepts is beneficial since SSH keys serves various purposes beyond just GitHub.</p><h3>I- Overview on some cryptographic concepts</h3><blockquote><strong>The need for cryptography arises from the following reasons:</strong></blockquote><ol><li><strong>Confidentiality: </strong>it allows for the secure transmission and storage of sensitive information by encrypting it. Encryption converts the plaintext (original message) into ciphertext (encoded message) using cryptographic algorithms. Only authorized parties possessing the correct decryption key can convert the ciphertext back to plaintext and access the original information.</li></ol><p><strong>2. Integrity: </strong>Cryptographic techniques can verify the integrity of data. By using hashing algorithms or digital signatures, the sender can create a unique value based on the data, which can be used by the recipient to verify that the data has not been modified during transmission.</p><p><strong>3. Authentication:</strong> Cryptography helps establish the authenticity of entities involved in communication. Digital signatures, for example, provide a way to verify the identity of the message sender and ensure the integrity of the message. By using asymmetric encryption, a private key is used to sign the message, and a corresponding public key is used to verify the signature aka Prove who you say you are !</p><p><strong>4. Non-repudiation:</strong> Cryptography provides a means to prevent individuals from denying their involvement in a communication or transaction. Digital signatures and other cryptographic mechanisms can ensure that the originator of a message or the parties involved in a transaction cannot later deny their participation.</p><p><strong>5. Secure Key Exchange:</strong> Cryptography allows for secure key exchange between parties. Key exchange protocols such as Diffie-Hellman or key agreement algorithms enable two or more parties to establish a shared secret key over an insecure communication channel. This shared key can then be used for symmetric encryption, which is faster and more efficient for encrypting large amounts of data.</p><p><strong>6. Privacy and Data Protection:</strong> Cryptography plays a crucial role in protecting personal privacy and sensitive data in various domains, including online communication, e-commerce, financial transactions, healthcare, and more. It helps ensure that only authorized individuals can access and interpret sensitive information.</p><ul><li><em>So by providing confidentiality, integrity, authentication, non-repudiation, and secure key exchange, cryptography enables secure communication, data protection, and trust in various digital systems and networks. It is a fundamental building block for ensuring security in today’s interconnected world.</em></li></ul><blockquote><strong>Public algorithms :</strong></blockquote><p>The algorithms used for encryption , are mainly publicly available , but the keys remain secret .<br> when an algorithm is made public, it allows everyone to explore and scrutinize it, making it easier to identify any vulnerabilities or weaknesses intentionally or unintentionally left by the designers. This leads to improved security. Additionally, since publication is permitted, there is no need to protect the code against reverse-engineering. The publication of algorithms also enables global research and the development of various software implementations. Furthermore, using the same public version promotes general standardization. Consequently, <strong><em>published algorithms are often preferred as they tend to be more secure due to the reasons mentioned above.</em></strong></p><h3>II- Asymmetric and Symmetric encryption</h3><p>Asymmetric encryption and symmetric one , are two fundamental techniques used in cryptography to secure data and communication. They differ in how they utilize keys and perform encryption and decryption processes.</p><h4>1-Symmetric Encryption :</h4><ul><li>Also known as secret-key or shared-key encryption,involves the use of a single key for both encryption and decryption. The same secret key is used by both the sender and the recipient to encrypt and decrypt the data. It is called symmetric encryption because the encryption and decryption processes are symmetric or identical .</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*Ncv3sYS0WB91HPgAyTouAA.png" /><figcaption>Symmetric encryption</figcaption></figure><p><strong>The Key features of symmetric encryption include:</strong></p><ul><li><strong>Efficiency:</strong> Symmetric encryption algorithms are generally faster and more efficient than asymmetric encryption algorithms.</li><li><strong>Security:</strong> The security of symmetric encryption depends on keeping the shared key secret. If the key is compromised, an attacker can decrypt the encrypted data.</li><li><strong>Key distribution:</strong> The challenge in symmetric encryption lies in securely distributing the shared key to all parties involved in the communication.</li></ul><p><strong>Example of symmetric encryption algorithmes :</strong> AES (Advanced Encryption Standard), DES (Data Encryption Standard), and 3DES (Triple Data Encryption Standard).</p><h4>1-Asymmetric Encryption :</h4><ul><li>This is a public-key encryption, employs a pair of <strong><em>mathematically related keys: a public key and a private key.</em></strong> The public key is freely distributed, while the private key remains secret and known only to the owner.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*8dNJ-uaWA3MJlv1bH6DOdw.png" /><figcaption>Asymmetric encryption</figcaption></figure><p><strong>The Key features of Asymmetric encryption include:</strong></p><ul><li><strong>Encryption and decryption : </strong>The public key is used for encryption, while the corresponding private key is used for decryption. Data encrypted with the public key can only be decrypted with the private key.</li><li><strong>Digital signatures:</strong> Asymmetric encryption also enables the creation and verification of digital signatures, which ensure data integrity and authenticity.</li><li><strong>Key distribution:</strong> Asymmetric encryption simplifies the key distribution problem since the public keys can be freely shared.</li></ul><p><strong>Common asymmetric encryption algorithms include:</strong> RSA, Diffie-Hellman, and Elliptic Curve Cryptography (ECC) .</p><p><strong><em>In practice, a combination of symmetric and asymmetric encryption is often used. For example, asymmetric encryption may be used to establish a secure channel and exchange a shared secret key. Subsequently, symmetric encryption using the shared key can be employed for encrypting the actual data, providing efficiency and security.</em></strong></p><h3>III- SSH remote connection in Github.</h3><ul><li>In 2021 Github stopped using username and passwords for authentication for git service because of some security issues and the need for more robust authentication methods .</li><li>In Git, SSH keys are used as a secure authentication method for establishing a secure connection between a client (local machine) and a Git server, such as GitHub, GitLab, or Bitbucket. SSH keys in Git serve as a secure alternative to using a username and password for authentication .</li></ul><h4>1-Setup keys in linux:</h4><ul><li>To setup remote connection with github , we should first generate key pairs , thank’s to them we can identify our machine by unique keys , using asymmetric encryption .</li></ul><p><strong>Checking Openssh client:</strong></p><ul><li>Before doing anything you should check if ssh client is installed , by the following command :</li></ul><pre>ssh -v</pre><ul><li>if not :</li></ul><pre>sudo apt update<br>sudo apt install openssh-client</pre><p><strong>Key generation:</strong></p><p>we need to generate an SSH key pair on out client machine. we create a public key and a corresponding private key. The private key is stored securely on the client machine, while the public key is shared with the Git server.</p><pre>ssh keygen -t ed25519 -C  my_email@example.com</pre><p>Let’s clarify this command : <br> — By using ssh-keygen we specify : how we are going to generate the key .<br> — the tag `-t` is used to specify the type of encryption , in our case we used `ed25519` which is a modern elliptic curve algorithm that provides strong security and is widely used for SSH key generation, we can use other algorithms like RSA as an example ..<br> — The tag -C , is used to Add a comment , it’s optional , and can be useful for identifying the key’s purpose or owner when managing multiple keys.<br>- When you run the previous command , the ssh-keygen utility will generate a new `ed25519` SSH key pair, consisting of a private key and a corresponding public key. The private key will be stored on your local machine, typically in the `~/.ssh/ directory` with the filename `id_ed25519`, while the public key will have a .pub extension and can be shared with remote system(github) .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*nvZMgnz9ZyjAWIolL3gJhg.png" /><figcaption>Generate keys</figcaption></figure><ul><li>Here we generated two key pairs using rsa algorithme , the private key is in `id_rsa` , and the public one is in `id_rsa.pub`<br>- it asked for locations and a passphrase , we skipped them to use default settings .</li></ul><p><strong>SSH-agent :</strong></p><ul><li>The SSH agent is a program that runs in the background on your local machine and securely stores your SSH private keys. When you use SSH to connect to a remote server or authenticate with a service, the SSH agent handles the private key operations on your behalf, eliminating the need to repeatedly enter passphrases or expose your private keys ; <strong><em>So we need to make sure that this agent knows about this key !!</em></strong></li><li>First thing you need to do is to start your ssh agent :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*eOzY2ODpWP6PZWCyFhBQjA.png" /><figcaption>Start SSH agent</figcaption></figure><ul><li>Then edit a file ,in your ssh wallet which is a configuration file for your ssh keys generated ,using the following command :</li></ul><pre>nano ~/.ssh/config</pre><p>and then type the following :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*ac4L7n_JZP9CJ2lgHCw_mA.png" /></figure><ul><li>The first line specifies the hosts , in our case it’s “*” for all hosts or websites , we can use multiple hosts as with different configurations , but the asterisk will do the job in our case .</li><li>The second line , specifies that we are adding the private key to our agent , and the last one we specify where this private key is located</li><li>After doing this we save the file .</li></ul><p><strong>Content of SSH folder :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*Z6nhWC7B1P6XWi8L3rNq-g.png" /><figcaption>Folder ssh</figcaption></figure><p>in our case we used just the first key that was already setup .</p><p><strong>Public Key Upload:</strong></p><ul><li>We upload the public key to the Git server. by adding the public key to the user’s account settings on the Git platform.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*SUxuASQe_sw5YSoNT5nN4Q.png" /><figcaption>SSH-keys-Git</figcaption></figure><ul><li>Head up to your settings , and setup your ssh public key .</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*bYhFGE0g3LMXbm6PZ8mgVg.png" /><figcaption>Create ssh keys</figcaption></figure><p>Here you add your public key , you can find it in : ‘id_rsa.pub’</p><pre>cat id_rsa.pub</pre><ul><li>Copy paste the content of the file there .</li></ul><p><strong>Test your ssh key</strong></p><ul><li>To test your ssh key , type the following command :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*cfflidbec5AafQuxhIcSDA.png" /></figure><ul><li>Now you’re good to goo !</li></ul><p><strong>Authentication : </strong>When you interact with the Git server, such as pushing or pulling code, the server requests authentication. The client’s SSH agent on the local machine presents the private key associated with the public key uploaded to the server.</p><p><strong>Secure Connection: </strong>The Git server uses the public key stored on its end to verify the authenticity of the private key presented by the client. If the keys match, the server allows the client to establish a secure encrypted connection for the Git operations.</p><h3>IV-CONCLUSION :</h3><p>In conclusion, setting up SSH keys for Git enhances security and streamlines collaboration with remote repositories. By generating an SSH key pair, adding the public key to your Git server, and configuring your Git client, you establish a secure connection without relying on traditional username/password authentication. Adopting SSH keys improves the protection of sensitive information and reduces the risk of unauthorized access. Remember to properly manage and safeguard your private key, regularly rotate your keys, and stay vigilant in protecting your code and data.</p><ul><li><strong><em>Happy coding and secure collaborating!</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a63e4e0fb91" width="1" height="1" alt=""><hr><p><a href="https://systemweakness.com/setting-up-your-ssh-keys-for-git-a63e4e0fb91">Setting up your ssh keys for git</a> was originally published in <a href="https://systemweakness.com/">System Weakness</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I-What is PCA ?]]></title>
            <link>https://medium.com/@yahyasghiouri1998/i-what-is-pca-7fd948ae05b3?source=rss-926c8b21d31f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fd948ae05b3</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[noise-reduction]]></category>
            <category><![CDATA[dimensionality-reduction]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Yahya sghiouri]]></dc:creator>
            <pubDate>Thu, 12 Jan 2023 05:05:54 GMT</pubDate>
            <atom:updated>2023-10-11T12:30:09.145Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is PCA ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kefjGHGBn4rgnKUXQRU6dA.png" /><figcaption>Denoised image</figcaption></figure><h3>I-INTRODUCTION:</h3><p>Welcome to our exploration of Principal Component Analysis (PCA), a powerful tool in the world of data analysis and statistics. In this journey, we’ll delve into the depths of PCA, understanding its applications and unveiling its potential to uncover patterns and streamline complex datasets. PCA, a linear technique, serves as a guiding light to reveal the significant directions in which data varies, allowing us to transform and simplify large datasets into a more manageable, lower-dimensional space. This newfound perspective can illuminate insights, aiding in visualizing intricate data, compressing information, and mitigating noise. So, fasten your seatbelt as we navigate through the intricacies and implications of PCA!</p><h3><strong>II-</strong>The mathematical concepts and methods underlying Principal Component Analysis (PCA)<strong>:</strong></h3><p>Before delving into the mathematical concepts, let’s first define what PCA is. PCA stands for Principal Component Analysis, a technique used in data analysis and statistics to identify patterns (signals) in data and reduce the dimensionality of large datasets. It is a linear technique that identifies the directions (principal components) in which the data varies the most. PCA can be used to transform the original dataset into a new, lower-dimensional space where the data is represented by a smaller number of features that capture most of the information present in the original dataset. This transformation is valuable for visualizing and understanding complex datasets, as well as for data compression and noise reduction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nioZllbllkFxeuKTihP7wA.png" /><figcaption>projection of data points on components</figcaption></figure><ul><li>As the figure illustrates, new axes have been created, serving as the new basis for data projection. These axes are the optimal directions for maximizing variance and the amount of projected information.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*lV2OOlESaDqxzcpTH8gpJQ.png" /><figcaption>Matrix (m,n)</figcaption></figure><ul><li>Let’s imagine the above matrix as our dataset , m is the number of observations , and n the number of variables , let’s say n=3 ,so we have 3 variables :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/1*IabC3jcGdhkNcqN9L7BeaQ.png" /></figure><ul><li>Each variable has a dimension of (m, 1), where m represents the number of observations. A single observation can be represented by a tuple of n elements. For instance, the observation in row i, takes the following form:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*6GaQuKiqq3eMJ_Qwpdldiw.png" /></figure><p>it is a single data point , We are looking to find a single data point that represents the overall characteristics of our dataset, which can be determined by taking the mean of all the variables Ai:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/1*nZVhigZq1eMJ0p50_470Cw.png" /></figure><ul><li>The quantity of information or variance in data , is : the sum of all euclidien distances between data points and data center (G) :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/176/1*0RcAMIyh5dWkfDKVhqbxTA.png" /></figure><p>it is simply equal to : sum(Variance(Ai))</p><ul><li>In our context, information is equivalent to the sum of variances (A1+A2+A3) or the eigenvalues of the covariance matrix, which we will cover later. Our objective is to find a new basis for projection while maximizing the retained variance. When projecting data onto new axes, some variance and therefore information is lost, as illustrated in the image. The blue area represents the lost variance, the green area represents the retained variance (projection) and the black line represents the total variance</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*lWBX08NF44kU9OIu8dk9cA.png" /><figcaption>projection of data points</figcaption></figure><h3>III-How these axis are found ?</h3><ul><li>Each principal component represents a certain proportion of variance, which is computed as the sum of the data point projections onto that component. The base of the projection is obtained by calculating the eigenvectors of the covariance or correlation matrix of the data. To manually perform this calculation, you first need to center the data and then apply the appropriate mathematical operation</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*m_QqOs6sXLg7rJt2FE4MjQ.png" /></figure><p>Here is a basic python code , to do it ,or you can just use numpy.cov() function :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*fyzJnHrNmQLmvVND-N95pA.png" /></figure><ul><li>The matrix has high rank, the number of eigenvectors is equal to the number of variables. Projecting the data onto these axes results in a new matrix, with the same dimensions as the original data but with new variables, referred to as components. Each component has a specific proportion of explained variance and are ordered based on the amount of information they contain.</li></ul><p>Explained_variance(Component 1)&gt;Explained_variance(Component 2)&gt;….&gt;Explained_variance(Component n) .</p><h3>IV-Uses of PCA :</h3><ul><li>It’s important to note that in reality, data is rarely perfect. Many datasets encounter the issue of multicollinearity, which results in high linear correlation among variables. Utilizing PCA to project the data onto a set of principal components (n components) effectively eliminates this correlation, rendering the components independent. This can solve the problem of multicollinearity in various modeling scenarios, while preserving the same number of variables.</li><li>Another way to retain a specific amount of information from the original data is by calculating the explained variance ratio of each variable. This can be done relatively easily by:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*g1IBcOZEy1DWqx9L4KX4Zg.png" /></figure><p>and then sum consecutive ratios , until we fill our need , for example suppose that consecutive ratios of our first example(Matrix A) are : r1=60% , r2=25% , r3=15%, we want to keep 80% of information , r1+r2=85% it contains the sufficient ratio ,we’ll keep then only the two components ,Or we can simply decide how much components to keep from the beginning , hese approaches are essential in filtering out noise and identifying patterns in data .</p><ul><li>A scree plot represents a line plot of explained variance as a function of the number of components in increasing order ,based on it we decide how many components to keep .</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*hx6Y0M9zxNPW3eCdmMbASQ.png" /><figcaption>Scree plot</figcaption></figure><ul><li>Another important point is that datasets often have large dimensions, hundreds or even thousands of columns, which makes them difficult to visualize and interpret. Summarizing them into a few components has a great significance, as we can then conduct analysis on it and interpret the results, hence the term principal component analysis,We then use individual and variable maps, where the individual map is a projection of data points or observations onto components, and the variable map is a representation of the projection of variables onto another basis.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*PYp6rz9AtllAmnyE7svrcA.png" /><figcaption><a href="https://user.oc-static.com/upload/2018/05/28/15275136646823_F1F2.png">https://user.oc-static.com/upload/2018/05/28/15275136646823_F1F2.png</a></figcaption></figure><ul><li>The second plot is the projection of variables. The method used to find these projections is similar to the first one. It’s just another way to view the matrix. In this case, data points are not the observations, but rather, the variables are used as the data. To create this plot, you simply perform the same steps outlined previously, but with the transpose of the matrix, rather than the matrix itself,you should keep in mind that Interpreting these plots individually is not appropriate as one is reliant on the other.</li><li>There are some mathematical formulas for transitioning between the two analyses, the analysis of observations and the analysis of variables. When you calculate a projection in one of them, the other can be found using these formulas. This is predictable because you are working with the same matrix. For more information, you can check this : <a href="https://pca4ds.github.io/formulas-for-pca.html">https://pca4ds.github.io/formulas-for-pca.html</a></li><li>Using PCA in time-series analysis can uncover important patterns or structure in the data that can guide the modeling and analysis steps. The goal is often to filter out noise and random patterns, and highlight useful signal. The following code in python illustrates this concept</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JggCLBe99JR_TA96Fi5r7w.png" /><figcaption>PCA performed on time series data</figcaption></figure><p>result of noise reduction :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*-AN0JTvuOzGtpu2v9QscgQ.png" /><figcaption>noise reduction</figcaption></figure><ul><li>PCA is an effective way of speeding up the training process without compromising on accuracy. Instead of training on many variables and taking a lot of time, PCA can be used. Some training algorithms, particularly when working with big datasets, require significant computational resources. Here is a straightforward example of how PCA can be used in a logistic regression model applied to the well-known ‘digits’ dataset.”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*s6glBDoYUSU8sqFQx7DyTQ.png" /><figcaption>logistic regression model on digits dataset with PCA</figcaption></figure><p>In the previous step, we loaded the digits dataset from sklearn, reshaped and scaled the data, and then divided it into train and test sets. We applied logistic regression to the first model and added PCA to the second model, retaining 80% of the data’s variance. By comparing the computation times and performance of both models, we found that PCA reduced the training time while maintaining a similar level of performance. The impact on training time when using PCA in larger datasets would be substantial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*FN7IKihO7xMOkCzzvjpW0A.png" /><figcaption>time elapsed and score of the two models</figcaption></figure><ul><li>PCA can be helpful when model interpretability is not a priority. because one of the downsides of PCA is that original variables lose their identity and become hard to interpret. Instead, we have components that are a combination or summary of these variables. For example, in linear regression, when PCA-transformed data is used, it becomes impossible to tell how the response variable will change with a 1 unit change of the variable .</li><li>It reduces overfitting in data, because one of the main causes of overfitting is having a complex model with many features, and it is commonly accepted that good models generalize well the data and they have less complexity .</li></ul><h3>V-Basic implementation of PCA :</h3><ul><li>Implementing PCA is easy in Python or any other programming language, as long as you have a basic understanding of loops, matrix, and scalar product,in order to implement it you should understand how it works we’ll see some basic operations to perform so we can understand this concept,Using the matrix A we previously mentioned, which has a dimension of (m,3), if we calculate its covariance matrix, we get a matrix of size (3,3). The eigenvectors of this matrix, e1,e2 and e3, can be easily found by utilizing numpy’s ‘linalg’ module” ,each eigen vector has the dimension (3,1).</li></ul><p>let’s take e1 as an example it has the form :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*j0gPwQHU59N4mdBIiBK9lw.png" /><figcaption>eigen vector</figcaption></figure><p>the projection of a given data point :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*6GaQuKiqq3eMJ_Qwpdldiw.png" /><figcaption>single observation</figcaption></figure><ul><li>on axis 1 is simply :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*bFzovhqYIkmXy-Og9s4m7Q.png" /></figure><ul><li>by computing the projections of this data point onto the three principal components, we obtain the following coordinates/values:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j3j0YdALiKccEY44i1-qvg.png" /><figcaption>Projection of observation i on the three components</figcaption></figure><p>For all the observations in data , we just compute the matrix product :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*ieX2-mpB9W7XsJIJYnDrQg.png" /><figcaption>projection of observations on components</figcaption></figure><ul><li>The given code will produce a matrix with a reduced dimensionality, based on the number of components specified and an input matrix P. Additionally, it will output the eigenvalues and corresponding eigenvectors, sorted in descending order based on their variance importance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*l5E9y72p5VvuACVcTH6FQQ.png" /><figcaption>Basic PCA implementation with python</figcaption></figure><p><em>-Note : Before using PCA, scale your data to avoid misleading results especially when you have data with different scales .</em></p><h3>V-Conclusion :</h3><ul><li>In conclusion, Variance can be both beneficial and detrimental in data analysis. Data with no variance holds little value, as it lacks patterns to be utilized. Conversely, data with high variability can be difficult to model. PCA can aid in these situations by simplifying the data, highlighting meaningful patterns, and other useful features. It’s important to note that each method has its advantages and disadvantages.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fd948ae05b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>