<?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 Yathartha Goenka on Medium]]></title>
        <description><![CDATA[Stories by Yathartha Goenka on Medium]]></description>
        <link>https://medium.com/@yatharthagoenka?source=rss-7a6ff9acf9d5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sgwrmvJ5T9ZwY43Q3IE9ng.jpeg</url>
            <title>Stories by Yathartha Goenka on Medium</title>
            <link>https://medium.com/@yatharthagoenka?source=rss-7a6ff9acf9d5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 21:25:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yatharthagoenka/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[Enhancing Developer Experience through Mercari’s Unified Platform Interface]]></title>
            <link>https://medium.com/@yatharthagoenka/enhancing-developer-experience-through-mercaris-unified-platform-interface-9dca4f3e256b?source=rss-7a6ff9acf9d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dca4f3e256b</guid>
            <dc:creator><![CDATA[Yathartha Goenka]]></dc:creator>
            <pubDate>Sun, 25 Jan 2026 13:18:42 GMT</pubDate>
            <atom:updated>2026-01-25T13:19:26.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UFCummXkmViZYhdg.jpg" /></figure><p>For legal reasons I can’t copy that blog here. Check it out at: <a href="https://engineering.mercari.com/en/blog/entry/20251204-enhancing-developer-experience-through-mercaris-unified-platform-interface/">https://engineering.mercari.com/en/blog/entry/20251204-enhancing-developer-experience-through-mercaris-unified-platform-interface/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dca4f3e256b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[hands-on CI/CD: starter-kit]]></title>
            <link>https://medium.com/@yatharthagoenka/hands-on-ci-cd-starter-kit-4e3d4431f263?source=rss-7a6ff9acf9d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e3d4431f263</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Yathartha Goenka]]></dc:creator>
            <pubDate>Fri, 31 Jan 2025 20:16:50 GMT</pubDate>
            <atom:updated>2025-11-09T09:14:30.235Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Not a lesson, tutorial or anything enough. Just something to prove it’s more simple than it sounds.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/0*2wxVTT7WI2dt-DXG" /><figcaption><a href="https://www.redhat.com/en/topics/devops/what-is-ci-cd">https://www.redhat.com/en/topics/devops/what-is-ci-cd</a></figcaption></figure><p>Before we begin, just keep it in the back of your mind that everything about CI/CD (usually) is basically stuff you could’ve and would’ve done in your local machine’s terminal, but decided to run automatically on someone else’s.</p><h4>Context</h4><blockquote>CI/CD is a set of practices and tools designed to improve the software development process by automating builds, testing, and deployment, enabling you to ship code changes faster and reliably ~ <a href="https://github.com/resources/articles/devops/ci-cd">GitHub Articles</a></blockquote><p>That’s what every article will tell you, and it’s correct. Roughly translated to english though, this is what it means:</p><h4><strong>Continuous Integration — CI</strong></h4><ul><li>Is basically any set of code/tests/scripts that run automatically when we commit some changes into a repository. This could be when we create a commit on a branch (or PR), when that branch is merged into another or any other trigger that you set.</li><li>This could be done to ensure that the code we push is correct, passes the tests, is formatted correctly or even to manage who can change which part of the code.</li></ul><h4><strong>Continuous Delivery/Deployment — CD</strong></h4><ul><li>Is a 2-part process that performs delivery of <em>approved</em> code changes to the end user. Difference between the two is that <em>“continuous delivery”</em> will ensure and prepare changes to be released to set environments (take production for example), but not actually change for production for the end-user to see those changes. Doing so will require manual approval by a user/owner before it is pushed to production. On the other hand, <em>“continuous deployment” </em>will say “syke!” and change production directly when you merge your tested/approved changes (without manual review).</li><li>Continuous Delivery’s “manual judgement” could be a button you click, an email you reply to, a slack message you put a sticker on or a release tag you create on the repo. Totally up to you.</li></ul><p><strong>Pipeline:</strong> is<strong> </strong>basically just all of this running on whatever machine you choose. You commit something, that commit starts a script/workflow which runs some operations to validate those changes (CI). Once merged, the changes are pushed somewhere else (CD). This is simply called a “CI/CD pipeline”.</p><h3>You know what, let’s build it.</h3><p>I created a repository to lay down some actual code, see it running and get out of theoretical reading: <a href="https://github.com/yatharthagoenka/sandbox">https://github.com/whhygee/sandbox</a>/</p><blockquote><strong>note</strong>: you do not need to understand terraform or the code I used to grasp the concepts in this article. Also if you’re curious, I used IAM resources because that’s one of the very few things that didn’t require me to setup a billing account XD</blockquote><h4><strong>Defining a CI workflow:</strong></h4><p>For simplicity’s sake, I set up some simple terraform configurations and a “CI workflow” to run terraform commands on GH’s machine to make sure my code is valid and correctly formatted before being merged into master. If it’s not, it will throw an error and won’t let me merge my PR (this behavior is ensured through <a href="http://The base branch does not allow updates">branch protection</a>).</p><p>I‘m using <a href="https://docs.github.com/en/actions">GH Actions</a> but you could set up any of those fancy tools like Jenkins, CloudBuild, Flow, CircleCI based on the context. To keep this short, I won’t get into the weeds of code and only attach links to relevant files:</p><ul><li><a href="https://github.com/yatharthagoenka/sandbox/tree/master/terraform">Terraform Configurations</a></li><li><a href="https://github.com/yatharthagoenka/sandbox/blob/master/.github/workflows/ci-validate-terraform.yml">GH Workflow</a></li></ul><p><strong>Actual Behavior:</strong></p><p>I pushed code with incorrect formatting and surely enough, it did fail. As per the branch protection we set, all checks (in our case, the <a href="https://github.com/yatharthagoenka/sandbox/blob/master/.github/workflows/ci-validate-terraform.yml">workflow</a> we created) need to pass successfully before the code can be merged.<br>PR: <a href="https://github.com/yatharthagoenka/sandbox/pull/1">https://github.com/whhygee/sandbox/pull/1</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*waBWX_M3bA-PqTb65z44oQ.png" /><figcaption>CI check against a PR on master</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mf5tH4hMLX6EaQEMAYklEg.png" /><figcaption>Branch Protection Ruleset — Status Check</figcaption></figure><h4>Defining a CD workflow:</h4><p>Integration was up till the point our PR wasn’t merged into origin/master (often referred to as “shared repository” or “source”). Once merged, we want to see those changes reflect in production.</p><blockquote>“production” could be anything from an application, service, static webpage, cloud resources etc. In our context, it’s the actual GCP resource. If it were an application/webpage, we’d write some code to push changes to our server but since we’re using terraform, we can just use terraform apply to sync our changes.<br><a href="https://developer.hashicorp.com/terraform/cli/commands/apply">Learn more about ‘terraform apply’ here.</a></blockquote><p>I configured this workflow to trigger upon commits to master and since it doesn’t require explicit manual approval, I believe we can call it “continuous deployment”.</p><ul><li><a href="https://github.com/yatharthagoenka/sandbox/blob/master/.github/workflows/cd-terraform-apply.yml">‘terraform apply’ Workflow</a></li></ul><p>I didn’t setup actual credentials on this repository to shield myself from doxxing and bankrupting myself, but you can setup your repos with all the variables and GCP credentials required by terraform to apply changes, and that’ll do the trick for you.</p><p>This might help with setting that up: <a href="https://jozimarback.medium.com/using-github-actions-with-terraform-on-gcp-d473a37ddbd6">https://jozimarback.medium.com/using-github-actions-with-terraform-on-gcp-d473a37ddbd6</a>.</p><p>— — — — — — — — — — — — — — — — — — — — — — — —</p><p>And there you have it: a very mindful, very demure <strong>CI/CD pipeline</strong>. now FAAFO.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e3d4431f263" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying multiple SPAs using AWS Cloudfront and S3 with Lamda@Edge as pseudo reverse-proxy]]></title>
            <link>https://medium.com/@yatharthagoenka/deploying-multiple-spas-using-aws-cloudfront-and-s3-with-lamda-edge-as-pseudo-reverse-proxy-8f6314531885?source=rss-7a6ff9acf9d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f6314531885</guid>
            <category><![CDATA[web-hosting]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[s3]]></category>
            <dc:creator><![CDATA[Yathartha Goenka]]></dc:creator>
            <pubDate>Sat, 01 Jul 2023 07:51:11 GMT</pubDate>
            <atom:updated>2023-07-01T07:52:25.631Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RiXfG5HUaMBMo581.png" /></figure><p>Web Hosting is always a crucial part of the development process for any application, especially when it comes to catering to a larger or widespread audience. Therefore, instead of diving straight into the technicalities, let’s give you a quick context of the tools and technologies at use here in order to put things into a clearer perspective.</p><h4>Components:</h4><ol><li><a href="#c715"><strong>A walk in the park</strong></a></li><li><a href="#0f5e"><strong>The Problem</strong></a> : Client-Side Routing with CloudFront / S3</li><li><a href="#dd2e"><strong>Solution</strong></a> : Lambda@Edge Function as pseudo reverse proxy</li></ol><h4>Amazon CloudFront</h4><p>Amazon CloudFront is a content delivery network (<strong>CDN</strong>) service built for high performance, security, and developer convenience. In layman terms, it helps deliver your website to the end user <em>faster, </em>no matter where they’re accessing it from. The way it achieves this is by storing a <strong>cache</strong> of requested files on edge locations once a user visits the website so that any subsequent requests for the same resources can be resolved without having to fetch those files again from the origin.</p><p>The “<strong>origin</strong>” in this case is wherever the files are physically present/stored. This could be an Amazon S3 bucket, a MediaStore container, a MediaPackage channel, an Application Load Balancer, an AWS Lambda function URL, an EC2 instance or any other custom origin.</p><p>You can read more about content delivery through cloudfront <a href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/HowCloudFrontWorks.html"><strong>here</strong></a>.</p><h4>Amazon S3 Buckets</h4><p><em>“Object storage built to retrieve any amount of data from anywhere”</em></p><p>As simple as it sounds, an Amazon S3 bucket is a <strong>flat, non-hierarchical</strong> storage service that hosts and manages our files as per the need. These files in our case, are the <a href="https://www.geeksforgeeks.org/what-is-the-role-of-src-and-dist-folders-in-javascript-jquery/"><strong>distributables</strong></a><strong> </strong>of our application, thus acting as an origin for the cloudfront distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jLP0es1aQ_LXFqzw.png" /></figure><h3>The Problem</h3><p>An issue with S3 buckets being a flat storage system is that it doesn’t understand folders (<a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-folders.html"><strong>read this</strong></a> to understand how S3 visualizes folders for organizational simplicity), so when you visit your website at yourdomain.com it works fine (even clicking on any link thereafter will give you the correct page), but when you directly try to access a specific route (say yourdomain.com/app/login), it tries to find the login file inside the app folder, which obviously doesn’t exist. This thing right here is called <strong>Client-Side Routing</strong>,<strong> </strong>which is not directly supported by S3. Thankfully, Cloudfront provides a very subtle workaround for this. It allows us to configure custom error pages for any kinds of HTTP error codes.</p><p>So when a “Viewer Request” comes in for <em>/app/login</em>, instead of returning a 403 error and breaking the app, it makes an “Origin Request” for the defined error page (if it isn’t cached already), which in our case will be <em>/index.html</em>. This index page has all the logic of our SPA’s router which knows exactly what <em>/app/login</em> means and thus provides us the correct page with a 200 status code. Perfect!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rp4_arWD_40JT0O6sCNv7Q.png" /><figcaption>Snippet of a sample AWS CF distribution config page</figcaption></figure><p>Okay so this setup is well and good, expect when we want to host multiple SPAs using just this CF distribution. Why? Maybe you have a dual-interface application, one for the clients and one for the admins and want to deliver each on <em>base.com/login</em> and <em>base.com/admin/login</em> respectively, or you have multiple versions of the same application and want to deploy them on their respective urls as <em>/login</em> and <em>/v2/login</em>. As the first thought (or atleast as it occured to me), you would think of going one of two ways:</p><p>1. <strong>Setting up multiple origins and configuring behaviors accordingly: </strong>Sure, you could setup two S3 buckets, one for each of the versions, put their distributables in their respective buckets and configure the default behavior of the cloudfront distribution to direct all requests with a path pattern of /<em>*</em> to origin-1 and of <em>v2/*</em> to origin-2. But not only will that cost you more, it will also <em>break during client-side routing</em> for the v2 application. i.e. as soon as you request <em>/v2/login</em>, it will return <em>/index.html</em> as the error page, which contains logic for the router of v1, and won’t have any knowledge of the routes of the v2 application, thus not knowing what <em>/v2/login </em>means.</p><p>2.<strong> Using a single origin with v2 distributables stored with /v2 prefix in S3</strong></p><p>Now you think of setting up a single bucket and storing all distributable files of the v2 application in a “folder” named v2. Now again, try to visit “<em>yourdomain.com/v2/index.html</em>” and your v2 application will load perfectly. But again, it will crash as soon as you try client-side routing.Why? It’s the same song, the error page of <em>/index.html</em> has no knowledge of v2 routes. Similarly, setting <em>/v2/index.html </em>as the error page will work fine for v2, but will have no knowledge of the v1 routes.</p><p>Now that we’ve exhausted much of our patience, let’s use <strong>Lambda@Edge</strong> functions to help with the routing conundrum.</p><h3>Lambda@Edge as pseudo reverse-proxy</h3><p>Turns out, the single origin setup was in the right direction, but it just needs a one last piece — Lambda@Edge. I’m not going to dwell in the specifics of <a href="https://aws.amazon.com/lambda/edge/">Lambda@Edge</a> or <a href="https://docs.aws.amazon.com/lambda/latest/dg/welcome.html">Lambda functions</a> in general, but you should give it a read if you’re unfamiliar with the concept.</p><p>Now let’s sit back for a second and take a look at the problem again. We have two applications (vis v1 and v2), one in the root of our S3 bucket and another in a “folder” called v2. We want to achieve a setup wherein the requests following a path pattern of ‘<em>*’ </em>are redirected to the application in the root — which is indeed the default behavior of cloudfront — and the ones with ‘/<em>v2/*’</em> to the application inside the ‘v2’ directory. So even with an error code of 403/404, the requests for v2 routes will be handled by its corresponding router.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*HHpJl4DqVvZgpUn4.png" /><figcaption>Request flow on Cloudfront cache</figcaption></figure><p>Follow <a href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-edge-how-it-works-tutorial.html">the attached article</a> by AWS to create and attach a Lamda@Edge function to your cloudfront distribution. In our case, the function will be <strong>triggered on ‘Origin Request’</strong>, wherein the request url is changed to return the respective index file to the regional cache, which processes the requested route in the ‘Viewer Request’ and returns the corresponding page as the ‘Viewer Response’ to the end-user.</p><p>This is also why I call it a “pseudo” reverse-proxy, for it doesn’t distribute the requests to multiple origins but only manipulates the request uri, in-effect acting as a proxy between multiple applications.</p><p>Seems pretty straightforward doesn’t it? Well, it is! Here’s the code for a lambda@edge function, running inside a <em>Node 18.x environment</em>, that implements this functionality for us:</p><pre>import * as path from &#39;path&#39;<br><br>export const handler = async (event, context, callback) =&gt; {<br>  const { request } = event.Records[0].cf;<br>  <br>  const parsedPath = path.parse(request.uri);<br><br>  if (parsedPath.ext === &#39;&#39;) {<br>    var newuri = request.uri.replace(/v2.*/, &#39;v2/index.html&#39;);<br>    request.uri = newuri;<br>  }<br><br>  console.log(&quot;REQUEST_URI&quot;+request.uri)<br><br>  callback(null, request);<br>};</pre><p>Why do we check for a path with no extension? Such a path typically refers to a route that doesn’t correspond to a specific file on the server and is instead a <strong>virtual route</strong> within the SPA itself. This would mean that the request isn’t for a particular file lying in our S3 bucket, but instead a route only to be handled by the application. It is thus forwarded to the index file of its corresponding app, which would identify and return the requested resource thereafter.</p><blockquote>Tip: You can use <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html"><strong>CloudWatch</strong></a><strong> </strong>to monitor the working of this lambda function as well as the logs generated using runtime.</blockquote><h3><strong>Why not CloudFront Functions?</strong></h3><p><em>“With CloudFront Functions in Amazon CloudFront, you can write lightweight functions in JavaScript for high-scale, latency-sensitive CDN customizations”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YsChfZdrVByG0UNa.png" /></figure><p>Translated in english, they’re a more lightweight version of Lambda@Edge functions which handle workloads requiring less than 1 milliseconds of execution time, at approximately 1/6th the price of Lambda@Edge</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K2pr-d74MZIluODme96sBA.png" /><figcaption>Detailed comparison of CloudFront Functions vs Lambda@Edge</figcaption></figure><p>At first glance, this might really seem like the better choice — being way more lightweight for that much cheaper (not that Lambda functions are making you go bankrupt either) — but they really aren’t… not yet anyway.</p><p>While Lambda@Edge functions can be triggered before or after the request and response reach the Regional cache, CloudFront Functions can only be triggered on ‘Viewer Request’ and ‘Viewer Response’. They are ideal for use cases like the following:</p><ul><li>Cache key normalization</li><li>Header manipulation</li><li>Status code modification and body generation</li><li>URL redirects or rewrites</li><li>Request authorization</li></ul><p>Don’t confuse URL redirects with what we were trying to achieve with our lambda function. We don’t want to redirect the user to another page when they make a certain request; rather, we want to fetch the correct resource (based on the request uri), so as to provide the user with the intended results catering to multiple applications. Therefore, we need not modify the Viewer Request, but rather than ‘Origin Request’, wherein the error page for the corresponding application will be returned for processing the route inside the viewer request.</p><p>That’s how you fit the final piece of your deployment setup in, upon completion of which you can successfully access both of your applications on their respective routes using a single CF Distribution and Origin.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f6314531885" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A detailed introduction to microservices]]></title>
            <link>https://medium.com/@yatharthagoenka/what-colour-is-your-microservice-b95bd37282a8?source=rss-7a6ff9acf9d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b95bd37282a8</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[oops-concepts]]></category>
            <dc:creator><![CDATA[Yathartha Goenka]]></dc:creator>
            <pubDate>Fri, 12 May 2023 13:37:31 GMT</pubDate>
            <atom:updated>2023-07-01T10:37:11.441Z</atom:updated>
            <content:encoded><![CDATA[<h3>A detailed insight into microservices and its applications</h3><h4>an easier approach</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hVe_nx0FKXeUOmb3.png" /></figure><p><em>“Microservices are an architectural and organisational approach to software development where software is composed of small independent services that communicate over well-defined APIs” </em>~ Amazon Web Services</p><h3>Components:</h3><ol><li><a href="#f9eb">Understanding microservices</a></li><li><a href="#404b">SOLID Principles [ OOPs ]</a></li><li><a href="#dbec">Stepping into the real world</a></li></ol><p>Okay so before we dive into what it really means, let’s clear out the common misconception of its place in the development lifecycle. Is it said to be a part of Cloud Computing? DevOps? Well, while it does utilise those concepts, it is actually “a style of <strong>system architecture</strong>” wherein more than one services — independent and loosely-coupled — work together as a part of a system, communicating through lightweight APIs.</p><p>A microservices architecture is a <a href="https://www.redhat.com/en/topics/cloud-native-apps"><strong>cloud-native</strong></a> approach to building software in a way that allows for each core function within an application to exist independently.</p><p>A cloud native approach, in its most basic sense, is where the system or the software is designed in such a way that it makes good use of the elasticity, resiliency, and flexibility that the cloud provides, while also staying scalable.</p><ul><li><em>Flexibility</em> could be in terms of the more compute power available to multiple services and being able to meet the “right-size infrastructure needs” of the applications.</li><li><em>Resiliency</em> may be noticed in cases where if one piece (one or more connected services) of the system fails, the rest of the infrastructure remains active.</li></ul><p>Of course, these are not the only things that microservices bring on the table. I’ve come across a bunch of blogs detailing the rest in much technical detail, so I’d suggest you to go through them once before continuing with this post (cause who wants redundancy?):</p><ol><li><a href="https://aws.amazon.com/microservices/">https://aws.amazon.com/microservices/</a></li><li><a href="https://www.ibm.com/topics/microservices">https://www.ibm.com/topics/microservices</a></li><li><a href="https://www.redhat.com/en/topics/microservices/what-are-microservices">https://www.redhat.com/en/topics/microservices/what-are-microservices</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FrEiqRLEPm1WNWyIlwiNYg.jpeg" /></figure><h4>All well and good, but WHYYYYY microservices?</h4><p><strong>Apart from</strong> what you must’ve read on all these posts, one point that I didn’t find clearly mentioned in the majority of them regarding the reason for the use of microservices is <strong>‘Separation of concerns’</strong>,<strong> </strong>probably one of the most principle concepts introducing the need for microservices, a concept that goes hand-in-hand with the SOLID principles originally presented as a part of ‘Object-Oriented Programming’</p><p>The principle is simple: don’t write your program as one solid block, instead, break up the code into chunks that are independently functioning tiny pieces of the system, each able to complete a simple distinct job. In other words, if your system is concerned with multiple functionalities, all/some of which are either computationally intensive or require a different stack of technologies, it’s better to separate them loosely-coupled independent “services” that communicate with each other as per the requirements of the system.</p><h3>OOPs in microservices : SOLID Principles</h3><p>The principles originally quoted as parts of Object Oriented Programming, however obscure they may seem, are kept in mind while designing a microservices architecture. Let’s see how:</p><p><strong>Single Responsibility Principle</strong> : States that there should be just one reason for a class to change. Roughly translated, a class should only be concerned with providing just one service at any time. The benefits of this principle are obvious — it reduces complexity and improves flexibility, extensibility, and maintenance.</p><p><strong>Open Closed Principle</strong> : States that software entities should be open for extension but closed for modification. This means that we should be able to change what a module does without modifying any existing working code. A ‘<a href="https://www.google.com/search?client=safari&amp;rls=en&amp;q=open+closed+principle+in+microservices&amp;ie=UTF-8&amp;oe=UTF-8">domain-driven design</a>’ is a close example of the use of this principle in microservices.</p><p><strong>Liskov Substitution Principle : </strong>States that objects of a superclass should be replaceable with objects of its subclasses without altering the intended behaviour of the program. In object-oriented programming this is called a <em>God object</em> — an object that either knows too much or does too much. This can also be observed in the case of microservices, wherein we create one or more services that do too much, as it is usually easier to implement.</p><p><strong>Interface Segregation Principle : </strong>States that an object should only depend on the interfaces it requires and shouldn’t be forced to implement anything else. In object-oriented programming, this is called <em>method chaining, </em>which<em> </em>when applied to microservices, can be seen when we chain too many microservices calls together. It’s best to keep the call stack as shallow as possible to avoid rippling failures.</p><p><strong>Dependency Inversion Principle : </strong>States that abstractions should not depend upon details, but details should instead depend upon abstractions. In simpler words, it means that high-level modules should not depend on low-level modules. In a microservices architecture, this translates to the <a href="https://www.theserverside.com/answer/How-do-microservices-API-gateways-aid-monolith-migrations">API gateway pattern</a>. Just as the client owns the API defined by the API gateway, a higher-level module should own the service interface.</p><p><em>(How</em> <em>did I find out about it? Got drilled in an interview for giving the wrong answer to the “Why” question. Much grateful though!)</em></p><h3>Stepping into the real world</h3><h4>A brief example — BlueCloud</h4><p>Bluecloud is a system that deals with cryptographic encryption of files and storage on a cloud server (a linux-based AWS ec-2 instance). The idea was to enable users to store their files securely on the cloud by encrypting the data during upload (using cryptographic algorithms like AES, ChaCha, AESGCM, AESCCM). The encryption service was written on and made use of relevant libraries in Python, in contrast to my auth and user services, which were built on, managed by and run through NestJS/ExpressJS. Now, my initial approach was definitely building a monolith where the encryption service (which were just a couple of scripts at that time) was spun up as a child process every time the upload route was hit, since neither of the services were much resource intensive at that point (over-engineering kills, by the way).</p><p>But things took a different turn when I went about containerising this monolith into a single docker container (I’m still open to ideas for achieving this). A single container didn’t allow for both environments to be setup and run inside, which consequently made me translate the individually-called python scripts into a flask server, containerised and deployed independently along with the NestJS service. Both of these communicate through REST, wherein a common storage is mounted as a volume to both containers for coordinating the read/write operations.</p><p><em>(You can take a deeper look into the project at: </em><a href="https://github.com/yatharthagoenka/BlueCloud"><em>https://github.com/yatharthagoenka/BlueCloud</em></a><em>)</em></p><h4>Are microservices always the right way to go?</h4><p>While this has revolutionised the way systems are designed, it still depends highly on the use-case, scope and scenario of the system under investigation.</p><p>The biggest example of this case that I can think of at this moment is how Amazon moved the architecture of its Prime Video audio/video monitoring service from microservices to a monolith, which helped achieve higher scale, resilience, and reduced costs by 90%.</p><p><em>“Moving our service to a monolith reduced our infrastructure cost by over 90%. It also increased our scaling capabilities. Today, we’re able to handle thousands of streams and we still have capacity to scale the service even further.” ~ AWS</em></p><p>The following diagram shows the architecture of the system after migrating to the monolith.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oePFD_ml8Egoa6WL.png" /></figure><p>The media converter (which was earlier another service running separately) and the instance memory (previously an Amazon S3 bucket) were moved into a monolithic application.</p><p>You can read more about the case on their official blog: <a href="https://www.primevideotech.com/video-streaming/scaling-up-the-prime-video-audio-video-monitoring-service-and-reducing-costs-by-90">https://www.primevideotech.com/video-streaming/scaling-up-the-prime-video-audio-video-monitoring-service-and-reducing-costs-by-90</a></p><p><strong>Recommended watch</strong>: <a href="https://www.youtube.com/watch?v=dV3wAe8HV7Q">https://www.youtube.com/watch?v=dV3wAe8HV7Q</a></p><p>That’s it from my side. I am aware that this post isn’t a one-stop shop for every principle mentioned, as each one is an extensive concept on its own and would be hard to fit inside the scope of this article. I suggest you to explore every concept in more depth hereafter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b95bd37282a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containerizing and load balancing a NestJS application with Docker and Nginx]]></title>
            <link>https://medium.com/@yatharthagoenka/containerizing-and-load-balancing-a-nestjs-application-with-docker-and-nginx-984aa5563caa?source=rss-7a6ff9acf9d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/984aa5563caa</guid>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Yathartha Goenka]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 13:57:12 GMT</pubDate>
            <atom:updated>2023-03-15T14:02:55.799Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*9a2IyFg3kefMBzX3B5VjbA.png" /></figure><p>The post is divided into two parts:</p><ul><li><a href="https://medium.com/@goenkayathartha2002/containerizing-and-load-balancing-a-nestjs-application-with-docker-and-nginx-8b14217262aa">Containerizing a Node/NestJS application using Docker.</a></li><li><a href="https://medium.com/@goenkayathartha2002/containerizing-and-load-balancing-a-nestjs-application-with-docker-and-nginx-984aa5563caa">Load balancing an application using Nginx.</a></li></ul><p>This guide will drive you through the principles of NGINX: what is load balancing, how does NGINX fit into the scope and how to implement it in your own application.</p><blockquote><em>In case you require context about the application worked upon in this article, read about it in the first part of the post at:</em><br><a href="https://medium.com/@goenkayathartha2002/containerizing-and-load-balancing-a-nestjs-application-with-docker-and-nginx-8b14217262aa">https://medium.com/@goenkayathartha2002/containerizing-and-load-balancing-a-nestjs-application-with-docker-and-nginx-8b14217262aa</a></blockquote><h4>Components:</h4><ol><li><a href="#d77d">What do we mean by load balancing?</a></li><li><a href="#1534">NGINX</a></li><li><a href="#eb6b">Load Balancing the application using NGINX</a></li><li><a href="#b539">Microservices architecture using NestJS</a></li></ol><h3>Load Balancing</h3><blockquote>Load balancing is the process of distributing network traffic across multiple servers to ensure that no single server becomes overwhelmed with requests.</blockquote><p>Long story short, load balancing is typically needed when a single server or instance cannot handle the amount of traffic or workload required by an application or service. By lowering reaction times and preventing downtime, the goal is to maximise the utilisation of computer resources, boost availability and dependability, and improve performance. It is possible to perform load balancing at several layers of the network stack, including the application, transport, and network layers, using hardware- or software-based methods.</p><h3>NGINX</h3><blockquote>NGINX is an open-source web server software designed to handle high traffic websites.</blockquote><p>It can be used as a standalone web server or as a reverse proxy in front of other web servers. It is known for its high performance, stability, and scalability, and is often used as a load balancer to distribute traffic across multiple servers to optimize resource utilization, maximize throughput, minimize response time, and avoid downtime or system failure.</p><blockquote>Nginx Installation guide: <a href="https://www.nginx.com/resources/wiki/start/topics/tutorials/install/">https://www.nginx.com/resources/wiki/start/topics/tutorials/install/</a></blockquote><h3>Load Balancing the application using NGINX</h3><p>NGinx, as explained earlier, will be used as a reverse proxy for the multiple instances of our server application. Note that these instances may be run on different cloud vm instances or different IPs, which would need to be mentioned respectively in the nginx.conf file.</p><p>For this application, we will be creating a “Docker network” inside which all of our containers will be running. This is essential for the load balancer to be able to connect to these containers and communicate with them.</p><pre>docker network create test-network</pre><p>Now that we have a new network, we need to create multiple instances of our server application to balance the load between and configure all of them to connect to the same test-network that we created just now. To do that, we will simply modify the docker-compose file as follows:</p><pre>version: &#39;3&#39;<br>networks:<br>  test-network:<br>    external: true<br>services:<br>  db:<br>    container_name: db_1<br>    image: mongo:4.4<br>    ports:<br>      - &quot;27015:27017&quot;<br>    volumes:<br>      - mongo-data:/data/db<br>    networks:<br>      - test-network<br>  app1:<br>    image: server_app<br>    container_name: app_1<br>    build: .<br>    ports:<br>      - &quot;3001:3001&quot;<br>    environment:<br>      - SERVER_PORT=3001<br>      - MONGO_URI=mongodb://db:27017<br>    depends_on:<br>      - db<br>    networks:<br>      - test-network<br>  app2:<br>    image: server_app<br>    container_name: app_2<br>    build: .<br>    ports:<br>      - &quot;3002:3002&quot;<br>    environment:<br>      - SERVER_PORT=3002<br>      - MONGO_URI=mongodb://db:27017<br>    depends_on:<br>      - db<br>    networks:<br>      - test-network<br>volumes:<br>  mongo-data:</pre><blockquote>The ‘external: true’ option is used to indicate that the network being defined is not managed by Docker Compose, but is instead created externally.</blockquote><p>— — — — — — — — —</p><blockquote>Notice how both of our apps use the same image ‘server_app’? That’s because we want the exact same code to be run on different ports for them to act as multiple instances of our server.</blockquote><p>Now that we can this in place, let’s configure nginx to work as a reverse proxy for our applications by creating a new configuration file in /etc/nginx/conf.d directory:</p><pre>sudo nano /etc/nginx/conf.d/nginx.conf</pre><p>and paste the following code in it :</p><pre>upstream servers {<br>    server &lt;IP_ADDRESS_1&gt;:&lt;PORT&gt;;<br>    server &lt;IP_ADDRESS_2&gt;:&lt;PORT&gt;;<br>}</pre><pre>server {<br>    listen 3000;</pre><pre>    location / {<br>        proxy_pass <a href="http://servers;/">http://servers;</a><br>    }<br>}</pre><p>Note that there are a bunch of other settings you can play around with in the nginx configuration, but I’ll keep things simple for now. <br>So what this file does is it tells nginx to listen on the port 3000, and act as a proxy for the upstream servers that we have specified above.</p><blockquote>Replace <em>&lt;IP_ADDRESS_1&gt;</em> and <em>&lt;IP_ADDRESS_2&gt;</em> with the IP addresses of the two instances of NestJS Docker apps, and <em>&lt;PORT&gt;</em> with the port number used by your NestJS app.</blockquote><blockquote>Given below is the exact example ‘nginx.conf ’ file for this specific usecase.</blockquote><p>To test the Nginx configuration and restart the Nginx service, run:</p><pre>sudo nginx -t<br>sudo systemctl restart nginx</pre><h4>Containerizing the load-balancer</h4><p>Again, this nginx configuration seems like a handful. We can also containerize this into another docker container by specifying new Dockerfile and docker-compose.yml files in another directory as such :</p><pre>FROM nginx:latest</pre><pre>RUN rm /etc/nginx/conf.d/default.conf</pre><pre>COPY nginx.conf /etc/nginx/conf.d/</pre><pre>EXPOSE 3000</pre><pre>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><pre>version: &#39;3&#39;<br>networks:<br>  test-network:<br>    external: true<br>services:<br>  nginx:<br>    build: .<br>    ports:<br>      - &quot;3000:3000&quot;<br>    networks:<br>      - test-network<br>    volumes:<br>      - ./nginx.conf:/etc/nginx/nginx.conf</pre><blockquote>Note how we’ve specified the load balancer to run in the same network as our application instances.</blockquote><p>Running this container will setup nginx as a load balancer between the two applications. Since all these containers are running inside the same docker network, we can reference our app instances using their container names in the configuration file as follows:</p><pre>upstream servers {<br>    server app_1:3001;<br>    server app_2:3002;<br>}</pre><pre>server {<br>    # setting protocol for balancing<br>    least_conn<br>    listen 3000;</pre><pre>    location / {<br>        proxy_pass <a href="http://servers;/">http://servers;</a><br>    }<br>}</pre><p>An important configuration mentioned above is the protocol for balancing between our instances. Nginx provides us with the following options:</p><ul><li>round_robin (Default)</li><li>least_conn</li><li>ip_hash</li><li>least_time</li></ul><h3>⭐ Microservices application using NestJS</h3><blockquote>Microservices architecture is a software design pattern in which an application is composed of a collection of loosely-coupled, independently deployable services that communicate with each other over a network.</blockquote><p>First things first, NestJS is a framework for building scalable and efficient server-side applications with Node.js. It is built on top of Express.js and provides a powerful set of features for web development, including dependency injection, middleware, routing, and more. (Yes, I googled that one). NestJS has a modular design that enables us to separate our work into smaller, more manageable components. Moreover, NestJS offers a simple method for implementing inter-service communication, which is essential in a microservices design.</p><ol><li>In NestJS, you can break your application into microservices using the built-in @nestjs/microservices package. This package allows you to define and create microservices within your NestJS application.</li><li>Next, you’ll need to define your microservices in your NestJS application. This involves setting up communication protocols, such as TCP or UDP, and defining the endpoints for each microservice.</li><li>Alternatively, you can reate separate services that communicate with each other through an API or message broker.</li></ol><p>We’ll dive deeper into this in one of your next posts. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=984aa5563caa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containerising and load balancing a NestJS application with Docker and Nginx]]></title>
            <link>https://medium.com/@yatharthagoenka/containerizing-and-load-balancing-a-nestjs-application-with-docker-and-nginx-8b14217262aa?source=rss-7a6ff9acf9d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b14217262aa</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Yathartha Goenka]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 13:54:02 GMT</pubDate>
            <atom:updated>2023-07-09T08:57:12.372Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IXYVE8jtZaQeAUT9SC8X9Q.jpeg" /><figcaption>Fun Fact: NodeJS is used by 47.12% of the current IT professionals.</figcaption></figure><p>The post is divided into two parts:</p><ul><li><a href="https://medium.com/@goenkayathartha2002/containerizing-and-load-balancing-a-nestjs-application-with-docker-and-nginx-8b14217262aa">Containerizing a Node/NestJS application using Docker.</a></li><li><a href="https://medium.com/@goenkayathartha2002/containerizing-and-load-balancing-a-nestjs-application-with-docker-and-nginx-984aa5563caa">Load balancing an application using Nginx.</a></li></ul><p>This guide will drive you through the foundations of docker: what it is, why is it a hype in the industry and how to implement and use it in your own applications.</p><p>(Don’t worry, I know what boring theory sounds like so I’ll try to keep it brief throughout the post. In case you’re familiar with the concept, feel free to <a href="#e7e9">skip it.</a>)</p><h4>Components:</h4><ol><li><a href="#8b72">What is Docker?</a></li><li><a href="#6031">Creating a NestJS application</a></li><li><a href="#e7e9">Containerizing the application using Docker</a></li></ol><p>How about we do away with the big words I threw around in the title first?</p><h3>What is Docker?</h3><blockquote>“Docker is a set of platform as a service products that use OS-level virtualization to deliver software in packages called containers”</blockquote><p>In simple-r english, Docker is a platform for creating, deploying and running applications using something fancy, called <strong>Containers</strong>. These containers are lightweight, independent, and executable software packages that collect all the components needed to run an application, such as dependencies, libraries, and code. These are portable and simple to move between various environments since they are isolated from one another and the host system. Along with managing containers, Docker also offers a variety of tools and services, including<strong> Docker Compose </strong>for multi-container applications, <strong>Docker Swarm f</strong>or container orchestration, and <strong>Docker Hub</strong> for sharing and distributing container images. We will be seeing docker compose in action further down this article.</p><p>Now that we’ve got that sorted out, let’s dive right in:</p><h3>Creating a NestJS application</h3><p>In case you haven’t already setup Node or a NestJS application, you can build one using the following command:</p><pre>sudo apt-get update                      // Update package list<br><br>sudo apt-get install nodejs npm          // Install node and npm <br><br>node -v                                  // Verify installation</pre><pre>npm i -g @nestjs/cli        // Install nestjs cli tool<br><br>nest new test-app           // Replace &#39;test-app&#39; with your own name</pre><p>The app-name directory will be created, node modules and a few other boilerplate files will be installed, and a src/ directory will be created and populated with several core files. By default, the app runs on port 3000.</p><p>Next, let’s create a .env file in the root directory to setup our environment variables:</p><pre>SERVER_HOST=&quot;127.0.0.1&quot;<br>SERVER_PORT=3000<br><br>MONGO_URI=&quot;mongodb://127.0.0.1:27017&quot;<br>DB_NAME=&quot;test-app_db&quot;</pre><blockquote>You might wonder what 127.0.0.1 is and how is 0.0.0.0 different (or was I the only idiot?).</blockquote><blockquote><em>127.0.0.1</em> is the loopback address of the local computer, also known as the &quot;localhost&quot;. This IP address is used to refer to the computer itself, and any application running on it can be accessed using this address.</blockquote><blockquote><em>0.0.0.0</em> is a special IP address that means &quot;any IP address&quot; or &quot;all available network interfaces&quot;. When an application binds to <em>0.0.0.0</em>, it will be available on all network interfaces of the computer. This can be useful for making an application accessible from any IP address or for testing on multiple interfaces.</blockquote><p>These variables (<em>may vary according to your own usecase</em>) will be used to specify the host and port our server listens on and the connection string for our database, by referencing them in main.ts and app.module.ts respectively as shown:</p><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br>const dotenv = require(&quot;dotenv&quot;)<br><br>dotenv.config();<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule,{ cors: true });<br>  app.enableCors();<br>  await app.listen(process.env.SERVER_PORT, process.env.SERVER_HOST)<br>      .then(() =&gt; {<br>        console.log(`Server running on http://${process.env.SERVER_HOST}:${process.env.SERVER_PORT}`);<br>      })<br>      .catch((error) =&gt; {<br>        console.error(`Failed to start server: ${error}`);<br>      });<br>}<br>bootstrap();</pre><p>Line 5 is used to tell our app to use the environment variables set in our .env file. These variables can now be used anywhere in our application as process.env.&lt;var&gt;</p><pre>import { Module} from &#39;@nestjs/common&#39;;<br>import { MongooseModule } from &#39;@nestjs/mongoose&#39;;<br>import { AppController } from &#39;./app.controller&#39;;<br>import { AppService } from &#39;./app.service&#39;;<br><br>@Module({<br>  imports: [<br>    MongooseModule.forRootAsync({<br>      useFactory: () =&gt; ({<br>        uri: process.env.MONGO_URI,<br>        dbName: process.env.DB_NAME,<br>      }),<br>    }),<br>  ],<br>  controllers: [AppController],<br>  providers: [AppService],<br>})<br>export class AppModule {}</pre><p>Before we jump into the next section, make sure you have <strong>Docker</strong> and <strong>Docker Compose</strong> installed in your system. You can follow the mentioned guide for installation:</p><p><a href="https://www.howtogeek.com/devops/how-to-install-docker-and-docker-compose-on-linux/">https://www.howtogeek.com/devops/how-to-install-docker-and-docker-compose-on-linux/</a></p><h3>Containerizing the application using Docker</h3><p>Now if you look back at it, all this was quite a bit of a task, all for setting up our application. What if all we needed was just one magic command to have someone do this for us? That’s where Docker steps in. It “containerizes” this application, incapsulating all the code, libraries and settings into it, and builds this app using a sequential set of instructions mentioned in something called a Dockerfile</p><pre># Use the official Node.js image as the base image<br># You can use any version that fits your usecase<br>FROM node:18<br><br># Set the working directory inside the container<br>WORKDIR /app<br><br># Copy the package.json and package-lock.json files into the container<br>COPY package*.json ./app/<br><br># Install the dependencies for the application<br>RUN npm install<br><br># Copy the rest of the application code into the container<br>COPY . /app<br><br># Expose the port that the application listens on<br>EXPOSE 3000<br><br># Start the application<br>CMD [ &quot;npm&quot;, &quot;run&quot;, &quot;start&quot; ]</pre><p>Once we have created this file in our root directory, we can build what is called a Docker image using the following command:</p><pre>docker build -t test-app .</pre><ul><li>‘ -t ‘ tag is used to specify the name of our docker image/=.</li><li>‘ . ‘ at the end specifies the build context, which is the current directory.</li></ul><p>This will create a new Docker image with the tag test-app. You can then run your application inside a Docker container using the following command:</p><pre>docker run -p 3005:3000 test-app</pre><p>Another thing I had to google here was, what’s the colon about? So, in case you’re wondering the same, the colon maps the port on its left to local machine and the one on its right to the container. Therefore, any requests made to port 3005 on the host machine will be forwarded to port 3000 in the container, where we have set our NestJS application to listen.</p><blockquote>The container port must match with the port we have set our app to listen over, and the port we have exposed in our dockerfile, unless you have configured it otherwise.</blockquote><p>This means that our app will be listening on port 3000 inside the container, but to us, it will be accessible by visiting port 3005 on localhost.</p><p>— — — — — — — -</p><h4>Using Docker Compose to setup the applications</h4><p>Actually, you know what? This is still too much work for me. Who’s going to run all these commands every time I want to build and run my app (which will be every time I make changes to the code in my local machine, since we’ll have to build a fresh image of it inside the container.) So let’s define a docker-compose.yml file (in the root directory) using the <strong>Compose</strong> tool, used for defining and running multi-container Docker applications.</p><pre>version: &#39;3&#39;<br>services:<br>  db:<br>    container_name: db_1<br>    image: mongo:4.4<br>    ports:<br>      - &quot;27017:27017&quot;<br>    volumes:<br>      - mongo-data:/data/db<br>  app:<br>    image: server_app<br>    container_name: app<br>    build: .<br>    ports:<br>      - &quot;3001:3000&quot;<br>    environment:<br>      - DB_INIT=false<br>      - SERVER_PORT=3000<br>      - MONGO_URI=mongodb://db:27017<br>    depends_on:<br>      - db<br>volumes:<br>  mongo-data:</pre><p>This docker-compose.yml file defines two services: app and db. The app service builds the Docker image for your NestJS application using the Dockerfile in the current directory, exposes port 3000, sets the MONGO_URI environment variable to the URL of the MongoDB instance, and depends on the db service. The db service uses the official MongoDB Docker image, exposes port 27017, and mounts a Docker volume to persist the data.</p><p>&gt; Volumes help persist data even if the container goes down or is removed.</p><blockquote>In case you get an error regarding the port 27017 already being in use (like I did), change the host port to something like 27015 or 27016. This is because you probably have a mongoDB server running on your localhost that you used to test your app locally.</blockquote><p>Now all you need to do in order to build and run your docker container is use the following command:</p><pre>docker-compose up --build -d</pre><ul><li>‘ — build ‘ tag is used to build a fresh image, and is to be added only during initial setup or when there are local changes that need to be reflected inside the container.</li><li>‘ -d ‘ tag tells the terminal to run the process in the background, avoiding all the visual cluster.</li></ul><p>You might also face an issue where the app doesn’t connect to the mongo server running inside the container even when your project is set up perfectly fine, because at times, the system firewall prevents this connection. If that’s the case, disable the firewall using the following command (in linux), and try running the containers:</p><pre>sudo ufw disable</pre><p>This concludes ‘Part 1’ of the post, having built and containerized a NestJS application using Docker. To learn about load balancing and implementing the functionality in the same application using NGINX, follow up with the second part of the post:</p><p><a href="https://medium.com/@goenkayathartha2002/containerizing-and-load-balancing-a-nestjs-application-with-docker-and-nginx-984aa5563caa">https://medium.com/@goenkayathartha2002/containerizing-and-load-balancing-a-nestjs-application-with-docker-and-nginx-984aa5563caa</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b14217262aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>