<?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 Mark Onyango on Medium]]></title>
        <description><![CDATA[Stories by Mark Onyango on Medium]]></description>
        <link>https://medium.com/@mark.onyango_95482?source=rss-3d56bcc1d665------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*08j_l9tkPZ6fidt9</url>
            <title>Stories by Mark Onyango on Medium</title>
            <link>https://medium.com/@mark.onyango_95482?source=rss-3d56bcc1d665------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 22:54:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mark.onyango_95482/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[You Don’t Need Kubernetes: The Case for Right-Sized Architecture]]></title>
            <link>https://medium.com/@mark.onyango_95482/you-dont-need-kubernetes-the-case-for-right-sized-architecture-34bcb6f2ed0b?source=rss-3d56bcc1d665------2</link>
            <guid isPermaLink="false">https://medium.com/p/34bcb6f2ed0b</guid>
            <category><![CDATA[codewithmark]]></category>
            <dc:creator><![CDATA[Mark Onyango]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 19:05:46 GMT</pubDate>
            <atom:updated>2026-10-14T19:05:46.065Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rycGruNVmpV4wL_RqrT4uw.jpeg" /></figure><p>There is a particular kind of engineering meeting that happens at startups all over the world. Someone opens a whiteboard and starts drawing boxes. Load balancers. API gateways. Message queues. Multiple availability zones. A service mesh. Kubernetes clusters with auto-scaling node pools. By the end of the session, the architecture looks like something that would make a Netflix engineer nod appreciatively.</p><p>The product has twelve users.</p><p>This article is about that meeting why it happens, why it is usually the wrong call and how to think about system design in a way that actually matches where your business is.</p><p>Before we talk about what the right architecture looks like, it is worth understanding why smart people keep building the wrong one.</p><p>The first reason is that complex architecture is genuinely interesting to build. Kubernetes, service meshes, event-driven microservices these are intellectually stimulating problems. They attract strong engineers and strong engineers want to work on hard problems. There is nothing dishonest about this, it is just human nature and it leads to systems that are harder to justify than to build.</p><p>The second reason is a misreading of what success looks like. We study FAANG architecture because those companies have published it, spoken about it at conferences and made it aspirational. What we do not see as clearly is the ten-year journey that produced it. Amazon’s services architecture did not start as microservices. It started as a monolith, became distributed out of necessity as the company scaled and evolved into what it is today under the pressure of real traffic from hundreds of millions of users. The architecture followed the business. The business did not wait for the architecture.</p><p>The third reason is fear. Fear of having to rewrite everything when scale arrives. Fear of being the engineer who shipped a monolith. Fear of technical debt. These fears are real but they lead to a specific kind of premature optimization that trades one problem (future scaling) for another more immediate one: complexity your team cannot maintain, operational overhead that slows you down and infrastructure costs that drain a runway that should be funding growth.</p><p>Let us talk about numbers because the conversation about architecture should always start with them.</p><p>Under 1,000 users, you are not solving a scaling problem. You are solving a product problem. Does this thing work? Do people want it? Does it do what they need? The constraint at this stage is almost never infrastructure. It is product-market fit.</p><p>Under 10,000 users, a single well-provisioned server can handle most workloads. A t3.medium on AWS, two CPUs, four gigabytes of RAM, can serve tens of millions of HTTP requests per day if the application is reasonably efficient. PostgreSQL on the same instance can handle thousands of concurrent connections. You will run into application bugs long before you run into infrastructure limits.</p><p>Under 100,000 users, you might start needing to think about a read replica for your database, a CDN for static assets and a caching layer for expensive queries. This is still not Kubernetes territory. This is “add a Redis instance and a CloudFront distribution” territory.</p><p>The companies that needed Kubernetes from day one are companies that had massive traffic from day one e.g a viral consumer app, a platform with a large pre-existing user base or a B2B product with enterprise contracts that guaranteed immediate load. Those situations exist. They are not your situation unless you have evidence that they are.</p><p>Complexity has a price that is easy to underestimate when you are designing on a whiteboard.</p><p>Operational overhead is the most obvious one. Every component you add is a component that can break, needs monitoring, needs someone to understand it when it does break at 2am and needs to be updated when security patches come out. A Kubernetes cluster is not just a cluster. It is node upgrades, pod scheduling decisions, network policies, persistent volume claims, ingress controllers, certificate managers and a learning curve for every engineer who joins the team.</p><p>Debugging difficulty compounds with every layer. A monolith that returns a 500 error gives you a stack trace in one place. A microservices architecture that returns a 500 error requires you to correlate traces across multiple services, check which service failed, determine whether the failure was a network timeout or an application error and figure out whether the retry logic introduced a duplicate write. This is solvable distributed tracing exists for this reason but it is meaningfully harder and at small scale you are absorbing that cost without the scale benefits that justify it.</p><p>Deployment complexity is the third cost. A single application deployed to a single server can be updated in thirty seconds with a git pull and a process restart. A Kubernetes deployment involves building a container image, pushing it to a registry, updating a manifest, applying the manifest, waiting for a rolling update and checking that health checks pass. With proper CI/CD this becomes automated but setting up that automation is itself a non-trivial investment of engineering time.</p><p>The opportunity cost is what kills startups. Every week spent configuring infrastructure is a week not spent talking to users, building features or fixing the things that are actually preventing growth. At the early stage, the most expensive resource you have is engineering time. Spending it on infrastructure your twelve users will never stress is a choice with a real cost.</p><h3>So What Should You Build?</h3><p>The answer depends on where you are and it changes as you grow. Here is a framework for thinking about it by stage.</p><p><strong>Zero to one thousand users: the boring stack</strong></p><p>Deploy a monolith. One application, one database, one server. Use a managed database if you can afford it — RDS on AWS, Cloud SQL on GCP — so you get automated backups and point-in-time recovery without operating a database yourself. Put your static assets behind a CDN. Use a process manager like PM2 or systemd to keep your application running and restart it if it crashes. Set up basic monitoring — CPU, memory, disk and a simple uptime check. That is it.</p><p>This stack is genuinely capable of handling thousands of users and is trivially simple to operate. When something breaks, you look in one place. When you want to deploy, it is one command. When a new engineer joins, they can understand the entire system in an afternoon.</p><p><strong>One thousand to fifty thousand users: selective additions</strong></p><p>At this point you start adding components where you have evidence of need not where you anticipate it. Database getting slow on read-heavy queries? Add a read replica. Serving a lot of images or large files? Move them to S3 and put CloudFront in front. Sessions or expensive computations repeating? Add Redis. Application server getting load? Add a second instance behind a load balancer.</p><p>Notice the pattern: you identify a specific bottleneck and add the minimum component that addresses it. You are not adding API gateways because API gateways are in the architecture diagrams you admire. You are adding a read replica because your slow query log is showing you that reads are the problem.</p><p><strong>Fifty thousand users and beyond: earned complexity</strong></p><p>This is where Kubernetes, microservices and multi-region deployments start to make sense not because they are modern but because the problems they solve are the problems you now actually have. Your deployment frequency is high enough that rolling updates matter. Your traffic is high enough that single-region availability is a real business risk. Your team is large enough that separate services allow independent deployments without coordination overhead.</p><p>Even here, the rule is the same: add complexity proportional to the problem it solves. Splitting a monolith into microservices is a significant investment. The question is always whether the benefit independent scaling, independent deployment, isolated failure domains is worth the operational cost at your current scale.</p><p><strong>Kubernetes</strong> is cluster orchestration designed for running many services at scale across many nodes. If you have one service, it is unnecessary. A single EC2 instance with a process manager or a managed container service like AWS App Runner or Google Cloud Run, gives you most of what you need at a fraction of the operational complexity.</p><p><strong>Multi-AZ from day one</strong> makes sense for databases because managed database failover is cheap and automated. It does not make sense for application servers when you have traffic that a single server handles comfortably. The cost doubles, the complexity increases and the benefit surviving an availability zone failure only matters when your traffic requires high availability. Most early-stage products can tolerate a few minutes of downtime during an AZ failure. Your SLA with your twelve users does not require five nines.</p><p><strong>API gateways</strong> are useful when you have multiple services that need centralized authentication, rate limiting and routing. With one service, your application handles all of that. Adding an API gateway adds a network hop, another service to monitor, another configuration to maintain and another potential failure point.</p><p><strong>Message queues for everything</strong> makes sense when your system has genuinely asynchronous workflows with high volume like sending emails, processing uploads, running background jobs. It does not make sense as a default communication pattern between components that could just call each other directly. A BullMQ queue for email sending is sensible. An event bus between three services that all live in the same codebase is premature abstraction.</p><p><strong>Microservices from the start</strong> is perhaps the most common mistake. The main benefit of microservices is that separate teams can develop, deploy, and scale services independently. If you have one team or two engineers you get the operational overhead of microservices with none of the organizational benefit. A well-structured monolith with clear module boundaries gives you most of the architectural benefit and is dramatically easier to operate. When you genuinely need to split, you split along the seams you have already defined.</p><h3>When You Actually Need to Scale Up</h3><p>There are signals, not timelines. Watch for these:</p><p>Your database is the bottleneck queries are slow despite indexes, connection counts are high, CPU on the database instance is consistently above 70%. This is the time for a read replica or a caching layer.</p><p>Your deployment is causing downtime users notice when you deploy because the server restarts. This is the time for a second instance behind a load balancer and a proper deployment pipeline.</p><p>Your team cannot deploy independently engineers are blocking each other because changes in one area affect another and coordinating deployments is becoming a project in itself. This is the signal that you might be ready to extract a service.</p><p>Your single region is a real business risk , you have SLAs with paying customers that require uptime guarantees your single-region setup cannot meet. This is the time for multi-region not because it is on the architecture diagram but because the business requires it.</p><p>The common thread is that each of these signals is concrete and measurable. You do not move to a more complex architecture because you expect to need it. You move because the evidence is in front of you.</p><p>The teams that tend to build durable, successful systems early are not the ones who copy the most sophisticated architecture they can find. They are the ones who keep asking a specific question: what is the simplest thing that solves the problem in front of us?</p><p>Basecamp has run one of the most successful project management products in the world for over two decades on an architecture that would make a distributed systems engineer wince. No microservices, no Kubernetes, minimal infrastructure. The product grew because the team spent their engineering time on the product, not the infrastructure.</p><p>Stack Overflow served hundreds of millions of monthly users for years on fewer than ten physical servers. The architecture was simple because the team were rigorous about understanding where their bottlenecks actually were and solving only those.</p><p>These are not arguments against sophisticated architecture. They are arguments that sophistication should be earned by necessity, not chosen by aspiration.</p><p>Start with a boring stack. Know what your actual user count is. Know what your actual bottlenecks are. Add complexity only when you have evidence that the simpler solution is no longer adequate.</p><p>The goal of architecture is not to be impressive on a whiteboard. It is to keep your product running, allow your team to ship quickly and give the business the best possible chance of surviving long enough to reach the scale where the complex architecture genuinely earns its keep.</p><p>Most products never reach that scale. The ones that do almost never arrived there with the architecture they started with. They built something simple, got users, found the bottlenecks and fixed them. That is how systems and companies actually grow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34bcb6f2ed0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Subnetting Made Easy For Cloud Engineer Before Touching a VPC]]></title>
            <link>https://medium.com/@mark.onyango_95482/subnetting-made-easy-for-cloud-engineer-before-touching-a-vpc-4a55c416c38f?source=rss-3d56bcc1d665------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a55c416c38f</guid>
            <category><![CDATA[codewithmark]]></category>
            <dc:creator><![CDATA[Mark Onyango]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 19:27:56 GMT</pubDate>
            <atom:updated>2026-10-07T19:27:56.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R2iT2I2RBGZeyNzwFy9zRQ.png" /></figure><p>When I set up my first VPC on AWS, I ran into a wall I did not expect. Not the console. Not the IAM permissions. The subnetting. Specifically, the moment where I had to type a CIDR block and genuinely did not know what I was typing or why.</p><p>If you are a developer who came to cloud engineering without a networking background, this article is for you. Subnetting is one of those foundational topics that nobody teaches you until you are already staring at it in production. By the end of this, you will understand what the numbers mean, how to calculate them and how to apply that knowledge directly when designing a VPC.</p><p>Every time you create a VPC, you assign it a CIDR block something like 10.0.0.0/16. Every time you create a subnet inside that VPC, you carve a smaller CIDR block out of it, something like 10.0.1.0/24.</p><p>If you do not understand how those numbers work, you end up:</p><ul><li>Creating subnets that are too small and running out of IP addresses as your application grows</li><li>Overlapping CIDR ranges when trying to peer two VPCs, making peering impossible</li><li>Wasting large blocks of address space on tiny subnets</li><li>Misunderstanding why certain IPs in your subnet are unusable</li></ul><p>Subnetting is not optional knowledge for cloud work. It is foundational.</p><p>An IPv4 address is 32 bits written as four decimal numbers separated by dots.</p><p>192.168.1.10</p><p>In binary that is: 11000000.10101000.00000001.00001010</p><p>Each of the four sections is called an octet because it is 8 bits. Each octet can hold a value from 0 to 255.</p><p>That is it. Every IP address you will ever work with is just 32 binary digits presented in a friendlier format.</p><p>Here is the core concept of subnetting: in any IP address, some bits identify the network and some bits identify the host — a specific device on that network.</p><p>The slash notation, the /16 or /24 after an IP address, tells you how many of the 32 bits are network bits. The rest are host bits.</p><p>10.0.0.0/16</p><p>Network bits: 16, the first 16 bits identify the network Host bits: 16, the remaining 16 bits identify hosts on that network</p><p>10.0.0.0/24</p><p>Network bits: 24 Host bits: 8</p><p>Think of it like a postal address. The network bits are your city and street. The host bits are your house number. Every house on the same street shares the same street address, they are on the same network.</p><h3>The Subnet Mask</h3><p>The subnet mask is another way of expressing the same information. Instead of /24, you might see 255.255.255.0. They mean the same thing.</p><p>/24 = 255.255.255.0</p><p>In binary: 11111111.11111111.11111111.00000000</p><p>The 1s represent network bits. The 0s represent host bits.</p><p>The 1s in the subnet mask mark the network portion. The 0s mark the host portion. You will see both notations in AWS — the console accepts CIDR notation (/24) and some tools display the full subnet mask.</p><p>This is where a lot of people lose track of usable IPs.</p><p>For any subnet, two addresses are reserved and cannot be assigned to any host:</p><p>The Network Address is the very first address in the subnet. It identifies the subnet itself. All host bits are 0.</p><p>The Broadcast Address is the very last address in the subnet. It is used to send a message to every device on the network simultaneously. All host bits are 1.</p><p>Subnet: 192.168.1.0/24</p><p>Network address: 192.168.1.0 — host bits all zero Broadcast address: 192.168.1.255 — host bits all one Usable range: 192.168.1.1 to 192.168.1.254</p><p>The formula is straightforward:</p><p>Usable IPs = 2^(host bits) — 2</p><p>You subtract 2 for the network address and broadcast address.</p><p>In AWS it is actually 5 addresses reserved per subnet, not 2. AWS reserves the network address, broadcast address and three more for internal routing, DNS and future use. So for a /24 subnet in AWS you get 251 usable IPs, not 254. Keep this in mind — it catches people out when subnet planning.</p><h3>The Magic Number Method</h3><p>When you need to figure out subnet boundaries quickly without converting everything to binary, the magic number method is the fastest approach. This is what network engineers use in their head.</p><p>The magic number is always: 256 minus the subnet mask octet value</p><p>Let me show you with an example.</p><p>You have the subnet 10.0.1.0/26.</p><p>A /26 means 26 network bits, which means the subnet mask is 255.255.255.192.</p><p>The last octet in binary: 11000000 = 192 in decimal.</p><p>The magic number for the last octet: 256 minus 192 = 64</p><p>This means subnets in this range increment in blocks of 64:</p><p>Block 1: 10.0.1.0 to 10.0.1.63 Block 2: 10.0.1.64 to 10.0.1.127 Block 3: 10.0.1.128 to 10.0.1.191 Block 4: 10.0.1.192 to 10.0.1.255</p><p>For 10.0.1.0/26:</p><ul><li>Network address: 10.0.1.0</li><li>Broadcast address: 10.0.1.63</li><li>Usable range: 10.0.1.1 to 10.0.1.62</li></ul><p>The magic number tells you the block size. Once you know the block size, you can instantly identify where any subnet starts and ends and whether two subnets overlap.</p><p>Another example: 172.16.5.128/25</p><p>Subnet mask last octet: 128 Magic number: 256 minus 128 = 128</p><p>Blocks increment by 128:</p><p>Block 1: 172.16.5.0 to 172.16.5.127 Block 2: 172.16.5.128 to 172.16.5.255</p><p>So 172.16.5.128/25 covers 172.16.5.128 to 172.16.5.255.</p><ul><li>Network address: 172.16.5.128</li><li>Broadcast address: 172.16.5.255</li><li>Usable range: 172.16.5.129 to 172.16.5.254</li></ul><h3>Private IP Ranges</h3><p>When designing a VPC you should always use private IP address ranges, addresses that are not routed on the public internet.</p><p>The three private ranges defined by RFC 1918 are:</p><p>10.0.0.0 to 10.255.255.255 — the 10.0.0.0/8 range 172.16.0.0 to 172.31.255.255 , the 172.16.0.0/12 range 192.168.0.0 to 192.168.255.255 and the 192.168.0.0/16 range</p><p>For VPC design, 10.0.0.0/8 gives you the most address space to work with. Most AWS architectures start with something like 10.0.0.0/16 for the VPC and curve /24 subnets out of it for each availability zone and tier.</p><p>Here is how you would think through a real VPC design for a three-tier application across two availability zones.</p><p>VPC CIDR: 10.0.0.0/16</p><p>This gives you 65,536 addresses to work with. Plenty of room.</p><p>Subnets — /24 per tier per AZ:</p><p>Public Subnet AZ-1: 10.0.1.0/24–251 usable in AWS Public Subnet AZ-2: 10.0.2.0/24</p><p>Private Subnet AZ-1: 10.0.10.0/24 Private Subnet AZ-2: 10.0.11.0/24</p><p>Database Subnet AZ-1: 10.0.20.0/24 Database Subnet AZ-2: 10.0.21.0/24</p><p>Why this works:</p><p>All subnets fit inside 10.0.0.0/16 with no overlaps. The numbering is readable — the third octet tells you the tier. Each subnet has 251 usable IPs, more than enough for most workloads. And the 10.0.0.0/16 block has space for many more subnets as the system grows.</p><p>Checking for overlaps using the magic number:</p><p>Is 10.0.1.0/24 inside 10.0.0.0/16?</p><p>/16 magic number applied to the second octet: 256 minus 255 = 1. Blocks increment by 1.</p><p>The /16 block covers 10.0.0.0 to 10.0.255.255. Yes, 10.0.1.0 is inside it. No overlap.</p><p>Do 10.0.1.0/24 and 10.0.2.0/24 overlap?</p><p>/24 magic number applied to the third octet: 256 minus 255 = 1. Blocks increment by 1. Block 1: 10.0.1.0 to 10.0.1.255 Block 2: 10.0.2.0 to 10.0.2.255</p><p>They are sequential, not overlapping. Good.</p><h3>The AWS-Specific Rules to Remember</h3><p>5 reserved IPs per subnet, not 2.</p><p>AWS reserves the first 4 addresses and the last 1 in every subnet.</p><p>For 10.0.1.0/24:</p><ul><li>10.0.1.0 — Network address</li><li>10.0.1.1 — AWS VPC router</li><li>10.0.1.2 — AWS DNS</li><li>10.0.1.3 — Reserved for future use</li><li>10.0.1.255 — Broadcast address</li></ul><p>Usable: 10.0.1.4 to 10.0.1.254 = 251 addresses.</p><p>Minimum subnet size is /28.</p><p>AWS does not allow subnets smaller than /28. A /28 gives you 16 addresses minus 5 reserved = 11 usable. That is the floor.</p><p>VPC peering requires non-overlapping CIDRs.</p><p>If you ever need to connect two VPCs for microservices, multi-environment setups or shared services, their CIDR blocks cannot overlap. This is where the magic number method saves you. Check for overlap before you create, not after because you cannot change a VPC’s CIDR block after creation without significant pain.</p><p>/16–65,536 addresses — 65,531 usable in AWS /20–4,096 addresses — 4,091 usable in AWS /24–256 addresses — 251 usable in AWS /25–128 addresses — 123 usable in AWS /26–64 addresses — 59 usable in AWS /27–32 addresses — 27 usable in AWS /28–16 addresses — 11 usable in AWS</p><p>Subnetting feels intimidating because it sits at the intersection of binary maths and networking theory but in practice you only need four things:</p><p>The prefix tells you how many bits are network bits, the rest are host bits.</p><p>Usable IPs = 2^(host bits) minus 5 in AWS.</p><p>The magic number — 256 minus the relevant subnet mask octet, gives you the block size instantly.</p><p>Never let two subnets overlap and always leave room to grow.</p><p>The next time you open the VPC console and see the CIDR input, you will know exactly what you are typing and why. That is the difference between configuring infrastructure and understanding it.</p><p>Happy coding!!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a55c416c38f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure for AWS Developers: Same Cloud, Different Language]]></title>
            <link>https://medium.com/@mark.onyango_95482/azure-for-aws-developers-same-cloud-different-language-f0f73378111a?source=rss-3d56bcc1d665------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0f73378111a</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[codewithmark]]></category>
            <dc:creator><![CDATA[Mark Onyango]]></dc:creator>
            <pubDate>Thu, 01 Oct 2026 07:16:49 GMT</pubDate>
            <atom:updated>2026-10-01T07:16:49.414Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PlPjpA-NtYdodoteNM9HDw.jpeg" /></figure><p>You already know how cloud works. You have provisioned servers, configured networks, stored files and connected databases. You understand regions, availability zones and why you never hardcode credentials.</p><p>Azure does not ask you to learn cloud from scratch. It asks you to learn a new vocabulary for things you already understand. That is what this article is about, a surface-level map from what you know in AWS to where it lives in Azure.</p><p>Before the comparisons, there is one Azure concept you will not find in AWS: <strong>Resource Groups</strong>.</p><p>Every resource you create in Azure: a VM, a database, a storage account must belong to a Resource Group. Think of it as a mandatory folder that groups related resources for one application or environment. You can delete the entire group in one action, apply permissions to everything inside it at once and filter billing by it.</p><p>Once it clicks, it actually makes more sense than AWS’s looser approach. It just feels unfamiliar the first time.</p><p><strong>EC2 → Azure Virtual Machine</strong></p><p>Same concept. You pick an OS, choose a size, configure networking and pay for compute time. The instance sizing names are different, Azure uses series like B-series for burstable (your T-series equivalent) and D-series for general purpose (your M-series equivalent) but the underlying idea is identical.</p><p><strong>Auto Scaling Group → VM Scale Set</strong></p><p>Define a VM template, set min and max counts, configure scaling rules. Works the same way.</p><p><strong>Lambda → Azure Functions</strong></p><p>Serverless compute triggered by HTTP, queues, timers or events. The Consumption Plan is the true serverless equivalent scales to zero, pay per execution.</p><p><strong>ECS Fargate → Azure Container Apps</strong></p><p>Serverless containers without managing the underlying infrastructure.</p><p><strong>EKS → AKS (Azure Kubernetes Service)</strong></p><p>Managed Kubernetes. Same concept, different console.</p><p><strong>Elastic Beanstalk → Azure App Service</strong></p><p>PaaS hosting for web applications. Push code or a container image and Azure handles the runtime. It has deployment slots built in Azure’s version of blue/green deployments.</p><h3>Networking</h3><p><strong>VPC → Virtual Network (VNet)</strong></p><p>Your isolated network in the cloud. Subnets, route tables and peering all exist in Azure under the same concepts and nearly the same names.</p><p><strong>Security Group → Network Security Group (NSG)</strong></p><p>Works almost identically. One difference worth knowing: an NSG can attach to a subnet (applies to all resources inside it) or to a specific network interface. In AWS, Security Groups attach at the network interface level only.</p><p><strong>Internet Gateway → nothing</strong></p><p>This one trips up AWS engineers. In AWS, a subnet is only public if you explicitly attach an Internet Gateway. In Azure, internet access for public resources is implicit, there is no IGW resource to create. You control access through NSGs and Azure Firewall instead.</p><p><strong>ALB → Application Gateway</strong></p><p>Layer 7 load balancing with path-based routing, SSL termination and WAF capabilities.</p><p><strong>Route 53 → Azure DNS + Traffic Manager</strong></p><p>Azure DNS handles your zones and records. Traffic Manager handles routing policies, latency-based, weighted, failover, geographic. They are separate services where AWS combines them in Route 53.</p><p><strong>VPC Endpoints → Private Endpoints</strong></p><p>Keep traffic between your VNet and Azure services off the public internet. Same concept.</p><h3>Storage</h3><p><strong>S3 → Azure Blob Storage</strong></p><p>Object storage. Buckets are called Containers. Objects are called Blobs. Hot, Cool and Archive tiers map to S3 Standard, Standard-IA, and Glacier.</p><p>One structural difference: in Azure you first create a Storage Account, then create containers inside it. A Storage Account is also the parent for file shares, queues, and table storage, it is a unified namespace for multiple storage services.</p><p><strong>S3 Presigned URLs → Shared Access Signatures (SAS)</strong></p><p>Time-limited, permission-scoped URLs for sharing access to a specific resource without exposing credentials. Same concept, different name.</p><p><strong>EFS → Azure Files</strong></p><p>Managed file shares over SMB or NFS. Useful when VMs need a shared network drive.</p><p><strong>SQS → Azure Storage Queues / Service Bus</strong></p><p>Azure has two queue options. Storage Queues are simple and cheap your basic SQS equivalent. Service Bus is the premium option with topics, subscriptions, dead-letter queues and sessions , closer to SQS and SNS combined.</p><h3>Databases</h3><p><strong>RDS PostgreSQL / MySQL → Azure Database for PostgreSQL / MySQL</strong></p><p>Fully managed relational databases. Same concepts: high availability, read replicas, automated backups, maintenance windows. The Flexible Server deployment mode is the one to use, it is the current recommended option.</p><p>One thing that catches AWS engineers: the connection username includes the server name. Instead of just username, you use username@servername. Small detail, real frustration the first time.</p><p><strong>Aurora → Azure SQL Hyperscale</strong></p><p>Cloud-native database that separates compute from storage, scales read replicas independently, and handles very large datasets without the pain of traditional vertical scaling.</p><p><strong>DynamoDB → Cosmos DB</strong></p><p>Globally distributed NoSQL database. Tables are called Containers, items are called Documents. Capacity is measured in Request Units (RUs) instead of RCUs and WCUs — a different abstraction for the same idea of provisioned throughput.</p><p>Cosmos DB also supports a MongoDB-compatible API, which means you can point a standard MongoDB driver at it without rewriting your query layer.</p><p><strong>ElastiCache Redis → Azure Cache for Redis</strong></p><p>Direct 1:1 mapping. Managed Redis. Point your ioredis or any Redis client at the Azure Cache endpoint exactly as you would with ElastiCache.</p><h3>Identity and Access</h3><p>This is where Azure diverges most from AWS and is worth understanding clearly.</p><p>AWS IAM handles everything in one place who can authenticate and what they are allowed to do.</p><p><strong>Azure splits this across two systems:</strong></p><p>Azure Active Directory (now called Entra ID) handles authentication — users, groups and service identities live here.</p><p>Azure RBAC handles authorisation — what those identities are allowed to do with Azure resources. You assign a built-in role (like Storage Blob Data Reader) to an identity at a specific scope (subscription, resource group, or individual resource).</p><p><strong>EC2 Instance Profile → Managed Identity</strong></p><p>Instead of storing credentials in your application, you assign a Managed Identity to your VM or App Service. That identity gets permissions through RBAC. Your code calls Azure services without credentials in the code or environment variables, the same pattern as using an instance profile with the AWS SDK.</p><h3>A Quick Reference</h3><p>AWS → Azure</p><p>EC2 → Virtual Machine Auto Scaling Group → VM Scale Set Lambda → Azure Functions ECS Fargate → Container Apps EKS → AKS Elastic Beanstalk → App Service VPC → Virtual Network (VNet) Security Group → Network Security Group Internet Gateway → (implicit, no resource) NAT Gateway → NAT Gateway Route 53 → Azure DNS + Traffic Manager ALB → Application Gateway S3 → Blob Storage EFS → Azure Files SQS → Storage Queue / Service Bus SNS → Service Bus Topics RDS → Azure Database for PostgreSQL/MySQL Aurora → Azure SQL Hyperscale DynamoDB → Cosmos DB ElastiCache → Azure Cache for Redis IAM Role → Managed Identity IAM Policy → RBAC Role Assignment CloudWatch → Azure Monitor CloudTrail → Azure Activity Log CloudFormation → Bicep / ARM Templates Secrets Manager → Azure Key Vault Parameter Store → Azure App Configuration</p><h3>Where to Start</h3><p>The fastest way to get comfortable is to rebuild something you already have running on AWS. Take a simple project eg a server, a database, some file storage and deploy the equivalent on Azure. The Azure portal’s guided creation flows are clear and surface the right options without hiding everything behind Advanced tabs.</p><p>The vocabulary is different. The concepts are the same. That is the main thing to hold onto.</p><p>Happy coding!!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0f73378111a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Git Safety Net: How Pre-Commit Hooks Protect Your Code Before It Leaves Your Machine]]></title>
            <link>https://medium.com/@mark.onyango_95482/the-git-safety-net-how-pre-commit-hooks-protect-your-code-before-it-leaves-your-machine-80f526e3a79c?source=rss-3d56bcc1d665------2</link>
            <guid isPermaLink="false">https://medium.com/p/80f526e3a79c</guid>
            <category><![CDATA[codewithmark]]></category>
            <dc:creator><![CDATA[Mark Onyango]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 17:54:10 GMT</pubDate>
            <atom:updated>2026-09-23T17:54:10.807Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bYE72ODdJFjS8ylteTTRfA.png" /></figure><h3>What Are We Learning and Why Does It Matter?</h3><p>There is a moment every developer has experienced where you run git push, the code lands on GitHub and then you see it. An API key sitting in plain text. A console.log(user.password) that made it into a pull request. A node_modules folder that turned your 2MB repository into a 200MB monster overnight.</p><p>These are not junior mistakes. They happen to experienced engineers at funded companies, on production systems, under deadline pressure. They happen because the human brain is fallible and git add .is dangerously easy to type.</p><p>What if your version control system could catch these things before they became anyone else’s problem?</p><p>That is exactly what <strong>pre-commit hooks</strong> do.</p><h3>What Is a Git Hook?</h3><p>Git has a built-in event system. Every time you perform an action like committing, pushing, merging, Git fires an event at a specific point in that process. A <strong>hook</strong> is a script you attach to that event.</p><p>A <strong>pre-commit hook</strong> runs the moment you type git commit, before Git records anything. If the script exits with a non-zero code (meaning something is wrong), the commit is blocked. If it exits cleanly, the commit goes through.</p><p>It is your last line of defence before code leaves your machine.</p><pre>You type: git commit -m &quot;add payment integration&quot;<br>                        ↓<br>          Pre-commit hook runs your checks<br>                        ↓<br>         ┌──────────────────────────────┐<br>         │  All checks pass?            │<br>         │  → Commit proceeds           │<br>         │                              │<br>         │  Any check fails?            │<br>         │  → Commit is blocked         │<br>         │  → You see exactly why       │<br>         └──────────────────────────────┘</pre><p>The hook lives at .git/hooks/pre-commit in your repository. It is a shell script. It runs on every commit, automatically, silently without you having to remember anything.</p><h3>Why This Is a Production Skill</h3><p>Let me tell you what actually happens when secrets reach GitHub.</p><p>GitHub’s public repositories are continuously scraped by automated bots — some operated by security researchers, others by malicious actors. In 2022, a study found that thousands of secrets are committed to GitHub every day. AWS has their own detection system that monitors for leaked IAM keys and notifies account owners, but that notification comes after the key is already public. In the time between your push and AWS’s email, your key could have been picked up, used to spin up EC2 instances, mine cryptocurrency and rack up thousands of dollars in charges all billed to you.</p><p>In a professional team setting, a committed .env file with database credentials is not just an embarrassment. It is a security incident. It triggers an incident response, credential rotation across all environments, a post-mortem report and depending on your industry, possible compliance and regulatory implications.</p><p>Pre-commit hooks exist precisely to prevent this class of problem from ever reaching the repository. They are not optional tooling in a serious engineering team, they are infrastructure.</p><h3>The Checks That Matter in Production</h3><p>Here are the categories of problems pre-commit hooks commonly guard against, and why each one matters.</p><h3>1. Secrets and Credentials</h3><p>The most critical check. This covers:</p><ul><li>.env files staged for commit</li><li>AWS access key patterns (AKIA followed by 16 uppercase alphanumeric characters)</li><li>Private key file headers (-----BEGIN RSA PRIVATE KEY-----)</li><li>Generic secret patterns: password=, secret=, api_key=, token= hardcoded in source files</li><li>Certificate files (.pem, .p12, .key)</li></ul><p><strong>Real world example:</strong> A developer working on an M-Pesa integration hardcodes their Daraja API consumer secret directly in a test file to make debugging faster. They forget it is there. Two weeks later, during a code review for an unrelated feature, the file gets committed. The consumer secret is now in the repository’s history permanently — even after deletion, it lives in every git clone.</p><h3>2. Files That Should Never Be Tracked</h3><ul><li>node_modules/ — this means .gitignore was missed or overridden with git add -f</li><li>dist/ or build/ folders — compiled output rebuilt from source on every deploy</li><li>.sql database dumps — often contain real user data</li><li>Log files (.log) that grew large and got caught in a git add .</li><li>Binary files over a size limit — images, zip files, build artifacts</li></ul><p><strong>Real world example:</strong> A developer adds an npm package, forgets the .gitignore entry and does git add .. The commit adds 47,000 files and increases the repository size by 180MB. Every team member who pulls now has to download those 180MB. Cloning the repository in CI takes 4 minutes instead of 15 seconds. This compounds with every future npm install.</p><h3>3. Debug Statements Left in Code</h3><ul><li>console.log() containing sensitive values</li><li>debugger statements — pause execution in browser dev tools</li><li>print() statements in Python printing internal data</li><li>echo statements in PHP printing request variables</li></ul><p><strong>Real world example:</strong> During debugging of a payment flow, a developer adds console.log(&#39;Payment payload:&#39;, JSON.stringify(payload)) where payload contains the user&#39;s card details. This makes it through code review because the reviewer is focused on business logic. The log runs in production, sending card data to your logging infrastructure which may not be PCI-DSS compliant. Now you have a data breach.</p><h3>4. Commit Message Quality</h3><ul><li>Empty commit messages</li><li>Messages too short to be meaningful: fix, wip, test, asdf</li><li>Messages not following your team’s convention (Conventional Commits: feat:, fix:, chore:)</li></ul><p><strong>Real world example:</strong> Six months after a feature ships, a bug is reported. The engineer investigating runs git log and sees fifty commits with messages like update, fix thing, try this. Tracing which commit introduced the regression takes three hours instead of ten minutes. A good commit message costs you ten seconds to write. A bad one costs your team hours.</p><h3>5. Dependency Inconsistencies</h3><ul><li>package.json changed but package-lock.json not updated someone installed without the lockfile</li><li>Both yarn.lock and package-lock.json present, team is using two package managers</li><li>.env.example not updated when .env gains a new variable, the next developer to clone has no idea the variable exists and gets a cryptic runtime error</li></ul><h3>Building It: The Bash Script Approach</h3><p>For developers who want full control, you can write a pre-commit hook as a plain bash script. This has no dependencies, it works in any environment that has Git and bash.</p><p>Create the file at .git/hooks/pre-commit:</p><pre>#!/bin/bash<br># hooks/pre-commit — blocks commits with likely secrets or oversized files<br>set -e<br>staged=$(git diff --cached --name-only --diff-filter=ACM)<br>blocked=0<br>for file in $staged; do<br>  # Check for secret patterns<br>  if git diff --cached -- &quot;$file&quot; | grep -qE &#39;AKIA[0-9A-Z]{16}|-----BEGIN (RSA|OPENSSH|PRIVATE) KEY-----|password\s*=\s*[&quot;\x27][^&quot;\x27]+[&quot;\x27]|secret\s*=\s*[&quot;\x27][^&quot;\x27]+[&quot;\x27]&#39;; then<br>    echo &quot;BLOCKED: possible secret in $file&quot;<br>    blocked=1<br>  fi<br>  # Block .env files<br>  if echo &quot;$file&quot; | grep -qE &#39;^\.env$|^\.env\.[a-z]+$&#39;; then<br>    echo &quot;BLOCKED: .env file staged - add it to .gitignore&quot;<br>    blocked=1<br>  fi<br>  # Block node_modules<br>  if echo &quot;$file&quot; | grep -q &#39;^node_modules/&#39;; then<br>    echo &quot;BLOCKED: node_modules staged - add node_modules/ to .gitignore&quot;<br>    blocked=1<br>  fi<br>  # Block oversized files (over 1MB)<br>  size=$(git cat-file -s &quot;$(git rev-parse &quot;:$file&quot;)&quot; 2&gt;/dev/null || echo 0)<br>if [ &quot;$size&quot; -gt 1000000 ]; then<br>    echo &quot;BLOCKED: $file is $(($size / 1000000))MB - over the 1MB limit&quot;<br>    blocked=1<br>  fi<br>  # Block console.log with sensitive-looking content<br>  if git diff --cached -- &quot;$file&quot; | grep -qE &#39;console\.log.*password|console\.log.*token|console\.log.*secret|console\.log.*key&#39;; then<br>    echo &quot;WARN: $file contains console.log that may expose sensitive data&quot;<br>    blocked=1<br>  fi<br>done<br>if [ &quot;$blocked&quot; -eq 1 ]; then<br>  echo &quot;&quot;<br>  echo &quot;Commit rejected. Fix the issues above and try again.&quot;<br>  exit 1<br>fi</pre><p>Make it executable:</p><pre>chmod +x .git/hooks/pre-commit</pre><p><strong>Important — the Windows gotcha:</strong> If you are developing on Windows using Git Bash, Windows will replace Unix line endings (LF) with Windows line endings (CRLF), which silently breaks shell scripts. Fix it with:</p><pre>sed -i &#39;s/\r//&#39; .git/hooks/pre-commit<br>git config core.autocrlf false</pre><h3>The Team Approach: Husky + lint-staged (Node.js)</h3><p>The bash approach has one significant limitation: .git/hooks/ is not tracked by Git. Every developer who clones your repository has to manually install the hooks. Someone will forget. That one person is the one who commits the API key.</p><p>For Node.js teams, <strong>Husky</strong> solves this. It stores hooks in your repository as regular files and installs them automatically when anyone runs npm install.</p><h3>Setting up Husky</h3><pre>npm install --save-dev husky lint-staged<br>npx husky init</pre><p>This creates a .husky/ folder in your repository root. Hooks inside it are version controlled — every team member gets them automatically.</p><h3>Adding your pre-commit hook</h3><pre># .husky/pre-commit<br>npx lint-staged</pre><p><strong>lint-staged</strong> is the companion tool. Instead of running checks against your entire codebase on every commit (slow), it runs them only against the files you have staged (fast). On a large codebase this is the difference between a 30-second block and a 3-second one.</p><h3>Configuring lint-staged</h3><p>In your package.json:</p><pre>{<br>  &quot;lint-staged&quot;: {<br>    &quot;*.{js,ts,jsx,tsx}&quot;: [<br>      &quot;eslint --fix&quot;,<br>      &quot;prettier --write&quot;<br>    ],<br>    &quot;*.{json,md,css}&quot;: [<br>      &quot;prettier --write&quot;<br>    ]<br>  }<br>}</pre><p>Now every staged JavaScript or TypeScript file runs through ESLint and Prettier before it can be committed.</p><h3>The Libraries That Make This Production-Grade</h3><h3>secretlint — purpose-built secret detection</h3><pre>npm install --save-dev secretlint @secretlint/secretlint-rule-preset-recommend</pre><p>Configure in .secretlintrc.json:</p><pre>{<br>  &quot;rules&quot;: [<br>    {<br>      &quot;id&quot;: &quot;@secretlint/secretlint-rule-preset-recommend&quot;<br>    }<br>  ]<br>}</pre><p>Add to lint-staged:</p><pre>{<br>  &quot;lint-staged&quot;: {<br>    &quot;*&quot;: [&quot;secretlint&quot;]<br>  }<br>}</pre><p>Secretlint knows the specific patterns of AWS keys, GCP credentials, Stripe API keys, Twilio auth tokens, GitHub personal access tokens, Slack webhooks, and dozens of other services. It is far more precise than a grep regex.</p><h3>commitlint — enforce commit message standards</h3><pre>npm install --save-dev @commitlint/cli @commitlint/config-conventional</pre><p>Configure in commitlint.config.js:</p><pre>module.exports = {<br>  extends: [&#39;@commitlint/config-conventional&#39;]<br>}</pre><p>Add a commit-msg hook:</p><pre>echo &quot;npx --no -- commitlint --edit \$1&quot; &gt; .husky/commit-msg</pre><p>Now commits like fix stuff are blocked. Only conventional commit messages pass:</p><ul><li>feat(auth): add JWT refresh token rotation</li><li>fix(payments): handle null response from payment gateway</li><li>chore(deps): upgrade express to 4.19</li></ul><p>This matters because tools like semantic-release and auto-generated changelogs read these messages to determine version numbers and release notes automatically.</p><h3>ESLint — catch code quality issues</h3><p>ESLint rules can block commits that contain:</p><ul><li>debugger statements</li><li>console.log in production code (configurable per environment)</li><li>Unreachable code</li><li>Unused variables that might indicate leftover debug code</li></ul><pre>// .eslintrc.js<br>module.exports = {<br>  rules: {<br>    &#39;no-debugger&#39;: &#39;error&#39;,<br>    &#39;no-console&#39;: &#39;warn&#39;,<br>    &#39;no-unused-vars&#39;: &#39;error&#39;<br>  }<br>}</pre><h3>Making Hooks Shareable Across Your Team</h3><p>Since .git/ is not tracked, you keep your hook scripts in a hooks/ folder in your project root. Add a setup script that every developer runs once after cloning:</p><pre>#!/bin/bash<br># setup.sh — run once after cloning<br>chmod +x hooks/pre-commit<br>cp hooks/pre-commit .git/hooks/pre-commit<br>sed -i &#39;s/\r//&#39; .git/hooks/pre-commit   # fix Windows line endings<br>echo &quot;Git hooks installed.&quot;</pre><p>Or if using Husky, this happens automatically on npm install via the prepare script:</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;prepare&quot;: &quot;husky&quot;<br>  }<br>}</pre><h3>What This Looks Like in a Real Project</h3><p>Here is the complete setup for a Node.js project that takes this seriously:</p><pre>project/<br>├── .husky/<br>│   ├── pre-commit          # runs lint-staged + secretlint<br>│   └── commit-msg          # runs commitlint<br>├── hooks/<br>│   └── pre-commit          # bash version for non-Node environments<br>├── .secretlintrc.json      # secretlint config<br>├── .eslintrc.js            # eslint rules<br>├── commitlint.config.js    # commit message rules<br>├── .gitignore              # node_modules/, .env, dist/<br>└── package.json            # lint-staged config inside</pre><p>Every commit now goes through:</p><ol><li>Secretlint — blocks secrets and credentials</li><li>ESLint — blocks code quality violations and debug statements</li><li>Prettier — enforces consistent formatting</li><li>Commitlint — enforces meaningful commit messages</li></ol><p>All of this runs in under 5 seconds on staged files only. The developer sees immediate, specific feedback: not “commit rejected” but “BLOCKED: possible AWS key in src/services/payment.js, line 14.”</p><h3>The Bigger Picture</h3><p>Pre-commit hooks are part of a family of automated safety checks that run at different stages of the development lifecycle:</p><pre>Local machine          → pre-commit hooks (this article)<br>Pull request           → CI pipeline (GitHub Actions, tests, linting)<br>Merge to main          → branch protection rules, required approvals<br>Deploy to production   → deployment gates, smoke tests</pre><p>Each layer catches what slipped through the previous one. Pre-commit hooks are the earliest and cheapest layer, they catch problems before anyone else sees them, before CI time is spent on them, before code review bandwidth is wasted on them.</p><p>The mental model is simple: <strong>make bad commits harder than good ones.</strong> Not impossible a developer can always bypass hooks with git commit --no-verify. But the friction of doing so, combined with the clarity of the error messages, means that in practice, the hooks do their job.</p><h3>Getting Started Today</h3><p>If you take nothing else from this article, take this: add a pre-commit hook to your next project before you write a single line of business logic. It takes ten minutes and it will save you from the moment every developer eventually has the one where you realise what you just pushed and the race to rotate credentials begins.</p><p>For a Node.js project, the minimum viable setup is:</p><pre>npm install --save-dev husky secretlint @secretlint/secretlint-rule-preset-recommend<br>npx husky init<br>echo &quot;npx secretlint --secretlintrc .secretlintrc.json \$(git diff --cached --name-only)&quot; &gt; .husky/pre-commit<br>echo &#39;{ &quot;rules&quot;: [{ &quot;id&quot;: &quot;@secretlint/secretlint-rule-preset-recommend&quot; }] }&#39; &gt; .secretlintrc.json</pre><p>That is it. You now have automated secret detection running on every commit.</p><p>The rest ESLint, Prettier, commitlint, lint-staged you can add progressively as your project and team mature. Start with secrets. That is the one that matters most and it is the one nobody taught us about until it was already too late.</p><p>Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80f526e3a79c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HOW TO STORE YOUR IMAGE ON ECR AND MANAGE IT VIA ECS]]></title>
            <link>https://medium.com/@mark.onyango_95482/how-to-store-your-image-on-ecr-and-manage-it-via-ecs-4c06bd300634?source=rss-3d56bcc1d665------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c06bd300634</guid>
            <category><![CDATA[codewithmark]]></category>
            <dc:creator><![CDATA[Mark Onyango]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 14:02:48 GMT</pubDate>
            <atom:updated>2026-09-15T14:02:48.878Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BKgdd_LwvxP6wd1cyKSuFw.jpeg" /></figure><p>You’ve built your Docker image and confirmed it runs as expected. Now you need to get it in front of real users, a public endpoint they can actually hit. There are several ways to do this on AWS, this article covers one of the most common: Elastic Container Service (ECS).</p><p>To progress through the tutorial smoothly, you will need to have the following pre-requisites:</p><ul><li>AWS CLI installed</li><li>An AWS account</li><li>Docker installed</li><li>Comfortable building and running docker images locally.</li></ul><p>Before we get started, we need to know what two AWS resources we are going to use and what role they will play. ECR stores our image and ECS runs it. ECS(Elastic Container Service) is a fully managed container orchestration service that lets you run, stop and manage Docker containers on a cluster of computers either through AWS Fargate(AWS manage underlying infrastructure for you) or EC2(you manage your own virtual machines that run the containers). ECR(Elastic Container Registry) is a fully managed Docker container registry, it stores and versions your container images but it doesn’t run them. That is the job of ECS.</p><p>For our sample image, we shall build a minimal demo app. Create a folder called ‘app-demo’ and inside that folder create an app.js the paste the following code in:</p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br>const PORT = process.env.PORT || 3000;<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.json({<br>    message: &#39;Hello from ECS!&#39;,<br>    hostname: require(&#39;os&#39;).hostname(),<br>    timestamp: new Date().toISOString()<br>  });<br>});<br><br>app.get(&#39;/health&#39;, (req, res) =&gt; {<br>  res.status(200).send(&#39;OK&#39;);<br>});<br><br>app.listen(PORT, () =&gt; {<br>  console.log(`Server running on port ${PORT}`);<br>});</pre><p>Create a package.json and paste the following:</p><pre>{<br>  &quot;name&quot;: &quot;ecs-demo-app&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;main&quot;: &quot;app.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node app.js&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;express&quot;: &quot;^4.19.2&quot;<br>  }<br>}</pre><p>Finish by creating a Dockerfile and paste this in:</p><pre>FROM node:18-alpine<br><br>WORKDIR /app<br><br>COPY package*.json ./<br>RUN npm install --production<br><br>COPY app.js .<br><br>EXPOSE 3000<br><br>CMD [&quot;npm&quot;, &quot;start&quot;]</pre><p>Next we will build and test our docker image locally. In your terminal add the following:</p><pre>docker build -t ecs-demo-app .<br>docker run -d --name ecs-demo-app -p 3000:3000 ecs-demo-app</pre><p>Hit the following routes to confirm both work; <a href="http://localhost:3000/">http://localhost:3000</a> and <a href="http://localhost:3000/">http://localhost:3000</a>/health. Confirming the container runs locally before uploading to ECR is important. It will help in debugging as you will have confirmed it already works locally. Quick cleanup before moving to ECR, you should find the running container name ‘ecs-demo-app’ and stop it using the commands below:</p><pre>docker rm -f ecs-demo-app</pre><p>We first need to create an ECR repository. Think of it as an empty private folder where we will place our image. This is the equivalent of creating an empty docker hub folder that is private and tied to our AWS account. Below is the command to create our ECR repository.</p><p>N/B — you can adjust the region according to your preference but here we will use ‘us-east-1’.</p><pre>aws ecr create-repository --repository-name ecs-demo-app --region us-east-1</pre><p>From the output, we will need the repositoryUri which looks something like:</p><pre>&lt;account-id&gt;.dkr.ecr.us-east-1.amazonaws.com/ecs-demo-app</pre><p>To access your account id, run the following:</p><pre>aws sts get-caller-identity</pre><p>Next we will authenticate docker to ECR. <em>get-login-password</em> generates a temporary auth token valid 12 hours hence why you will need to re-run the command periodically rather than a one-time login. In the command you will need to add the correct region and your account id.</p><pre>aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin &lt;account-id&gt;.dkr.ecr.us-east-1.amazonaws.com</pre><p>We then tag the docker image to match the ECR repo URI. Docker decides where to push purely based on what the tag looks like, which is why the tag must exactly match the repository URI.</p><pre>docker tag ecs-demo-app:latest &lt;account-id&gt;.dkr.ecr.us-east-1.amazonaws.com/ecs-demo-app:latest</pre><p>Proceed to push the image:</p><pre>docker push &lt;account-id&gt;.dkr.ecr.us-east-1.amazonaws.com/ecs-demo-app:latest</pre><p>Verify your upload was successful:</p><pre>aws ecr describe-images --repository-name ecs-demo-app --region us-east-1</pre><p>Now we will create our ECS cluster. An ECS cluster is a logical grouping of tasks or services that run your containerized applications. It is a logical grouping with Fargate not necessarily servers we are creating.</p><pre>aws ecs create-cluster --cluster-name ecs-demo-cluster</pre><p>ECS will require permissions to pull our image from ECR and write logs on our behalf. In the same directory, create a file called trust-policy.json and paste the following:</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: { &quot;Service&quot;: &quot;ecs-tasks.amazonaws.com&quot; },<br>      &quot;Action&quot;: &quot;sts:AssumeRole&quot;<br>    }<br>  ]<br>}</pre><p>We then create a role with our inline policy and attach ecsTaskExecutionRole. What this simply does is allow our task to pull an image and write logs.</p><pre>aws iam create-role --role-name ecsTaskExecutionRole --assume-role-policy-document file://trust-policy.json<br>aws iam attach-role-policy --role-name ecsTaskExecutionRole --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy</pre><p>We will need somewhere to store our logs to be able to read them. CloudWatch handles this for us. All we have to do is create our log group for container output.</p><pre>aws logs create-log-group --log-group-name /ecs/ecs-demo-app</pre><p>An ECS task definition is a blueprint text file in JSON format that describes how one or more containers should be launched in AWS i.e. docker images, resource allocation, networking mode, logging configuration, environment variables and storage volumes. Fargate requires specific valid combinations (256 CPU units = 0.25 vCPU pairs with limited memory options). Create a file called task-definition.json in the same directory and add:</p><pre>{<br>  &quot;family&quot;: &quot;ecs-demo-task&quot;,<br>  &quot;networkMode&quot;: &quot;awsvpc&quot;,<br>  &quot;requiresCompatibilities&quot;: [&quot;FARGATE&quot;],<br>  &quot;cpu&quot;: &quot;256&quot;,<br>  &quot;memory&quot;: &quot;512&quot;,<br>  &quot;executionRoleArn&quot;: &quot;arn:aws:iam::&lt;account-id&gt;:role/ecsTaskExecutionRole&quot;,<br>  &quot;containerDefinitions&quot;: [<br>    {<br>      &quot;name&quot;: &quot;ecs-demo-app&quot;,<br>      &quot;image&quot;: &quot;&lt;account-id&gt;.dkr.ecr.us-east-1.amazonaws.com/ecs-demo-app:latest&quot;,<br>      &quot;portMappings&quot;: [{ &quot;containerPort&quot;: 3000, &quot;protocol&quot;: &quot;tcp&quot; }],<br>      &quot;logConfiguration&quot;: {<br>        &quot;logDriver&quot;: &quot;awslogs&quot;,<br>        &quot;options&quot;: {<br>          &quot;awslogs-group&quot;: &quot;/ecs/ecs-demo-app&quot;,<br>          &quot;awslogs-region&quot;: &quot;us-east-1&quot;,<br>          &quot;awslogs-stream-prefix&quot;: &quot;ecs&quot;<br>        }<br>      }<br>    }<br>  ]<br>}</pre><p>Then run the following command:</p><pre>aws ecs register-task-definition --cli-input-json file://task-definition.json</pre><p>Next we create a security group for our ECS and open port to 0.0.0.0/0 meaning anyone can reach it. Opening the port straight to 0.0.0.0/0 is fine for a disposable tutorial demo but in a real setup you&#39;d front this with an ALB.</p><pre>aws ec2 create-security-group --group-name ecs-demo-sg --description &quot;Allow app traffic&quot; --vpc-id &lt;your-vpc-id&gt;<br>aws ec2 authorize-security-group-ingress --group-id &lt;sg-id&gt; --protocol tcp --port 3000 --cidr 0.0.0.0/0</pre><p>Now to the ECS service, it is a configuration tool used to run and maintain a specified number of simultaneous instances of a task definition in an ECS cluster. Run the following command to create one:</p><pre>aws ecs create-service \<br>  --cluster ecs-demo-cluster \<br>  --service-name ecs-demo-service \<br>  --task-definition ecs-demo-task \<br>  --desired-count 1 \<br>  --launch-type FARGATE \<br>  --network-configuration &quot;awsvpcConfiguration={subnets=[&lt;public-subnet-id&gt;],securityGroups=[&lt;sg-id&gt;],assignPublicIp=ENABLED}&quot;</pre><p>assignPublicIp=ENABLED is what gives you a directly reachable public IP for this simple version. For production you utilise ALB as the production-grade alternative.</p><p>Find the running task’s public IP and test:</p><pre>aws ecs list-tasks --cluster ecs-demo-cluster --service-name ecs-demo-service<br>aws ecs describe-tasks --cluster ecs-demo-cluster --tasks &lt;task-arn&gt; --query &quot;tasks[0].attachments[0].details&quot;</pre><p>The commands will give you the ENI ID then from there, run the command below:</p><pre>aws ec2 describe-network-interfaces --network-interface-ids &lt;eni-id&gt; --query &quot;NetworkInterfaces[0].Association.PublicIp&quot; --output text</pre><p>Now in your browser, hit the endpoint: http://&lt;public-ip&gt;:3000, you should be able to see the results from <a href="http://localhost:3000.">http://localhost:3000.</a> You can as well try http://&lt;public-ip&gt;:3000/health. There it is you have successfully stored your docker image on ECR and run it using ECS. Let me know if you want me to make it production grade by adding an ALB.</p><p>Lastly, we have to do a cleanup to avoid receiving huge AWS bills at the end of the month. Order matters as some block deletion of other.</p><p>You can’t delete a service while it still has running tasks, so scaling to 0 first lets ECS gracefully stop them before the service itself is removed. We start with deleting the service:</p><pre>aws ecs update-service --cluster ecs-demo-cluster --service ecs-demo-service --desired-count 0<br>aws ecs delete-service --cluster ecs-demo-cluster --service ecs-demo-service</pre><p>Next we delete the cluster</p><pre>aws ecs delete-cluster --cluster ecs-demo-cluster</pre><p>De-register the task definition, task definitions are never fully deleted, only deregistered.</p><pre>aws ecs deregister-task-definition --task-definition ecs-demo-task:1</pre><p>Delete the cloudwatch log group</p><pre>aws logs delete-log-group --log-group-name /ecs/ecs-demo-app</pre><p>Delete the security group. This one can fail if the ENI from your task hasn’t fully released yet. Waiting a minute or two after step 1 usually resolves it.</p><pre>aws ec2 delete-security-group --group-id &lt;sg-id&gt;</pre><p>Delete the ECR repository and the images. The --force flag is required here since the repo still contains the image you pushed, without it, ECR refuses to delete a non-empty repository.</p><pre>aws ecr delete-repository --repository-name ecs-demo-app --force</pre><p>For the IAM role, it will not cost you anything you can choose to delete or leave it.</p><pre>aws iam detach-role-policy --role-name ecsTaskExecutionRole --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy<br>aws iam delete-role --role-name ecsTaskExecutionRole</pre><p>We are done with this project. Leave a like if this helped you. Happy coding!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c06bd300634" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HOW TO HOST A STATIC WEBSITE ON AN AWS S3 BUCKET]]></title>
            <link>https://medium.com/@mark.onyango_95482/how-to-host-a-static-website-on-an-aws-s3-bucket-f280a7bd10ab?source=rss-3d56bcc1d665------2</link>
            <guid isPermaLink="false">https://medium.com/p/f280a7bd10ab</guid>
            <category><![CDATA[codewithmark]]></category>
            <dc:creator><![CDATA[Mark Onyango]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 12:35:37 GMT</pubDate>
            <atom:updated>2026-09-08T12:35:37.356Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4cEfR1203RKrlLw5e-DRTg.jpeg" /></figure><p>Having built your portfolio, you want your site to be accessible online to showcase your projects. The usual concern is how expensive hosting can cost which is not easy especially when you are just starting out. AWS offer a cost effective option to host your static website for just under $3 per month. S3 buckets are one of the cheapest storage options by cloud providers but for today, I will handle how you can use an S3 bucket to host your static website.</p><p>For this tutorial, you will need to have access to an AWS account with console/ CLI permissions. I will cover both using the AWS console and AWS CLI. Head into your AWS console and look up S3 buckets, go ahead and create one. On the creation page, a lot of the settings will remain default. Here is how you will setup; bucket type should be general purpose, namespace remains global namespace, enter a unique name for the bucket(remember the name should be globally unique therefore you can use a naming convention such as [organization/project]-[environment]-[purpose]-[region/account-id]), object ownership stays as ACLs disabled, uncheck block all public access(this will allow public access into your bucket and it resources), bucket versioning disabled(if you enable it you will be charged so be careful) and the rest remain the default, proceed and create the bucket.</p><p>If you are using AWS CLI, here is an alternative. Get your credentials from your IAM user(in the IAM section) that is your access key ID and secret key. Next, in your CLI enter the command:</p><pre>aws configure<br><br># proceed to fill in the following<br>AWS Access Key ID [None]: enter your access key ID<br>AWS Secret Access Key [None]: enter your secret access key<br>Default region name [None]: enter your region<br>Default output format [None]: json</pre><p>To create the actual bucket use:</p><pre>aws s3api create-bucket --bucket [organization/project]-[environment]-[purpose]-[region/account-id] --region (default region) --create-bucket-configuration LocationConstraint=(bucket region)<br><br># confirm bucket was created<br>aws s3 ls</pre><p>Back to the console, when you click on your bucket name, it opens up a section that you can upload object(files/ folder) to the bucket. Click on upload then select add file or folder after which you open the folder your project exists and for the files select them individually and upload, if you had a folder as well then using the add folders button upload your folder then save changes. After successfully uploading your files and folder, head into properties tab(the tab options are just below your bucket name). Go to the last section, which is static hosting and click on edit. Enable it, hosting type will remain host static website, for your index document enter the name you used, more often it is index.html and add your error file name, if you have one then save changes.</p><p>At the bottom, you will be provided a link but when you try to access it you will get a 403 forbidden. This is because we have not yet set our bucket policy. If you had not unchecked “block all public access” during bucket creation, do so in the permissions tab(right next to properties). Just below “block all public access” section, you will see a bucket policy field. Click on edit and enter the json below:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;PublicReadGetObject&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: &quot;*&quot;,<br>            &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::&lt;your-bucket-name&gt;/*&quot;<br>        }<br>    ]<br>}</pre><p>Proceed to save, then try accessing the link again. There you go, your website is now live and can be accessed publicly.</p><p>For the CLI group, we will start by uploading our files and folders.</p><pre>cd ./your-project<br>aws s3 sync . s3://my-static-website-bucket-xyz </pre><p>After successfully uploading, enable static hosting by:</p><pre>aws s3api put-bucket-website --bucket my-static-website-bucket-xyz --website-configuration &#39;{&quot;IndexDocument&quot;: {&quot;Suffix&quot;: &quot;index.html&quot;}, &quot;ErrorDocument&quot;: {&quot;Key&quot;: &quot;error.html&quot;}}&#39;</pre><p>Remove public access and add public read policy.</p><pre>aws s3api put-public-access-block --bucket my-static-website-bucket-xyz --public-access-block-configuration &quot;BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false&quot;</pre><p>Add public read policy:</p><pre>aws s3api put-bucket-policy --bucket my-static-website-bucket-xyz --policy &#39;{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;PublicReadGetObject&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: &quot;*&quot;,<br>            &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::my-static-website-bucket-xyz/*&quot;<br>        }<br>    ]<br>}&#39;</pre><p>Get your live link.</p><pre>echo &quot;http://my-static-website-bucket-xyz.s3-website-$(aws configure get region).amazonaws.com&quot;</pre><p>There it is you are done and your website is live. If you ever want to pull down the s3 bucket make sure to delete all its contents first then you will be allowed to delete the bucket. You now have no excuse as to why your portfolio is still in localhost. Happy coding!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f280a7bd10ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SCRIPT TO SCAN NGINX ACCESS LOGS FOR ABNORMAL ACTIVITIES]]></title>
            <link>https://medium.com/@mark.onyango_95482/script-to-scan-nginx-access-logs-for-abnormal-activities-f4e25c819430?source=rss-3d56bcc1d665------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4e25c819430</guid>
            <category><![CDATA[codewithmark]]></category>
            <dc:creator><![CDATA[Mark Onyango]]></dc:creator>
            <pubDate>Mon, 07 Sep 2026 12:19:05 GMT</pubDate>
            <atom:updated>2026-09-07T12:19:05.003Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zaxgrYz0Pj9ygev7T1hLCA.jpeg" /></figure><p>In a practice to maintain a secure and healthy systems, organizations have embraced logging and monitoring as an important pillar in the lifecycle of the system. Today, we are going to tackle just a small fraction of monitoring for systems. We will write a bash script that will automate the monitoring of our nginx access logs, come up with a report and from there use an agent to analyse the report then give us recommendations. This exercise will not require much, you will only need access to an editor like vim or nano, an application running on nginx and an agent of your choice but for this article I will use claude.</p><p>In the introductory part of our script we will have the following:</p><pre>#!/bin/bash</pre><p>The line above is known as a shebang, it is used to tell the computer program loader which interpreter to use to run the file.</p><p>Proceed to create variables we will use within the script:</p><ul><li>THRESHOLD — this will be the number of requests upon exceeding an IP is flagged.</li><li>OUTDIR — this is the directory you want your report stored.</li><li>OUTFILE — this is the file where the script will write the report into.</li></ul><p>First, we start by checking if the required file path argument has been provided. Test this using an “if statement”.</p><pre>if [ condition ]; then<br>    # Commands to run if the condition is true<br>fi</pre><p>The check will follow the syntax above and will look as follows:</p><pre>if [ -z &quot;$1&quot; ]; then<br>    echo &quot;Usage: bash $0 /path/to/access.log&quot;<br>    exit 1<br>fi</pre><p>It checks if the first argument passed to the script is empty. If it is not empty we store our $1 to a variable and proceed to check if path points to a regular file.</p><pre>LOGFILE=&quot;$1&quot;<br> <br>if [ ! -f &quot;$LOGFILE&quot; ]; then<br>    echo &quot;Error: file not found: $LOGFILE&quot;<br>    exit 1<br>fi</pre><p>Next we make sure our OUTDIR exists by running:</p><pre>mkdir -p &quot;$OUTDIR&quot;</pre><p>The “-p” flag ensures there is no error if the directory already exists. We now want to log our ouput both to the terminal and output file hence we add:</p><pre>exec &gt; &gt;(tee &quot;$OUTFILE&quot;) 2&gt;&amp;1</pre><p>We need to access status codes from our logs and store them in a variable.</p><pre>STATUS_CODES=$(awk -F&#39;&quot;&#39; &#39;{print $3}&#39; &quot;$LOGFILE&quot; | awk &#39;{print $1}&#39;)</pre><ul><li>F ‘ “ ‘ — tells <em>awk </em>to split the log line using double quotes as a seperator.</li></ul><p>For example</p><pre>127.0.0.1 - - [07/Sep/2026:12:00:00 +0000] &quot;GET /index.html HTTP/1.1&quot; 200 4324</pre><p><em>awk </em>will divide it into three sections i.e</p><ul><li>127.0.0.1 — — [07/Sep/2026:12:00:00 +0000] — before the first quote</li><li>GET /index.html HTTP/1.1 — before the second quote</li><li>200 4324 — after the second quote</li></ul><p>We have established from this command “ print $3 ” we are taking the third portion which is “200 4324” and then piping it into another <em>awk</em>. The second <em>awk </em>by default splits using space and lastly, we take the first argument from the third piped portion “print $1” which gives us our http status code “200”.</p><p>We can now access our error codes 4XX(client) and 5XX(server) as shown below;</p><pre>FOUR_XX=$(echo &quot;$STATUS_CODES&quot; | grep -c &#39;^4&#39;)<br>FIVE_XX=$(echo &quot;$STATUS_CODES&quot; | grep -c &#39;^5&#39;)</pre><p>From our logs we get the top five IPs sending requests.</p><pre>awk &#39;{print $1}&#39; &quot;$LOGFILE&quot; | sort | uniq -c | sort -rn | head -5</pre><p>Next, we get the number of times an IP has sent a request, pass it into a loop that will check the count against our THRESHOLD then echo flagging the exact IP and the number of requests made to flagged_output variable.</p><pre>FLAGGED_OUTPUT=$(awk &#39;{print $1}&#39; &quot;$LOGFILE&quot; | sort | uniq -c | sort -rn | while read count ip; do<br>    if [ &quot;$count&quot; -gt &quot;$THRESHOLD&quot; ]; then<br>        echo &quot;FLAGGED: $ip made $count requests&quot;<br>    fi<br>done)</pre><p>Keyword ‘<em>read’ </em>— also splits using space. It takes the output from the command that is piping into the loop, which will be something like 10 10.0.0.0, and it splits the two, the first number goes into variable count and the ip into variable ip.</p><p>Lastly, if there is no flagged output, echo a clear message else echo the flagged output.</p><pre>if [ -z &quot;$FLAGGED_OUTPUT&quot; ]; then<br>    echo &quot;No threats found — no IP exceeded the $THRESHOLD request threshold.&quot;<br>else<br>    echo &quot;$FLAGGED_OUTPUT&quot;<br>fi</pre><p>The full code is as follows:</p><pre>#!/bin/bash<br><br># log_monitor.sh — scan an Nginx access log for abnormal activity<br># Usage: bash log_monitor.sh /path/to/access.log<br># (overwritten on every run — always reflects the most recent scan)<br><br>THRESHOLD=10<br>OUTDIR=&quot;/path/to/dir&quot;<br>OUTFILE=&quot;$OUTDIR/file-name.txt&quot;<br><br># --- Input validation ---<br>if [ -z &quot;$1&quot; ]; then<br>    echo &quot;Usage: bash $0 /path/to/access.log&quot;<br>    exit 1<br>fi<br><br>LOGFILE=&quot;$1&quot;<br><br>if [ ! -f &quot;$LOGFILE&quot; ]; then<br>    echo &quot;Error: file not found: $LOGFILE&quot;<br>    exit 1<br>fi<br><br># Make sure the output directory exists before we try to write into it<br>mkdir -p &quot;$OUTDIR&quot;<br><br># Everything from here on is sent to BOTH the terminal and the report<br># file at the same time, via tee. &gt; &quot;$OUTFILE&quot; (not &gt;&gt;) means each run<br># overwrites the previous report rather than appending to it.<br>exec &gt; &gt;(tee &quot;$OUTFILE&quot;) 2&gt;&amp;1<br><br>echo &quot;==================================================&quot;<br>echo &quot; Nginx Access Log Report&quot;<br>echo &quot; Source file : $LOGFILE&quot;<br>echo &quot; Generated   : $(date)&quot;<br>echo &quot;==================================================&quot;<br>echo<br>echo &quot;This report scans the log for three things:&quot;<br>echo &quot;  1) how many requests resulted in errors (4xx/5xx)&quot;<br>echo &quot;  2) which IPs sent the most requests&quot;<br>echo &quot;  3) any single IP that crossed the abuse threshold ($THRESHOLD requests)&quot;<br>echo<br><br># --- Parse status codes ONCE, reuse the result ---<br># Splitting on &quot; first isolates the request field (which can contain<br># unpredictable garbage/spaces from malformed or malicious requests),<br># so status-code extraction stays reliable no matter what junk ends up<br># inside the request line. We only run this parsing pass one time and<br># store it, instead of re-reading the file for every section below.<br>STATUS_CODES=$(awk -F&#39;&quot;&#39; &#39;{print $3}&#39; &quot;$LOGFILE&quot; | awk &#39;{print $1}&#39;)<br><br>echo &quot;--- Status code counts ---&quot;<br>echo &quot;$STATUS_CODES&quot; | sort | uniq -c | sort -rn<br>echo<br><br>echo &quot;--- 4xx / 5xx totals ---&quot;<br>FOUR_XX=$(echo &quot;$STATUS_CODES&quot; | grep -c &#39;^4&#39;)<br>FIVE_XX=$(echo &quot;$STATUS_CODES&quot; | grep -c &#39;^5&#39;)<br>echo &quot;4xx responses: $FOUR_XX&quot;<br>echo &quot;5xx responses: $FIVE_XX&quot;<br>echo<br><br># --- Top 5 requesting IPs ---<br>echo &quot;--- Top 5 requesting IPs ---&quot;<br>awk &#39;{print $1}&#39; &quot;$LOGFILE&quot; | sort | uniq -c | sort -rn | head -5<br>echo<br><br># --- Threshold flagging ---<br># Checks EVERY IP, not just the top 5 — a fixed head -5 would silently<br># hide additional offenders if more than 5 IPs crossed the threshold.<br>#<br># The flagging logic runs inside a command substitution $(...) rather<br># than a bare `while read` piped loop. A piped while loop runs in a<br># subshell, so a variable set inside it (like FLAGGED=1) would vanish<br># the moment the loop ends and never be visible afterward. Capturing<br># the loop&#39;s PRINTED OUTPUT via $(...) sidesteps that entirely — we<br># just check whether any text came back, instead of relying on a<br># variable that was mutated inside the subshell.<br>echo &quot;--- Flagged IPs (&gt; $THRESHOLD requests) ---&quot;<br>FLAGGED_OUTPUT=$(awk &#39;{print $1}&#39; &quot;$LOGFILE&quot; | sort | uniq -c | sort -rn | while read count ip; do<br>    if [ &quot;$count&quot; -gt &quot;$THRESHOLD&quot; ]; then<br>        echo &quot;FLAGGED: $ip made $count requests&quot;<br>    fi<br>done)<br><br>if [ -z &quot;$FLAGGED_OUTPUT&quot; ]; then<br>    echo &quot;No threats found — no IP exceeded the $THRESHOLD request threshold.&quot;<br>else<br>    echo &quot;$FLAGGED_OUTPUT&quot;<br>fi<br><br>echo<br>echo &quot;==================================================&quot;<br>echo &quot; Report saved to: $OUTFILE&quot;<br>echo &quot;==================================================&quot;</pre><p>If you will not proceed to the agents sections, just give the script execute permissions and run it. As shown below:</p><pre>chmod +x filename.sh<br>./filename.sh</pre><p>For the next section, we are going to analyse the report from our script above using claude (use claude CLI to access the agent) and have the claude agent give us recommendations. We will require two files for this CLAUDE.md(provides standing rules and context of your project) and SKILL.md(has instructions on how to perform a specific task).</p><p>Create a folder “.claude” at the parent folder of your project. In your “.claude”, you will create “CLAUDE.md” file and a folder called “skills”. Inside “skills” create another folder called “nginx_monitoring” now inside folder “nginx_monitoring”, create file “SKILL.md”. The structure will look as follows:</p><pre>ls .claude - CLAUDE.md  skills<br><br>cd ./skills<br>ls skills - nginx_monitoring<br><br>cd ./nginx_monitoring<br>ls nginx_monitoring - SKILL.md</pre><p>CLAUDE.md</p><p>N/B — substitute “filename.sh” with your actual file name and “/path/to/dir” with actual path.</p><pre># Nginx Monitoring — Agent Instructions<br><br>## Purpose<br>This agent reviews the Nginx access log report produced by `filename.sh`<br>and gives a human-readable analysis with recommended next steps. It does<br>not take any action itself — a human decides what to do with the findings.<br><br>## Scope — narrow, single responsibility<br>The ONLY commands this agent is allowed to run are the two needed to<br>generate the report (`chmod +x` on the script, then run it). Everything<br>after that is read-and-recommend only.<br><br>- ONLY execute: `chmod +x log_monitor.sh` and then `./filename.sh`<br>  (or the equivalent path to the script) to (re)generate the report<br>- ONLY read the report file at: `/path/to/dir/log-report.txt`<br>- ONLY write your analysis back into that same file, appended below the<br>  existing report content (never overwrite or delete the original report)<br>- Do NOT run any other commands against the server — no restarting<br>  services, modifying security groups, blocking IPs, editing Nginx<br>  config, or touching any other file<br>- Do NOT execute or suggest running any remediation commands — only<br>  describe what a human could choose to do<br><br>## What to do when run<br>1. Ensure the log monitor script is executable, then run it, to produce<br>   a fresh report: `chmod +x &lt;path-to-filename.sh&gt; &amp;&amp; &lt;path-to-filename.sh&gt; &lt;logfile&gt;`<br>2. Read the resulting `/path/to/dirlog-report.txt`<br>3. Look at the status code breakdown, top requesting IPs, and any flagged<br>   IPs already identified by the script<br>4. Summarize in plain language: what&#39;s normal, what&#39;s unusual, and why<br>5. Recommend specific next steps a human engineer could take (e.g.<br>   &quot;consider blocking IP X at the security group level&quot;, &quot;investigate<br>   whether IP Y is a legitimate user before acting&quot;, &quot;no action needed —<br>   traffic looks like normal background scanning&quot;)<br>6. Append that analysis to the bottom of the same report file, under a<br>   clearly marked `## AI Analysis` section with a timestamp<br><br>## Tone<br>Be direct and specific. Don&#39;t pad the recommendation with hedging —<br>name the IP, name the concern, name the suggested action. If nothing<br>looks abnormal, say so plainly instead of manufacturing a finding.</pre><p>SKILL.md</p><pre>---<br>name: nginx-monitoring<br>description: Reads the Nginx access log report and produces a plain-language analysis with recommended next steps. <br>Read-only — never modifies the server, never takes action, only reads the report and appends analysis to it.<br>---<br><br># Nginx Monitoring Analysis<br><br>## When to use this skill<br>Use when asked to review, analyze, or summarize the Nginx access log<br>report, or when the `/nginx_monitoring` command is invoked.<br><br>## Steps<br><br>1. Read the report file:<br>   `/path/to/dir/log-report.txt`<br>   If the file doesn&#39;t exist, say so and stop — do not generate findings<br>   from nothing.<br><br>2. Review the sections already in the report:<br>   - Status code counts (4xx/5xx totals)<br>   - Top 5 requesting IPs<br>   - Flagged IPs (already over the script&#39;s request threshold)<br><br>3. Write a short analysis covering:<br>   - Overall traffic health in one or two sentences<br>   - Anything genuinely unusual, named specifically (which IP, which<br>     status code pattern, why it stands out)<br>   - A concrete recommended next step for each finding — or an explicit<br>     &quot;no action needed&quot; if traffic looks normal<br><br>4. Append the analysis to the END of the same report file (do not<br>   overwrite the script&#39;s original output), under a header like:<br><br>   ```<br>   ## AI Analysis — &lt;date/time&gt;<br>   &lt;findings and recommendations here&gt;<br>   ```<br><br>## Hard limits<br>- Read-only on the server. Never run remediation commands, never edit<br>  Nginx config, never touch security groups, never block an IP directly.<br>- Only ever writes to the report file itself, and only by appending.<br>- If the report shows nothing concerning, say that plainly rather than<br>  inventing a recommendation to seem useful.</pre><p>Finally proceed to go through the recommendations and gather next steps. If you found it beneficial leave a thumbs up.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4e25c819430" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BUILDING A SECURE AWS VPC ARCHITECTURE]]></title>
            <link>https://medium.com/@mark.onyango_95482/building-a-secure-aws-vpc-architecture-770bd43d04b5?source=rss-3d56bcc1d665------2</link>
            <guid isPermaLink="false">https://medium.com/p/770bd43d04b5</guid>
            <category><![CDATA[codewithmark]]></category>
            <dc:creator><![CDATA[Mark Onyango]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 11:49:05 GMT</pubDate>
            <atom:updated>2026-08-30T11:49:05.536Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XCEZr-BZ4RT5WLFFek7ZaQ.jpeg" /></figure><p>In a previous <a href="https://medium.com/@mark.onyango_95482/deploying-a-react-app-on-ubuntu-vm-using-nginx-ecfdca64040c?sharedUserId=mark.onyango_95482">article</a>, I covered how you can deploy a static application on an EC2 using nginx. Today, I want to walk you through how you can organize your architecture in a VPC(Virtual Private Cloud). How do you build a secure AWS VPC architecture? The truth is there are numerous ways to setup your VPC and the one I will demonstrate is just one common setup.</p><p>Before diving deep into the building phase let us first understand components of this architecture and what role they play.</p><ul><li>Virtual Private Cloud— Isolated logical network within the cloud.</li><li>Internet Gateway — allows communication between your VPC resources and the internet.</li><li>Route Table — set of rules that determine where network traffic from your subnet is directed.</li><li>Application Load Balancer — fully managed service that automatically distributes incoming traffic across multiple targets.</li><li>Security Group — virtual firewalls that control inbound and outbound traffic for specific resources.</li><li>IAM Role — an identity you create in your AWS account that has specific permissions. AmazonSSMManagedInstanceCore is an IAM policy that when attached to an IAM role, it grants an EC2 instance the minimum required permissions to securely connect to and be managed by AWS Systems Manager (SSM).</li><li>AWS Systems Session Manager — is a secure, central management service that gives you complete visibility and control over all of your cloud and on-premises infrastructure.</li><li>Target group — logical routing destination used by a load balancer to direct incoming traffic to your actual backend resources</li></ul><p>N/B — This exercise will be fully done from the AWS console, we will cover deployment through terraform in a future series. SSM endpoints and ALB will cost you so if you are trying to stay in the free tier consider that.</p><p>We will start by creating our VPC. The process is straightforward you just need to fill in the name, CIDR and create. After creating your VPC proceed to create your subnets. Here we will create four subnets i.e. a public and private subnet in two different availability zones to make our setup highly available and fault tolerant. For example you can setup public-subnet-1 in availability zone eu-north-1a and public-subnet-2 in availability zone eu-north-1b.</p><p>Follow up by creating an Internet Gateway, you just provide a name and you are done. After that you can start creating your public and private route tables. When done creating your route table, create subnet associations for the private route table and add your two private subnets and same goes for your public route table. To enable the public route table have access to internet traffic, in the route tab add a route to 0.0.0.0/0 (internet) and your target should be the internet gateway initially created.</p><p>You will require security groups to control traffic in and out of your resources. In this case we will have three security groups, one for the instances in our private subnet, one security group for our ALB and another for SSM. For ALB security group inbound rules, we add HTTP and HTTPS as this will handle traffic from our internet gateway and distribute to our instances. For our private subnet group, we will add http for our inbound rule and set the source as our ALB security group. For SSM, we add inbound rule https with the source as our private subnet security group.</p><p>Next, we create an IAM role, for our instances, that will allow SSM connection(for private access to our instances). The role will be for a service and the use case EC2, on the next page search for “AmazonSSMManagedInstanceCore” select it and lastly enter a name and short description then create. This role will be attached to the instances in your VPC, in the advanced details sections when launching an instance, select IAM instance profile and add the role. Make sure you start your instances. A point to note when launching your instance disable public IP as the only access to the instance will be through our ALB(public access) or a secure SSM private connection.</p><p>Next you will be creating a target group for instances in the EC2 page under laod balancing, leave the protocol default, select your VPC, move to the register targets’ page and select the running instances you want for your target group and include as pending below and create. This target group is what will be used by our load balancer to direct traffic. Moving us to our next activity, creating an application load balancer. Select load balancer and then choose application load balancer, it should be internet facing, select your two availability zones, select the ALB security group, select the target group you created and lastly create the ALB.</p><p>To conclude, we are going to create endpoints for a private SSM connection to our instances. Remember, currently we do not have a public IP so SSH is not an option if we want access to our instances. The three endpoints we will be creating are:</p><ul><li>ssm — the control endpoint. This is where the SSM Agent registers itself and where the Systems Manager service issues commands/session requests.</li><li>ec2messages — despite the name, this isn&#39;t a general EC2 endpoint. It&#39;s specifically the channel the agent uses to poll for pending commands and send back status/results. This existed before Session Manager was built and originally served plain SSM commands (like Run Command).</li><li>ssmessages — this is specifically for interactive session data. The actual live keystrokes and terminal output when you&#39;re in a Session Manager shell, as opposed to a one-off command.</li></ul><p>For endpoint creation we head into VPC and select endpoints. Provide a name, type will be AWS services, for the three endpoints only the services will be changing. We will search the following services according to their endpoint:</p><ul><li>ssm — search “com.amazonaws.&lt;region&gt;.ssm”</li><li>ec2messages — search “com.amazonaws.&lt;region&gt;.ec2messages”</li><li>ssmessages — search “com.amazonaws.&lt;region&gt;.ssmmessages”</li></ul><p>For the security group, you select the SSM security group we initially created. Give sometime for all the endpoints to be active. Once they are active we can proceed to test our connections. To test our private SSM connection proceed to your instance, ensure it is running, press the connect button, under the session manager tab go on and connect, a terminal will open and type in a command like “whoami” if you see a response you have successfully connected.</p><p>Lastly, we test to see if we can recieve requests from the internet through our ALB. In your open terminal (from session manager) you can input “sudo python3 -m http.server 80”.Python3 is pre-installed on Amazon linux, if on a different machine you can download python3. Head to your load balancer tab and copy the DNS they provide then paste on a web browser. If you see a list of directories then your connection is successful. If you were trying to stay in the free tier, terminate the instance running, tear down your ALB, target group and the endpoints from SSM after the test works.</p><p>There it is we have successfully built a production style secure AWS VPC architecture. Go ahead and experiment and see what works best for your needs. You can choose to let your VPC and its resources(subnets, route tables, security groups, IGW) stay or you can tear down everything.</p><p>Let me know what you want me to cover next. Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=770bd43d04b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PERFORM HEALTH CHECKS WITH A BASH SCRIPT AND AI-ASSISTED ANALYSIS]]></title>
            <link>https://medium.com/@mark.onyango_95482/perform-health-checks-with-a-bash-script-and-ai-assisted-analysis-fdc9aad074c6?source=rss-3d56bcc1d665------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdc9aad074c6</guid>
            <category><![CDATA[codewithmark]]></category>
            <dc:creator><![CDATA[Mark Onyango]]></dc:creator>
            <pubDate>Sat, 29 Aug 2026 08:36:36 GMT</pubDate>
            <atom:updated>2026-08-29T08:36:36.280Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_hm3S2YLGjyB8cJVwgI0sQ.jpeg" /></figure><p>Once the application is up and running we need to perform frequent health checks to ensure we capture a problem before it happens or have an idea of how to diagnose a problem when it occurs. For today, I will be taking you over some checks you can perform after deploying your application on an EC2 through nginx.</p><p>To automate this process we are going to write a bash script that will perform all these checks for us and use claude agent to review our report and give us a proper analysis of the outcome as well as propose the next steps for us. This activity assumes you are working from a linux supported machine and you are working locally.</p><p>The checks we will be performing include:</p><ul><li>Check if nginx is running</li><li>Check if port 80 is listening</li><li>Check if application responds locally</li><li>Check if disk is nearly full</li><li>Check if memory is available</li></ul><p>To start us out, Nginx should be running and active for your app to be accessible. The following command above will check if your nginx is running and active.</p><pre>sudo systemctl is-active --quiet nginx</pre><p>Once you are sure your nginx is running correctly, you can check if your port 80 is listening. The command to verify your port 80 is listening is:</p><pre>ss -ltn | awk &#39;NR &gt; 1 {print $4}&#39; | grep -qE &#39;:80$&#39;</pre><p>ss -ltn — Lists listening TCP sockets with numerical port and IP addresses</p><p>awk ‘NR &gt; 1 {print $4}’ — Skips the first header row and prints only the fourth column, which shows the local address and port</p><p>grep -qE ‘:80$’ — Quietly searches the output to see if any line ends with port 80</p><p>Continue to check for http status code returned. We will perform the check by running:</p><pre>curl -s -o /dev/null -w &#39;%{http_code}&#39; --max-time 5 &quot;$target_url&quot; || true</pre><p>curl — A tool to transfer data to or from a server using various network protocols</p><p>-s — Runs in silent mode. It hides the progress meter and error messages.</p><p>-o /dev/null — Discards the actual body of the downloaded webpage by sending it to a black-hole file.</p><p>w ‘%{http_code}’ — Prints out only the final HTTP status code after completing the request.</p><p>- -max-time 5 — Stops and fails the request if it takes longer than 5 seconds.</p><p>“$target_url” — The website address or API endpoint you are testing.</p><p>|| true — Prevents the script from stopping if the curl command exits with an error code.</p><p>Next we look up the disk usage as this is a common culprit for slowing down applications. Run the following command:</p><pre>df -P / | awk &#39;NR == 2 {gsub(&quot;%&quot;,&quot;&quot;,$5); print $5}&#39;</pre><p>df -p / — displays disk space usage for the root filesystem</p><p>awk ‘NR == 2 …’ — Processes only the second row<strong> </strong>of the text (skipping the header row)</p><p>gsub(“%”, “”, $5) — Finds the fifth column ($5), which holds the use percantage and remove the percantage sign</p><p>print $5 — print the cleaned percentage value</p><p>Lastly, we check for available memory. Execute the following command:</p><pre>free -m | awk &#39;/^Mem:/ {print $7}&#39;</pre><p>free -m — displays total used and free system memory</p><p>awk ‘/Mem:…’ — Filters the output to the line starting with <em>Mem:</em></p><p>print $7 — prints the seventh column of that specific line</p><p>Now for the full script you can use:</p><pre>1 #!/bin/bash<br>2 set -u<br>3 full_name=&quot;Your name&quot;<br>4 service_name=&quot;nginx&quot;<br>5 target_url=&quot;http://localhost&quot;<br>6 disk_warning_threshold=80<br>7 disk_failure_threshold=90<br>8 memory_warning_mb=100<br>9 base_dir=&quot;$(cd &quot;$(dirname &quot;${BASH_SOURCE[0]}&quot;)/..&quot; &amp;&amp; pwd)&quot;<br>10 report_dir=&quot;$base_dir/reports&quot;<br>11 report_file=&quot;$report_dir/linux-health-report.txt&quot;<br>12<br>13 checks=(<br>14 check_service<br>15 check_port<br>16 check_http<br>17 check_disk<br>18 check_memory<br>19 )<br>20<br>21 pass_count=0<br>22 warning_count=0<br>23 failure_count=0<br>24 mkdir -p &quot;$report_dir&quot;<br>25<br>26 :&gt;&quot;$report_file&quot;<br>27<br>28 write_line(){<br>29 echo &quot;$1&quot; | tee -a &quot;$report_file&quot;<br>30 }<br>31<br>32 mark_pass(){<br>33 write_line &quot;[PASS] $1&quot;<br>34 pass_count=$((pass_count + 1))<br>35 }<br>36<br>37 mark_warning(){<br>38 write_line &quot;[WARN] $1&quot;<br>39 warning_count=$((warning_count + 1))<br>40 }<br>41<br>42 mark_failure(){<br>43 write_line &quot;[FAIL] $1&quot;<br>44 failure_count=$((failure_count + 1))<br>45 }<br>46<br>47 print_header(){<br>48 write_line &quot;==============================================&quot;<br>50 write_line &quot;Linux Incident Triage Report&quot;<br>51 write_line &quot;==============================================&quot;<br>53 write_line &quot;Full Name: $full_name&quot;<br>54 write_line &quot;Timestamp: $(date -u &#39;+%Y-%m-%dT%H:%M:%SZ&#39;)&quot;<br>55 write_line &quot;Hostname: $(hostname)&quot;<br>56 write_line &quot;Target Service: $service_name&quot;<br>57 write_line &quot;Target URL: $target_url&quot;<br>58 write_line &quot;&quot;<br>59 }<br>60<br>61 check_service(){<br>62 if systemctl is-active --quiet &quot;$service_name&quot;<br>63 then<br>64 mark_pass &quot;Nginx service is active&quot;<br>65 else<br>66 mark_failure &quot;Nginx service is not active&quot;<br>67 fi<br>68 }<br>69<br>70 check_port(){<br>71 if ss -ltn | awk &#39;NR &gt; 1 {print $4}&#39; | grep -qE &#39;:80$&#39;<br>72 then<br>73 mark_pass &quot;Port 80 is listening&quot;<br>74 else<br>75 mark_failure &quot;Port 80 is not listening&quot;<br>76 fi<br>77 }<br>78<br>79 check_http(){<br>80 local http_code<br>81 http_code=$(curl -s -o /dev/null -w &#39;%{http_code}&#39; --max-time 5 &quot;$target_url&quot; || true)<br>82 if [ -z &quot;$http_code&quot; ]<br>83 then<br>84 http_code=&quot;000&quot;<br>85 fi<br>86<br>87 if [ &quot;$http_code&quot; = &quot;200&quot; ]<br>88 then<br>89 mark_pass &quot;Local HTTP check returned status $http_code&quot;<br>90 else<br>91 mark_failure &quot;Local HTTP check returned status $http_code&quot;<br>92 fi<br>93 }<br>94<br>95 check_disk(){<br>96 local disk_usage<br>97 disk_usage=$(df -P / | awk &#39;NR == 2 {gsub(&quot;%&quot;,&quot;&quot;,$5); print $5}&#39;)<br>98 if [ &quot;$disk_usage&quot; -ge &quot;$disk_failure_threshold&quot; ]<br>99 then<br>100 mark_failure &quot;Root disk usage is ${disk_usage}%&quot;<br>101 elif [ &quot;$disk_usage&quot; -ge &quot;$disk_warning_threshold&quot; ]<br>102 then<br>103 mark_warning &quot;Root disk usage is ${disk_usage}%&quot;<br>104 else<br>105 mark_pass &quot;Root disk usage is ${disk_usage}%&quot;<br>106 fi<br>107 }<br>108<br>109 check_memory(){<br>110 local available_memory<br>111 available_memory=$(free -m | awk &#39;/^Mem:/ {print $7}&#39;)<br>112 if [ &quot;$available_memory&quot; -lt &quot;$memory_warning_mb&quot; ]<br>113 then<br>114 mark_warning &quot;Available memory is ${available_memory} MB&quot;<br>115 else<br>116 mark_pass &quot;Available memory is ${available_memory} MB&quot;<br>117 fi<br>118 }<br>119<br>120 capture_recent_logs(){<br>121 local log_output<br>122 write_line &quot;&quot;<br>123 write_line &quot;Recent Nginx service logs (last 5 lines):&quot;<br>124 log_output=$(journalctl -u &quot;$service_name&quot; --no-pager -n 5 2&gt;/dev/null || true)<br>125 if [ -n &quot;$log_output&quot; ]<br>126 then<br>127 echo &quot;$log_output&quot; | sed &#39;s/^//&#39; | tee -a &quot;$report_file&quot;<br>128 else<br>129 write_line &quot;No readable Nginx journal entries were found.&quot;<br>130 fi<br>131 }<br>132<br>133 print_summary(){<br>134 local overall_status<br>135 local script_exit_code<br>136 if [ &quot;$failure_count&quot; -gt 0 ]<br>137 then<br>138 overall_status=&quot;FAIL&quot;<br>139 script_exit_code=2<br>140 elif [ &quot;$warning_count&quot; -gt 0 ]<br>141 then<br>142 overall_status=&quot;WARN&quot;<br>143 script_exit_code=1<br>144 else<br>145 overall_status=&quot;HEALTHY&quot;<br>146 script_exit_code=0<br>147 fi<br>148<br>149 write_line &quot;&quot;<br>150 write_line &quot;Summary:&quot;<br>151 write_line &quot;PASS: $pass_count&quot;<br>152 write_line &quot;WARN: $warning_count&quot;<br>153 write_line &quot;FAIL: $failure_count&quot;<br>154 write_line &quot;Overall Status: $overall_status&quot;<br>155 write_line &quot;Script Exit Code: $script_exit_code&quot;<br>156 write_line &quot;Report File: $report_file&quot;<br>157 return &quot;$script_exit_code&quot;<br>158 }<br>159<br>160 print_header<br>161 for check_function in &quot;${checks[@]}&quot;<br>162 do<br>163 &quot;$check_function&quot;<br>164 done<br>165<br>166 capture_recent_logs<br>167 print_summary<br>168 exit $?</pre><p>After generating a report we can use claude agent to analyse the report and guide us on the next steps. You can install claude to your machine then login. For installation on your linux machine use the following command:</p><pre>curl -fsSL https://claude.ai/install.sh | bash</pre><p>Next to add it to path to enable you run command from terminal, run:</p><pre>echo &#39;export PATH=&quot;$HOME/.local/bin:$PATH&quot;&#39; &gt;&gt; ~/.bashrc &amp;&amp; source ~/.bashrc</pre><p>After run the command claude - -version to ensure it has installed correctly. You can then proceed to come up with your CLAUDE.md file containing the following:</p><ul><li>Project overview</li><li>Incident workflow</li><li>Safety rules</li><li>Output rules</li></ul><p>After writing the necessary guidelines into your CLAUDE.md, proceed to run the following prompt in your claude CLI:</p><pre>Read CLAUDE.md. Do not create or edit any files. <br>Inspect this Ubuntu server using only read-only commands. <br>Propose a Bash incident-triage plan with exactly five checks: <br>Nginx service status, port 80 listening state, localhost HTTP response, <br>root disk usage, and available memory. For each check, show the Linux command, <br>what a healthy result looks like and what a failed result means.</pre><p>Then proceed to come up with a SKILL.md ensuring it does the following:</p><ul><li>Packages the workflow into a / command so that it creates a shortcut carrying all instruction e.g.</li></ul><pre>When `/linux-triage` is invoked:<br>1. Read `CLAUDE.md` before doing anything else.<br>2. Run `bash scripts/linux-triage.sh || true`.<br>3. Read `reports/linux-health-report.txt`.<br>4. Report the following......</pre><ul><li>Controls what tools the agent is allowed to use e.g. bash, read, grep</li><li>Defines the exact execution order</li></ul><p>Upon running your skill, store a success report analysis in a seperate file as well as a simulated failure report analysis for your own reference.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdc9aad074c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DEPLOYING A REACT APP ON UBUNTU VM USING NGINX]]></title>
            <link>https://medium.com/@mark.onyango_95482/deploying-a-react-app-on-ubuntu-vm-using-nginx-ecfdca64040c?source=rss-3d56bcc1d665------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecfdca64040c</guid>
            <category><![CDATA[codewithmark]]></category>
            <dc:creator><![CDATA[Mark Onyango]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 10:51:40 GMT</pubDate>
            <atom:updated>2026-08-21T08:08:47.659Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHn7lh5e1WYGGiCvTuSELQ.jpeg" /></figure><p>In this project, I am going to be guiding you on how to take your project sitting on github and upload it to aws and eventually make it accessible on the internet. The pre-requisites for this:</p><ul><li>A simple project on GitHub</li><li>An AWS account</li></ul><p>The first step would be to launch an EC2 instance where your project will be running. Login to your AWS console, head into the AWS console and search for EC2, you will be directed to a page like the one below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kFv38kEcF9eUHGbGYZp7Yw.png" /></figure><p>Head into instances and launch an instance. Select an ubuntu AMI, please be careful choose resources that are free tier eligible only or you will get charged. For the instance type leave it at default t3.micro, create a key pair that will allow you to ssh into your ubuntu machine. Once you get to the network settings, create a security group and make sure the following are checked; allow ssh and http. If you fail to allow http, you will not be able to view your application through the public IP AWS provides. Leave the storage section default (free tier eligible) and proceed to launch your EC2 instance. You should have a page similar to the one below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*brBodOeyxMCM8nY4ck4DkQ.jpeg" /></figure><p>N/B — DO NOT FORGET TO TO STOP YOUR INSTANCE ONCE DONE. OTHERWISE AWS WILL BILL YOU. CLICK ON INSTANCE STATE BUTTON TO STOP IT.</p><p>Proceed to connect where you have two options:</p><ul><li>connect through EC2 instance connect</li><li>connect through SSH</li></ul><p>You can choose any and follow the instructions given to connect. Once you log in to your virtual machine, you can upload your project from github in three ways:</p><ol><li>Using scp (secure copy) command to copy directly from your device into the virtual machine through your ssh connection.</li></ol><pre>scp -r ./your-folder username@your_server_ip:~</pre><p>2. You can download a zipped copy from GitHub using wget (make sure you install unzip package to assist you unzip your download)</p><pre>wget https://github.com/&lt;user&gt;/&lt;repo&gt;/archive/refs/heads/&lt;branch&gt;.zip</pre><p>3. You can git clone directly from your repository.</p><pre>git clone &lt;repository-url&gt;</pre><p>The next step is to make sure you have nginx installed and running. Use the commands below:</p><pre>sudo apt update &amp;&amp; sudo apt upgrade<br>sudo apt install -y nginx<br>sudo systemctl enable nginx</pre><p>To verify nginx is running correctly:</p><pre>sudo systemctl status nginx --no-pager</pre><p>We are going to run a react app therefore install node and npm to assist us.</p><pre>sudo apt install nodejs npm</pre><p>Navigate into your application folder and run:</p><pre>sudo cd ./your-project<br>npm install<br>npm run build</pre><p>The first second command will help you generate a node modules folder and the third command is to bundle our application into a production-ready folder. Proceed to run the following commands:</p><p><em>Remeber to replace </em><strong><em>my-app</em></strong><em> with whatever you want you want to name it</em></p><pre>sudo mkdir -p /var/www/my-app (create dedicated folder for your website)<br>sudo mv ~/dist/* /var/www/my-app/ (move the newly generated dist folder)<br>sudo chown -R www-data:www-data /var/www/my-app (set nginx as file owner)<br>sudo chmod -R 755 /var/www/my-app (assign permissions to folder)</pre><p>We then proceed to configure nginx:</p><pre>sudo nano /etc/nginx/sites-available/my-app</pre><p>That will open an editor and you can paste the text below into your configuration file:</p><pre>server {<br>    listen 80;<br>    listen [::]:80;<br><br>    server_name _;<br><br>    root /var/www/my-app;<br>    index index.html;<br><br>    location / {<br>        try_files $uri $uri/ /index.html;<br>    }<br><br>    # Optional: Optimize caching for static assets<br>    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {<br>        expires max;<br>        log_not_found off;<br>    }<br>}</pre><p>Press <strong>ctrl + O</strong> and <strong>Enter</strong> to save then <strong>ctrl + x</strong> to exit our nano editor.</p><p>Lastly, you enable the site and restart nginx with the following commands:</p><pre>sudo ln -s /etc/nginx/sites-available/my-app /etc/nginx/sites-enabled/ (creates a symbolic link to enable your nginx configuration)<br>sudo unlink /etc/nginx/sites-enabled/default (To unlink the default nginx welcome page)<br>sudo nginx -t  (To test for syntax errors in your nginx configuration)<br>sudo systemctl restart nginx (Restart nginx to apply the changes)</pre><p>Next you can copy your public IP from the AWS console instance page and paste it into a new web page to access your application i.e <a href="http://10.92.34.56/">http://10.92.34.56</a> (it is http, do not add the ‘s’). There it is, you have officially hosted your react app on an EC2 and it is publicly accessible.</p><p>A few challenges you may face:</p><ul><li>You access you public IP and an error page cannot connect to &lt;your IP&gt;. Check in your security group to and make sure you have set http as an inbound rule allowed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HOh85xDXOomQHAlRwJZAVA.jpeg" /></figure><ul><li>You might not have enabled nginx, check if nginx is running and enabled:</li></ul><pre>sudo systemctl status nginx --no-pager</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*S8mdj3-VJn9yQSKvim2Y7Q.png" /></figure><p>If all is fine, you should get active(running) and enabled.</p><ul><li>You can also fetch header information for your IP</li></ul><pre>curl -I &lt;your public IP&gt;</pre><p>If all is fine, you should see a http 200 OK</p><ul><li>Check if the configuration file contains any syntax errors</li></ul><pre>sudo nginx -t</pre><p>Leave a like if you found this article informative. Happy coding!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecfdca64040c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>