<?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 Prakhar Agarwal on Medium]]></title>
        <description><![CDATA[Stories by Prakhar Agarwal on Medium]]></description>
        <link>https://medium.com/@prakharagarwal234?source=rss-1714b56fe866------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LykO71W0OhDFl-pUiyTWgQ@2x.jpeg</url>
            <title>Stories by Prakhar Agarwal on Medium</title>
            <link>https://medium.com/@prakharagarwal234?source=rss-1714b56fe866------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 12:13:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prakharagarwal234/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[First telegram bot in python.]]></title>
            <link>https://prakharagarwal234.medium.com/first-telegram-bot-in-python-458b143f1f6c?source=rss-1714b56fe866------2</link>
            <guid isPermaLink="false">https://medium.com/p/458b143f1f6c</guid>
            <category><![CDATA[telegram-bot]]></category>
            <category><![CDATA[python-bot]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[vaccine-alert]]></category>
            <category><![CDATA[python-telegram-bot]]></category>
            <dc:creator><![CDATA[Prakhar Agarwal]]></dc:creator>
            <pubDate>Fri, 21 May 2021 21:27:54 GMT</pubDate>
            <atom:updated>2021-05-22T14:37:48.636Z</atom:updated>
            <content:encoded><![CDATA[<p>Hola Amigos !</p><p>In this short blog , I will walk you guys through the steps for creating your own Telegram bot in python. I would like to show you how you can create a simple telegram bot.</p><p><strong>Let me give a background on how i landed up on this thought.</strong></p><p>In this pandemic when we all are locked out and fighting with this vicious virus. I thought of creating a bot that will give the nearest vaccination centers as per the pincode and district name provided by the user.</p><p><strong>So what my bot does ?</strong> It throws 5 questions and based on the answers it will respond back with the nearest available vaccination centers along with available capacity. These answers will act as filters to take off unnecessary and not required data. I am using <a href="https://apisetu.gov.in/public/api/cowin"><strong>Co-WIN Public APIs</strong></a> provided by Indian Government to get all these data.</p><p>It also has <strong>subscribing feature</strong> where on subscribing user gets automatic notification if there is any update. I am hitting the API on every 2 mins and comparing the current response with the previous one. If the current and previous responses are same there will be no message.</p><p>Check it out on Telegram . Bot name : <a href="https://t.me/vaccine_ki_khoj_bot"><strong>Vaccine_ki_Khoj</strong></a><strong> <br>Note : Useful for Indian Users only.</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F8TA6HPlfTiBhsJB7v4%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F8TA6HPlfTiBhsJB7v4%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F8TA6HPlfTiBhsJB7v4%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="940" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef2199a112082de8c5748292fc978e94/href">https://medium.com/media/ef2199a112082de8c5748292fc978e94/href</a></iframe><p>I never worked with python before and being a complete novice it took 4 days to complete this bot.</p><p>This was my use case of creating one such bot. Similarly there could be many use cases like you can use it to send automatic notifications on cryptocurrency price , stock values , send daily quotes to user , create surveys or quizzes and many more. Think about your objective and let me know in comment section if you need any help.</p><p>In this blog i am not covering my use case. We will be creating a simple echo bot where our bot echoes the messages that we send to it. Trust me it would take hardly 15 mins to create and run this bot.</p><p>As a prerequisite make sure you have python installed in your system. So lets get started with this fun activity.</p><h4>1. Register a new bot in BotFather</h4><p>In order to create a bot in Telegram, first you have to “register” it with telegram. To achieve this you need to contact the <a href="https://telegram.me/BotFather">BotFather</a>, which is essentially a bot used to create other bots. When we “register” our bot, we will get the token to access the Telegram API.</p><ul><li>Search for @botfather in Telegram. You can use telegram app on phone/desktop or web app as well.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*7hv2953Wepog6_UoA7GrgQ.png" /></figure><ul><li>Press Start button to start the conversation.</li><li>Create the bot by running <strong>/newbot </strong>command</li><li>Enter the Display Name and User Name for the bot.</li><li>BotFather will send you a message with the token.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*i8oRSKBDW9Zpe6VMMBZgmg.jpeg" /></figure><p>NOTE— Keep it secure. Anyone with its access can manipulate your bot.</p><p>By the way, BotFather is also able to perform following actions for you:</p><ul><li>Put description to your bot</li><li>Upload avatar</li><li>Change access token</li><li>Delete your bot etc.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fdesertedoffbeatbluewhale&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fdesertedoffbeatbluewhale&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FDesertedOffbeatBluewhale-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="720" height="1280" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c3e3e124c7fec26104792f48f3d345a/href">https://medium.com/media/0c3e3e124c7fec26104792f48f3d345a/href</a></iframe><h4>2. Lets Code</h4><p>We will be using <a href="https://python-telegram-bot.readthedocs.io/en/stable/">python-telegram-bot</a> package for interacting with Telegram API. Install the package using the following command.</p><p>pip install<strong> </strong>python-telegram-bot</p><p>Lets start coding our bot.</p><p>Create a file bot.py . First lets have our imports in place.</p><pre><strong>from</strong> telegram.ext <strong>import</strong> Updater, CommandHandler, MessageHandler, Filters</pre><p>Now lets define our functions . These functions are basically command/message handlers. They usually take the two arguments update of type Update and context of type CallbackContext . Error handlers also receive the raised TelegramError object in error.</p><p>In our bot we will define three function , one to handle our <strong>/start</strong> command</p><pre><strong>def start_bot</strong>(update,context):<br>    # Your bot will send this message when users first talk to bot <br>    #using /start command</pre><pre>    update.message.reply_text(&#39;Hi! Welcome. Please give me any text <br>    and i will echo it for you&#39;)</pre><p>this handler will take of care of <strong>/help</strong> command.</p><pre><strong>def need_help</strong>(update, context):     <br>   # on /help command<br>   update.message.reply_text(&#39;Help!&#39;)</pre><p>and this messagehandler function will be called for remaining text other than /start and /help.</p><pre><strong>def</strong> <strong>echo</strong>(update, context):     <br>   update.message.reply_text(update.message.text)</pre><p>Lastly, lets have our main to run our program. Change YOUR_TOKEN with the token that we generated earlier in this tutorial.</p><pre>def main():<br>    updater = Updater(&#39;YOUR_TOKEN&#39;)<br>    <br>    #get dispatcher from updater to register handlers<br>    dp = updater.dispatcher<br>    <br>    # adding start command handler to dispatcher.<br>    #handles /start command      <br>    dp.add_handler(CommandHandler(&#39;start&#39;,start_bot))</pre><pre>    # calls help method on /help command<br>    dp.add_handler(CommandHandler(&#39;help&#39;,need_help))</pre><pre>    #<em>on noncommand i.e for text other than start and help , echo    <br>    #the message on Telegram</em>        <br>    dp.add_handler(MessageHandler(Filters.text, echo))<br>    <br>    #<em> Start the Bot<br> </em>   updater.start_polling()</pre><pre><em>    # Run the bot until you press Ctrl-C or the process receives     <br>    #SIGINT, SIGTERM or SIGABRT. This should be used most of the      </em><br>    <em># time, since,start_polling() is non-blocking and will stop <br>    # the bot<br>    </em>updater.idle()<em> <br></em>  <br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>This code uses polling approach to check for messages and will reply to every message it receives with the same message. Here our server is checking hitting our bot continuously and checking for any message. Another way is webhook.</p><p><a href="https://www.wikiwand.com/en/Webhook">Webhook</a> provides us a way of letting the bot call our server whenever a message is called, so that we don’t need to make our server suffer in a while loop waiting for a message to come.</p><p>Run the script</p><pre>python bot.py</pre><p>Goto your telegram , search for bot with the name give during registering with BotFather . Type /start to start the conversion and enjoy.</p><p><strong>Voilà ! We’re done with our first bot.</strong></p><h3>Lets check our Echo 🤖 in action</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F7FvK253Gbo5k03NCB5%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F7FvK253Gbo5k03NCB5%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F7FvK253Gbo5k03NCB5%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="940" frameborder="0" scrolling="no"><a href="https://medium.com/media/5847ca310b7ae5e6123568beefc5ed80/href">https://medium.com/media/5847ca310b7ae5e6123568beefc5ed80/href</a></iframe><p><strong>TIP :</strong></p><p>In order to make you bot active 24*7 , you need to have the script up and running all the time. You can have it deployed on any of the cloud service. For my use case i used AWS EC2 instance. I chose Ubuntu 18.04 , installed python on it and run below</p><pre>nohop python3 bot.py &amp;</pre><p>this will run the script in background.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=458b143f1f6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive API vs Traditional API]]></title>
            <link>https://prakharagarwal234.medium.com/reactive-api-vs-traditional-api-907ca3808c2f?source=rss-1714b56fe866------2</link>
            <guid isPermaLink="false">https://medium.com/p/907ca3808c2f</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[spring-webflux]]></category>
            <category><![CDATA[webflux]]></category>
            <category><![CDATA[thread-pool]]></category>
            <dc:creator><![CDATA[Prakhar Agarwal]]></dc:creator>
            <pubDate>Tue, 04 May 2021 10:25:24 GMT</pubDate>
            <atom:updated>2021-05-21T20:47:20.169Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog we will try to understand the basic difference between traditional REST API and Reactive Programming. We will understand Traditional REST API Design and its drawbacks. We will also get into Reactive Programming and see the advantages it gives us over traditional REST API.</p><p>Lets first have a look at how the things works with traditional REST API design. At the end I’ll show you the real difference through the same through the code .</p><h3>Traditional REST API Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*0MPV9eJsrExGbHoRZjIU9w.png" /></figure><p>Above code is a simple get mapping by item id and in response we are sending ResponseEntity of item. To achieve this we are first making a DB call to get the price of item then second rest call to get the location of the item. After that responses from both calls are combined to build the item object.</p><p>This design</p><ul><li>follows top to bottom approach.</li><li>it is <strong>Blocking and Synchronous</strong>.</li></ul><p>Imperative style of coding leads to inefficient use of resources . This means that the thread will remain in the blocking state until it gets a response back from the data source ( it can be DB or other microservice or anything ). In the above code once we get the response from DB then only the next rest call can be made to get the location. This is <strong>blocking and Synchronous.</strong></p><h4>Handle concurrent requests</h4><p>How traditional restful APIs handle concurrent requests ?</p><p><strong>Thread Per Request Model</strong></p><p>For each http request , tomcat is going to take a thread from the thread pool and assign it to that request. Each allocated thread is responsible to handle the life cycle of that http request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IEGVk_xlpK2uLW0PvTL2Vg.png" /></figure><p>With this model, number of concurrent request depends on the number of threads and number of threads directly depends on the size of the thread pool.</p><ul><li>By default pool size is 200.</li><li>Can be overridden in application.properties or application.yml using server.tomcat.max-threads property.</li></ul><p>But that doesn&#39;t mean you can set a large number of pool size as each thread will consume some memory. Large pool size means less memory for application processing and eventually the application will perform poorly.</p><p>Then How you can handle this situation ?</p><p>You can handle this by horizontal scaling i.e. spinning up or increase application instances. If you are using any orchestration ( like kubernetes ) then you can have a load balancer in front of your application and it will balance the load and distribute requests accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*xeUVVvlEKKcoXvJrtddpZg.png" /></figure><p>We can sum up to following disadvantages of traditional API:</p><ul><li>Limit on the number of concurrent users</li><li>Synchronous and blocking</li><li>Imperative style APIs</li><li>No back pressure support ( We will discuss this in later part )</li></ul><p>But it doesn&#39;t mean that traditional api is obsolete. Its still supported and gets fit in various use cases.</p><p>To overcome all the drawbacks of traditional API , we got reactive programming.</p><h3>What is Reactive Programming ?</h3><ul><li>Asynchronous and Non Blocking</li><li>Data flow as an Event/Message driven stream.</li><li>Back Pressure on Data Streams.</li></ul><p>Lets explain the difference with an example.</p><p>In Imperative design(see below image) , a thread will be in blocked state until it gets all the items requested by the application in the response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*gIzHE9gW2KALvJwRfWytOg.png" /></figure><p>Whereas in reactive programming world , data flows as an event/message driven stream.</p><ul><li>One event/message for each result item from Data Source.</li><li>One event/message on completion or error.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*d3m8N-UroPivpZUjI0NvOA.png" /></figure><ul><li>First step is to invoke the database to get the items , here call returns immediately as it is asynchronous .</li><li>Data will be pushed to application as a stream and as it is available one by one i.e. one event event for every single item in the result set. As you can see here we receive onNext call from DB to application layer for every single item. This will be continued until all items are pushed .</li><li>One all the data is pushed we received an event called onComplete() in case of success or onError() in case of any error.<br><strong>NOTE : </strong>onError() can be triggered on any of onNext() call in case of any error/ecveption. So lets say first item got pushed but while pushing second there is any exception then onError() event will be received.</li><li>In case of no data , we will just receive onComplete().</li></ul><p><strong>Reactive Programming supports Back Pressure.</strong></p><p>Lets have a look at the below simple get request to pull all the items in the inventory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*JLK0_JDy6fRgMja6tAcl7w.png" /></figure><p>This endpoint returns a list of items . Consider the items are too many in numbers then think about the response size and if endpoint is bombarded with many requests then as a result of this two things can happen either this might blow up the heap and application might crash with out of memory error or client will be provided with such a huge data in response which the client might not able to handle. <br>To avoid this we have a concept of back pressure where if the data source/publisher is producing more data than we expected ,there is a way for the application to provide a feedback to the data source stating to slow down or stop.<br>Traditional Rest api doesn&#39;t have such feature.</p><h3>Reactive Stream specification</h3><p>They are nothing but rules or specification for reactive stream. They are :</p><ul><li>Publisher</li><li>Subscriber</li><li>Subscription</li><li>Processor</li></ul><p><strong>Publisher </strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*UCQerZ_S8xop5gcoaJcp_Q.png" /></figure><p>Publisher is the data producer or the data emitter.</p><p><strong>Subscriber </strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*9JXrUhn-7Bk1JZ3gXAk-LQ.png" /></figure><p>Subscriber is the one that reads the data from the publisher. Anonymously consumer.</p><p><strong>Subscription </strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*hkEA4JXLSZPD2OFxjRFrqg.png" /></figure><p><strong>Processor</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*0Q-s4WmsD4D-nPCbM_Sfgg.png" /></figure><p>Combination of both Subscriber and Publisher interface and that why you wont see any specific methods for this interface.</p><h3>Publisher/Subscriber Event Flow</h3><p><strong>For request subscription</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*FPJq2mrBMheL06TbWNcl4A.png" /></figure><ul><li>Subscriber invokes subscribe() of the publisher and passes the subscriber instance as an input.</li><li>Publisher sends the subscription object to subscriber confirming the subscription.</li><li>By default request() is going to ask for all the data from the publisher.</li><li>Lets say the publisher is a database and is going to return 100 items in that case there will be hundred onNext() event with each event representing the row wil be sent to the subscriber.</li><li>Once all the data is send then we will be receiving a onComplete() event.<br>If there is any error in this workflow we will get onError() event.</li></ul><p><strong>NOTE</strong>: there is an option for the subscriber to provide a number to the publisher asking for a specific number of data. If you take a look at request method it takes a parameter n. For example , lets say out of 100 matching records you want only 2 items . In that case you send 2 in the request call and you will get two only onNext() event and followed by that you get onComplete(). Basically this concept is called as <strong>Back Pressure </strong>where Subscriber has the control on how much data it needs from the publisher.</p><p><strong>For cancel subscription</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*luXlcXCXiksNWUHNTY1sGQ.png" /></figure><p>Subscriber has the option to cancel the subscription that is received from the publisher. Basically this means we are cancelling the subscription and the publisher is not going to publish any event to the subscriber.</p><h3>Reactive Libraries</h3><p>Implementation of Reactive Stream Specifications. There are below three implementations:</p><ul><li>RxJava</li><li>Reactor</li><li>Flow class — JDK 9</li><li><a href="https://kotlinlang.org/docs/reference/coroutines/flow.html">Kotlin Flow</a></li></ul><h3><strong>Spring WebFlux</strong></h3><p>Spring WebFlux uses this Project Reactor library and is parallel version of Spring MVC that supports fully non-blocking reactive streams. It also supports the back pressure concept and uses Netty as inbuilt server to run reactive applications.</p><pre>&lt;dependency&gt;     <br>&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;     <br>&lt;artifactId&gt;spring-boot-starter-webflux&lt;/artifactId&gt;     <br>&lt;version&gt;{version}&lt;/version&gt; <br>&lt;/dependency&gt;</pre><p>The spring-boot-starter-webflux includes spring-web, spring-webflux, spring-boot-starter, spring-boot-starter-reactor-netty, etc., so there&#39;s no need for any other dependency to be present.</p><h3>Mono and Flux</h3><p>In Spring WebFlux, the data returned from any operation is packed into a reactive stream. There are two types such streams and are the building blocks in WebFlux applications — Mono and Flux.</p><p>Mono is a stream which returns zero items or a single item (0..1), whereas Flux is a stream which returns zero or more items (0..N).</p><p>Mono is therefore used when you&#39;re expecting a single (or none) result, such as retrieving a unique user from the database, whereas Flux is used when you&#39;re expecting multiple results or a collection of some sort.</p><h3>Coding</h3><p>Its time to get our hands dirty. After going through all the theory parts lets try to understand the same through coding.</p><p>To make you grasp the basic difference i have created a spring boot webflux project that showcase the difference between blocking and non-blocking way of programming i.e. traditional and reactive. The project has nothing fancy its a normal spring application with just webflux dependency and a get request mapping to show mono/flux type.</p><p>This is the controller class. I created a get request mapping for both ways and both these methods are pulling customer object data from the repository class using there respective method. getAllProdcuts()is tradtional way and getAllProductsStream() reactive way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*7dv2opz5UAXRIT4jFCbUCA.png" /></figure><p>In repository class, i am creating 5 customer objects. In getAllProducts() , i am doing in our normal stream way whereas in getAllProductsStream() i am doing it in reactive way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wrEajDpAnH5DJbELIl_yug.png" /></figure><p>To see this difference, go to the browser and hit <a href="http://localhost:8088/product">http://localhost:8088/product</a> , you will see the page remains in loading state until all data gets pulled i.e. thread is blocked and is waiting for the response to be completed. Once all data is pulled then only browser will show you the response. <br>Whereas on hitting <a href="http://localhost:8088/product">http://localhost:8088/product</a>/stream , the thread will not be blocked. Publisher will keep on emitting the data and as a result you will see see data one by one appearing on the screen.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fbeneficialfragrantindianglassfish&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fbeneficialfragrantindianglassfish&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FBeneficialFragrantIndianglassfish-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="1920" height="1032" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab8068e338aa12ce56452f72415b18f0/href">https://medium.com/media/ab8068e338aa12ce56452f72415b18f0/href</a></iframe><p>Please find the code at <a href="https://github.com/PrakharAgarwalSavvy/webflux-poc/">https://github.com/PrakharAgarwalSavvy/webflux-poc/</a></p><p>Thanks for the time. Keep learning , keep growing .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=907ca3808c2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Drool with Spring Boot]]></title>
            <link>https://prakharagarwal234.medium.com/drool-with-spring-boot-14aa3e3259c6?source=rss-1714b56fe866------2</link>
            <guid isPermaLink="false">https://medium.com/p/14aa3e3259c6</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[rules-engine]]></category>
            <category><![CDATA[drools]]></category>
            <category><![CDATA[business-rule-engine]]></category>
            <dc:creator><![CDATA[Prakhar Agarwal]]></dc:creator>
            <pubDate>Fri, 30 Apr 2021 18:31:27 GMT</pubDate>
            <atom:updated>2021-05-06T10:07:49.475Z</atom:updated>
            <content:encoded><![CDATA[<p>Before starting lets understand what’s exactly Drool is. Lets take a scenario of any Ecommerce site. Consider Amazon is having a mega sale going on. In this sale they are offering different discounts on different Bank Cards. Like for a purchase of more than 5000 Rupees on HDFC Bank customers are getting 15% discount . Similarly discount on ICICI is 12% and likewise some other discount on any other card. So for such use case you would have code using if else condition in the service layer something like this</p><pre>@PostMapping(&quot;/order&quot;)<br>public Order orderNow(@RequestBody Order order) {</pre><pre>   if(order.getCardType().equalsIgnoreCase(&quot;HDFC&quot;) <br>       &amp;&amp; order.getPrice() &gt; 5000) {<br>     order.setDiscount(15);<br>   }</pre><pre>   if(order.getCardType().equalsIgnoreCase(&quot;ICICI&quot;) <br>       &amp;&amp; order.getPrice() &gt; 8000) {<br>    order.setDiscount(12);<br>   }</pre><pre>return order;<br>}</pre><p>There is nothing wrong with it but lets assume in the next sale if Amazon wants to add new Banks or want to change discount offer on any existing card then this code needs to be change every time.</p><p>Drools comes to our rescue here. With drools we can create a separate file with all the rules and allow drool engine to take care of it. Drools is a rule engine , through which we can set rules for our business logic and we can separate our hard core conditions from business logic.</p><h4>What is Drool ?</h4><p>Drools is a Business Rules Management System (BRMS) solution. Using this framework users define rules that specify what action needs to be done when a particular condition is met. The algorithm mostly used by Drools is the <strong>Rete Algorithm</strong>.</p><h4>What is a Rule Engine ?</h4><p><strong>Drools Rule Engine</strong> is a rule-based approach to implement an Expert system in the Drools software. The Rule engine provides Expert systems which are knowledge-based systems that help you to make decisions like what to do and how to do it. It gathers knowledge into a knowledge base that can be used for reasoning.</p><h4>Spring boot dependency for Drool</h4><pre>&lt;dependency&gt;     <br>  &lt;groupId&gt;org.drools&lt;/groupId&gt;     <br>  &lt;artifactId&gt;drools-core&lt;/artifactId&gt; <br>  &lt;version&gt;7.49.0.Final&lt;/version&gt; <br>&lt;/dependency&gt; <br>&lt;dependency&gt;     <br>  &lt;groupId&gt;org.drools&lt;/groupId&gt;     <br>  &lt;artifactId&gt;drools-compiler&lt;/artifactId&gt;              <br>  &lt;version&gt;7.49.0.Final&lt;/version&gt; <br>&lt;/dependency&gt;</pre><h4>Create rule with drool file (.drl )</h4><pre>package KieRule; <br>import com.learning.model.Order;<br>  <br>rule &quot;HDFC&quot;  <br>when orderObject : Order(cardType==&quot;HDFC&quot; &amp;&amp; price&gt;10000); <br>then <br>orderObject.setDiscount(10); <br>end;  </pre><pre>rule &quot;ICICI&quot;  <br>when orderObject : Order(cardType==&quot;ICICI&quot; &amp;&amp; price&gt;15000); <br>then orderObject.setDiscount(8); <br>end;</pre><p><em>Package</em> − Every Rule starts with a package name. The package acts as a namespace for Rules. Rule names within a package must be unique. Packages in Rules are similar to packages in Java.</p><p><em>Import statement</em> − Whatever facts you want to apply the rule on, those facts needs to be imported. For example, com.learning.model.Order; in the above example.</p><p>Lets understand one of the rule:</p><pre>rule &quot;ICICI&quot;  <br>when orderObject : Order(cardType==&quot;ICICI&quot; &amp;&amp; price&gt;15000); <br>then orderObject.setDiscount(8); <br>end;</pre><p>Here , rule name is ICICI .<br>when &lt;objectName&gt; :&lt;ObjectType&gt;(condition)<br>then &lt;outcome&gt;<br>end of rule.</p><h4>Drools Config Class</h4><pre>import java.io.IOException;<br>import org.kie.api.KieServices;<br>import org.kie.api.builder.KieBuilder;<br>import org.kie.api.builder.KieFileSystem;<br>import org.kie.api.builder.KieModule;<br>import org.kie.api.builder.KieRepository;<br>import org.kie.api.builder.ReleaseId;<br>import org.kie.api.runtime.KieContainer;<br>import org.kie.api.runtime.KieSession;<br>import org.kie.internal.io.ResourceFactory;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;</pre><pre>@Configuration<br>public class DroolConfig {</pre><pre>private KieServices kieServices = KieServices.Factory.get();</pre><pre>private KieFileSystem getKieFileSystem() throws IOException {       <br>  KieFileSystem kieFileSystem = kieServices.newKieFileSystem();                                                              <br>  kieFileSystem.write(<br>    ResourceFactory.newClassPathResource(&quot;offer.drl&quot;));<br>  return kieFileSystem;<br>}</pre><pre>@Bean<br>public KieContainer getKieContainer() throws IOException {<br>  System.out.println(&quot;Container created...&quot;);<br>  getKieRepository();<br>  KieBuilder kb = kieServices.newKieBuilder(getKieFileSystem());<br>  kb.buildAll();<br>  KieModule kieModule = kb.getKieModule();<br>  KieContainer kContainer =        <br>  kieServices.newKieContainer(kieModule.getReleaseId());<br>  return kContainer;<br>}</pre><pre>private void getKieRepository() {<br>  final KieRepository kieRepository = kieServices.getRepository();<br>  kieRepository.addKieModule(new KieModule() {      <br>      public ReleaseId getReleaseId() {<br>      return kieRepository.getDefaultReleaseId();<br>    }<br>  });<br>}</pre><pre>@Bean<br>public KieSession getKieSession() throws IOException {<br>  System.out.println(&quot;session created...&quot;);<br>  return getKieContainer().newKieSession();<br>}</pre><pre>}</pre><p>KieFileSystem bean that finds all the rule files put under the classpath file system. These rule files define the rules, which would be applied on the object fields for validation.</p><p>KieContainer bean which is used to create different components, such as, KieSession that is required to create before fire rules on the drools file.</p><h4>Model Class</h4><p>Let us assume that we hava a POJO — a order class</p><pre>public class Order {</pre><pre>private String name;<br>private String cardType;<br>private int discount;<br>private int price;</pre><pre>//all args constructor<br>//getters and setters</pre><pre>}</pre><h4>Controller</h4><p>Create a controller class to verify the rules.</p><pre>@RestController<br>public class OfferController {</pre><pre>@Autowired<br>private KieSession session;</pre><pre>@PostMapping(&quot;/order&quot;)<br>public Order orderNow(@RequestBody Order order) {    <br>  session.insert(order);  // which object to validate<br>  session.fireAllRules(); // fire all rules defined into drool file <br>  return order;<br>}<br>}</pre><h4>Verify the result</h4><p>We are using postman to validate our implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iqKgORWa3_WfR-4rz-AaHw.png" /></figure><p>As you can see from the response , we are getting discount of 10% on HDFC card of 20000 payment.</p><p>We are good till. But there a catch here as well. Lets say some non-technical guy wants to add/edit a rule. I think it would be tough to change in the existing drl file for someone not familiar with the coding. In that case , we can make use xls file instead of drl file.</p><h4>Drool Decision Table</h4><p>For that you need to add one more dependency</p><pre>&lt;dependency&gt;<br>      &lt;groupId&gt;org.drools&lt;/groupId&gt;<br>      &lt;artifactId&gt;drools-decisiontables&lt;/artifactId&gt;<br>      &lt;version&gt;7.49.0.Final&lt;/version&gt;<br>    &lt;/dependency&gt;</pre><p>xls file looks something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5IGdybxah9GEH-l9QJxVQ.png" /></figure><p>Here , $param is the dynamic value passed.</p><p>Also please make sure to change the name of file in DroolConfig.getKieFileSystem() from “order.drl” to “order.xls”.</p><h4>Drools attributes :</h4><p>Drool attributes are <strong>salience, update statement and no-loop.</strong></p><p><strong>Salience</strong>: This is used to prioritize the rule in case multiple rule passed the condition. So lets say we got another condition in our drl file where we are checking if the user is normal or prime user. In case the user is prime we want to give them 15% discount.</p><pre>package KieRule; <br>import com.learning.model.Order;<br>  <br>rule &quot;HDFC&quot;  <br>when orderObject : Order(cardType==&quot;HDFC&quot; &amp;&amp; price&gt;10000); <br>then <br>orderObject.setDiscount(10); <br>end;</pre><pre>rule &quot;ICICI&quot;  <br>when orderObject : Order(cardType==&quot;ICICI&quot; &amp;&amp; price&gt;15000); <br>then orderObject.setDiscount(8); <br>end;</pre><pre>rule &quot;Prime user check&quot;  <br>when orderObject : Order(customerType==&quot;Prime&quot;); <br>then orderObject.setDiscount(15); <br>end;</pre><p>for the below object</p><pre>{<br>&quot;name&quot;:&quot;test name&quot;,<br>&quot;cardType&quot;: &quot;ICICI&quot;,<br>&quot;price&quot;: 50000,<br>&quot;customerStatus&quot;: &quot;prime&quot;<br>}</pre><p>two rules are qualified ( ICICI and Prime user check). By default rules run in the mentioned order will run. So without salience also discount will 15 . But , if you move ‘Prime user check’ to the top then discount will be 8 as ICICI rule is later and it will override status check rule. In the case , we use salience to the rule engine the priority in which rule should be applied.</p><p>For the below drl file , first ICICI rule will be triggered then ‘Prime user check’<br>rule.</p><pre>package KieRule; <br>import com.learning.model.Order;</pre><pre>rule &quot;Prime user check&quot;<br>salience 1<br>when orderObject : Order(customerType==&quot;Prime&quot;); <br>then orderObject.setDiscount(15); <br>end;</pre><pre>rule &quot;HDFC&quot;  <br>when orderObject : Order(cardType==&quot;HDFC&quot; &amp;&amp; price&gt;10000); <br>then <br>orderObject.setDiscount(10); <br>end;</pre><pre>rule &quot;ICICI&quot;  <br>salience 2<br>when orderObject : Order(cardType==&quot;ICICI&quot; &amp;&amp; price&gt;15000); <br>then orderObject.setDiscount(8); <br>end;</pre><p><strong>salience with greater value will get priority/triggered first.</strong></p><p><strong>Update &amp; no-loop: </strong>This attributes makes the engine aware that a fact is updated. This may cause other rules engine to be fired again which sometime gets result into indefinite loop.</p><p>Lets understand this better . So suppose for our prime customer we want to double the discount what they are getting normally on the banks. For prime users using ICICI bank and spending more than 15000 we want to give them 16% discount. Instead instead of hardcoding 16 in “Prime user check” we can use update attribute. Something like this</p><pre>rule &quot;Prime user check&quot;  <br>salience 1<br>when orderObject : Order(customerType==&quot;Prime&quot;); <br>then update(orderObject);<br>end;</pre><pre>rule &quot;ICICI&quot;  <br>salience 2<br>when orderObject : Order(cardType==&quot;ICICI&quot; &amp;&amp; price&gt;15000); <br>then orderObject.setDiscount(orderObject.getDiscount()+8); <br>end;</pre><p>But we got a problem here . This will get into infinite loop. Lets see how.</p><p>First ‘ICICI’ rule will be triggered ( higher salience )<br>Then ‘Prime user check’. Here we are using update order object. As we are updating the fact , the rule associate with it will again get triggered.<br>As a result ICICI will be triggered again and then prime user. This get loops in causing indefinite loop.</p><p>To break this loop we use <strong>no-loop</strong> attribute.</p><pre>rule &quot;Prime user check&quot;  <br>salience 1<br>no-loop true<br>when orderObject : Order(customerType==&quot;Prime&quot;); <br>then update(orderObject);<br>end;</pre><p>Second time the loop will break in “Prime user check” rule.</p><p>Please find the code at <br><a href="https://github.com/PrakharAgarwalSavvy/Drool-SpringBoot">https://github.com/PrakharAgarwalSavvy/Drool-SpringBoot</a></p><p>Thanks for the time. Keep learning , keep Growing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14aa3e3259c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerize MEAN application]]></title>
            <link>https://prakharagarwal234.medium.com/dockerize-mean-application-a62aac0cf8f3?source=rss-1714b56fe866------2</link>
            <guid isPermaLink="false">https://medium.com/p/a62aac0cf8f3</guid>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-container]]></category>
            <dc:creator><![CDATA[Prakhar Agarwal]]></dc:creator>
            <pubDate>Mon, 22 Feb 2021 14:36:52 GMT</pubDate>
            <atom:updated>2021-03-01T17:31:16.551Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are new to docker then i would strongly recommend to check out my <a href="https://medium.com/@prakharagarwal234/understanding-docker-90c38aab91fa">this</a> story on understanding basics of docker . How it works , its architecture and also a hands on to spin nginx container.</p><p>In this article i will show how to dockerize a MEAN application. We will create three containers one each for Angular , Node and Mongo. After that we will connect all three of them and make our website up and running .</p><p>Let’s get started .</p><h3><strong>Step -1 : Have your code ready on github</strong></h3><p>Please make sure you have your code ready on github as it will be used in the later part of the setup.</p><p>For demonstration purpose , i have created a simple MEAN application available on below github link , you can clone/fork it onto your local machine/github.</p><p><a href="https://github.com/PrakharAg-Learner/Blogger">PrakharAg-Learner/Blogger</a></p><p>In this application i am just adding/edit/deleting blogs. Simple.</p><h3><strong>Step-2 : Create DockerFiles for node , mongo and Angular.</strong></h3><p>You can have these files anywhere in the project. In my project , i had nodedockerfile and mongodockerfile in the backend folder whereas angulardockerfile in root folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*MHJRKeYjhycmKumaKEyJ6A.png" /></figure><p><strong>DockerFile for node:</strong></p><pre>FROM alpine:latest</pre><pre>RUN apk add --no-cache nodejs npm</pre><pre>WORKDIR /app</pre><pre>COPY . /app</pre><pre>RUN npm install</pre><pre>EXPOSE 3000</pre><pre>CMD [&quot;node&quot;,&quot;server.js&quot;]</pre><p>Let’s go through the commands line by line :</p><ul><li>First , we are using alpine as our base image. Why Alpine ? Alpine describes itself as:</li></ul><blockquote><em>Small. Simple. Secure. Alpine Linux is a security-oriented, lightweight Linux distribution based on musl libc and busybox.</em></blockquote><ul><li>Then we are installing nodejs and npm on our alpine image without cache i.e. it won’t pick anything from cache and build the image as a new. Suppose , you had some code changes and ran the same docker file but without this flag then there are chances that your changes will not be visible as they are picked from previous run cache. So just to avoid this scenario we added no-cache flag.</li><li>Creating a working directory /app</li><li>Copying all files from current direct to our working directory ( /app ) which also include package.json<br>NOTE: whatever file you are trying to copy has to be on the path where dockerfile is. Suppose you got some file at user/test/abc.html and you provided command in dockerfile as <br>COPY user/test/abc.html /app<br>you will get an error.</li><li>Doing npm install to get all dependencies mentioned in package.json</li><li>Exposing our node port 3000</li><li>Once the container is up and running , we are giving node server.js as default command to execute and run node.</li></ul><p>Save file as NodeDockerFile.</p><p><strong>DockerFile for Mongo:</strong></p><pre>FROM mongo:latest</pre><pre>EXPOSE 27017</pre><p>Its pretty simple and straight forward. Getting mongo latest image and exposing 27017 port on the container.</p><p>Save file as MongoDockerFile.</p><p><strong>DockerFile for Angular:</strong></p><pre>#stage-1</pre><pre>FROM node:alpine as build</pre><pre>WORKDIR /app</pre><pre>COPY package.json package-lock.json ./</pre><pre>RUN npm install</pre><pre>COPY . .</pre><pre>RUN npm run build --prod</pre><pre>#stage-2</pre><pre>FROM nginx:alpine</pre><pre>COPY --from=build /app/dist/blogger /usr/share/nginx/html</pre><p>Here , we are using multistage image building, in stage-1 we are creating dist folder that will have all our deployable packages. Then in stage-2 we are serving the files through nginx proxy server.</p><p>Let’s discuss commands , Stage-1</p><ul><li>considering alpine distribution of node as base image and naming this as <strong>build</strong>.</li><li>creating a working directory /app in the image</li><li>copying package.json package-lock.json to the root of this working directory in image.</li><li>doing npm install to get all dependencies in the node_modules folder.</li><li>copying all file from current direct to the image working directory.</li><li>runs the build field from the package.json scripts field. After this a dist folder will created in /app and it will have all our deployable files.</li></ul><p>Stage-2</p><ul><li>taking alpine distribution of nginx image.</li><li>copying file from dist folder that got created in stage-1 to nginx’s /usr/share/nginx/html . If noticed we used --from=build this tell to get files from stage-1 .</li></ul><p>Save file as AngularDockerFile.</p><p><strong>NOTE</strong> : We can also use ADD instead of COPY . Difference between ADD and COPY. <br>COPY takes in a <em>src</em> and <em>destination</em>. It only lets you copy in a local file or directory from your host (the machine building the Docker image) into the Docker image itself.</p><p>ADD lets you do that too, but it also supports 2 other sources. First, you can use a URL instead of a local file / directory. Secondly, you can extract a tar file from the source directly into the destination.</p><h3>Step -3 Create docker image from the docker file</h3><p>Lets create 3 separate docker image from each of respective docker file.</p><p>Move to the respective location and run the build commands provided below.</p><p>Command syntax</p><p>docker build -f &lt;filename&gt; -t &lt;imagename&gt;:&lt;tag&gt; &lt;directory&gt;</p><p>For angular,</p><p>docker build -f AngularDockerFile -t angular-docker-image:latest .</p><p>For Mongo,</p><p>docker build -f MongoDockerFile -t mongo-docker-image:latest .</p><p>For Node,</p><p>docker build -f NodeDockerFile -t node-docker-image:latest .</p><p>Note: dot at the end means current working directory</p><h3>Step -4 Spin containers from these docker images</h3><p>Now we will build containers from above created images.</p><p>Command syntax</p><p>docker run -d -p &lt;host-port&gt;:&lt;container-port&gt; --name &lt;container-name&gt; &lt;image-name&gt;:&lt;tag&gt;</p><ul><li>-d : This option is used to run the container in detached mode. This is so that the container can run in the background.</li><li>-p : it is used for port mapping i.e. host machine port with the container port.</li></ul><p>For angular,</p><p>docker run -d -p 8888:80 --name angular-docker angular-docker-image:latest</p><p>For mongo,</p><p>docker run -d -p 27017:27017 --name mongo-docker mongo-docker-image:latest</p><p>For node,</p><p>docker run -d -p 3000:3000 --name node-docker node-docker-image:latest</p><p>Test the results. Go to <a href="http://localhost:8888/">http://localhost:8888</a> . Here , you will be able to see the front page but you won&#39;t be able to add blogs.</p><h3>Step -5 Analyse the issue and Fix the error</h3><p>Let’s check what is the exact error. Syntax of the command to check the logs of a container is</p><p>docker logs &lt;container_name or id&gt;</p><p>and command is</p><p>docker logs node-docker</p><p>You should see this below error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDyDW7ES6Jlm-1HbzaOr2A.png" /></figure><p>where it clearly mention</p><p>connectedMongoNetworkError: failed to connect to server [localhost:27017] on first connect</p><p>Thing to understand here is we are trying to connect mongo on localhost whereas it is running in one of the container.</p><p>To fix this we need to know the ip address where mongodb is running.</p><p><strong>docker inspect</strong> is a command that returns detailed, low-level information on Docker objects. Those objects can be docker images, containers, networks, volumes, plugins, etc. Syntax :</p><p>docker inspect &lt;container-name or id&gt;</p><p>Command:</p><p>docker inspect mongo-docker</p><p>This will give all the information related to mongo-docker. Under network object look for IPAddress key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*v_2mkaeVkMXILgBDGE6xbA.png" /></figure><p>replace localhost with this IP in the MongoDB url in the below code. Code snippet can be found in app.js under backend folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*7gUYKou-U5_47jgYGrDA1Q.png" /></figure><p>Now remove the previous created node image with below command</p><p>docker image rm node-docker-image:latest</p><p>we have to create a new image with this change</p><p>docker build -f NodeDockerFile -t node-docker-image:latest .</p><p>spin the container</p><p>docker run -d -p 3000:3000 --name node-docker node-docker-image:latest</p><p><strong>NOTE: </strong>Default network available is <strong>bridge</strong> so if you have not given any network while spinning the containers it gets attached to the bridge network.</p><p>docker network ls gives all network available. By default you will get Bridge , Host and none.</p><p>Docker network create -d bridge &lt;name of the network&gt; creates a new network in docker of bridge driver type.</p><p>Now there are two ways to attach any of your containers to this newly created bridge</p><ol><li>You need to provide network argument while spinning new container something like this:</li></ol><p>docker run -d -p 3000:3000 --network &lt;custom-network-name&gt; --name node-docker node-docker-image:latest</p><p>2. On the fly — You can also attach an existing running container to your customer network with the help of this command</p><p>docker network connect &lt;network-name&gt; &lt;container-id&gt;</p><p>In case you’d like to give your own subnet range and gateway for you custom network, this is how you can do it</p><p>docker network create --subnet &lt;subnet_range&gt; --gateway &lt;gateway&gt; &lt;customer_network_name&gt;</p><p>But , till here we saw that even if we gave a custom subnet range , the ip to the container could be anything within that range . What if we want to give a static ip to the container ? To give a static ip , this is the command</p><p>docker run -d --network &lt;custom_network&gt; --ip &lt;ip_address&gt; &lt;image_id or name&gt;</p><h3>Step -5 Verify results</h3><p>Goto any of your browser and hit <a href="http://localhost:8888/">http://localhost:8888</a> . If everything works fine you will be successfully able to see the page and must be able to add/edit/delete the blogs.</p><p>That&#39;s it !! Thanks for connecting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a62aac0cf8f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Docker]]></title>
            <link>https://prakharagarwal234.medium.com/understanding-docker-90c38aab91fa?source=rss-1714b56fe866------2</link>
            <guid isPermaLink="false">https://medium.com/p/90c38aab91fa</guid>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Prakhar Agarwal]]></dc:creator>
            <pubDate>Sun, 21 Feb 2021 14:03:20 GMT</pubDate>
            <atom:updated>2021-02-22T12:17:57.305Z</atom:updated>
            <content:encoded><![CDATA[<p>Before telling about docker , let’s take a scenario which will help you in understanding where exactly docker comes into picture. So let’s say you worked on a MEAN stack application and any of your friend/colleague asked you to show your running application but unfortunately you are not carrying your laptop with you and the only option left with you is to use there laptop. Now , to run application on a new system, first you would be needing all prerequisites software or dependencies that supports your application then pull code from GIT and do lot other stuffs to make it up and running. This is where docker comes handy . So with docker you can just create an image that will have your application and all related dependencies. You just push the image to docker hub ( cloud docker repo) and then you can simply pull it to any other system with docker installed on it and run your application without thinking much about other software dependencies.</p><h3><strong>What is Docker ?</strong></h3><p>Docker is a containerisation platform which packages your application and all of its dependencies together in the form of containers and also it ensures that your application works seamlessly in any of the other env like DEV/QA/PROD<br>irrespective of the software or other platform dependencies , it just requires docker installed on other env that&#39;s it. Simple Right ?</p><blockquote>Docker is basically its own isolated environment packaged with all needed configuration.</blockquote><p>Unlike VM docker doesn&#39;t have its own OS therefore it saves a lot memory and also reduces overburden on your system whereas a virtual machine will include a complete operating system. It will work independently and act like a computer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*CASf0_1X11WAHLldF3fnEg.png" /></figure><ul><li>Docker shares same host OS Kernel for the hardware management.</li><li>Containers are lightweight and can easily be shared via docker hub.</li><li>As it sits on the HOST OS and doesn’t have its own OS , it occupies less RAM than VMs.</li></ul><p>From Docker’s official website</p><blockquote>Docker is written in the <a href="https://golang.org/">Go programming language</a> and takes advantage of several features of the Linux kernel to deliver its functionality. Docker uses a technology called namespaces to provide the isolated workspace called the <em>container</em>. When you run a container, Docker creates a set of <em>namespaces</em> for that container.</blockquote><h3><strong>How Docker works ?</strong></h3><p>Docker works on a client-server architecture. They both connects using docker REST Api. All these component together can also be called as Docker Engine.Docker client send requests to docker server through docker REST api.</p><ol><li><strong>Docker Daemon</strong>: A persistent background process that manages Docker images, containers, networks, and storage volumes. The Docker daemon constantly listens for Docker API requests and processes them.</li><li><strong>Docker Engine REST API</strong>: An API is used by applications to interact with the Docker daemon. It can be accessed by an HTTP client.</li><li><strong>Docker CLI</strong>: A command-line interface client for interacting with the Docker daemon. It significantly simplifies how you manage container instances and is one of the key reasons why developers love using Docker.</li></ol><h3>What is Docker-Machine ?</h3><p>Docker Machine <em>was</em> the <em>only</em> way to run Docker on Mac or Windows prior to Docker v1.12. Initially docker works natively with linux and to run it with windows/mac we should install docker-machine which is nothing but a lightweight linux VM.</p><p>Docker Machine is a tool that lets you install Docker Engine on virtual hosts, and manage the hosts with docker-machine commands. You can use Machine to create Docker hosts on your local Mac or Windows box, on your company network, in your data center, or on cloud providers like Azure, AWS, or DigitalOcean.</p><p>It is not recommended to use this now as we have got <a href="https://docs.docker.com/docker-for-mac/">Docker Desktop for Mac</a> and <a href="https://docs.docker.com/docker-for-windows/">Docker Desktop for Windows</a> are available as native apps.</p><h3><strong>How Docker Containers are made and run ?</strong></h3><p>Docker containers are made from docker images and Docker File is used to build docker images .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*-otU7qzDklEgbNJVmYWNGg.png" /></figure><p><strong>DockerFile</strong></p><p>DockerFiles are plain text file which describes step-by-step instructions of all the commands you need to run to assemble a Docker Image.</p><p><strong>DockerImage</strong></p><p>Docker Image contains all your project related things ( code , libraries , dependencies etc ). Run this docker image to get a running instance of docker container. You can spin n number of containers with this image. You can even push this docker image to docker hub and share it with other teams. This will also make sure it will run in the exact same way as it was running on your system. Due to their read-only quality, these images are sometimes referred to as snapshots.Since images are in a way just templates which would be used as a base to build a container. A container is, ultimately, just a running image. Once you create a container, it adds a writable layer on top of the immutable image, meaning you can now modify it.</p><p><strong>DockerContainer</strong></p><p>A Docker container is a virtualized run-time environment where users can isolate applications from the underlying system. These containers are compact, portable units in which you can start up an application quickly and easily.</p><h3><strong>Hands On Time</strong></h3><p>We are done with the theory part. Now let&#39;s get our hands dirty and move on to the hands on part in a step wise instructions. By the end of this section you will have basic understanding to start with dockerfile , creating images from this file and running container.</p><p>Firstly make sure you have docker installed on your system. If not please visit this <a href="https://docs.docker.com/desktop/">official</a> link and follow the step wise instructions to install docker desktop for your os.</p><p>Once installed open command prompt or terminal ( for mac ) and execute this command and check the output</p><pre>$ docker container run hello-world  </pre><pre>Unable to find image &#39;hello-world:latest&#39; locally<br>latest: pulling from library/hello-world<br>1b930d010525: Pull complete<br>Status: Downloaded newer image for hello world</pre><pre>Hello from Docker!<br>This message shows that your installation appears to be working correctly.</pre><pre>To generate this message, Docker did the following :<br>1. The Docker client contacted the Docker daemon.<br>2. The Docker daemon pulled the “hello-world” image from the Docker Hub.<br>3. The Docker daemon created a new container from that image which runs the executable that produces the output you are currently reading.<br>4. The Docker daemon streamed that output to the Docker client, which sent it to your terminal.</pre><pre>To try something more ambitious, you can run an ubutu container with:<br>$ docker run -it ubuntu bash</pre><p>Let look at what&#39;s happening behind the scene</p><ul><li>here docker engine tried to find an image named hello-world.</li><li>But as its just a start and our first container run, there is no such image stored locally</li></ul><pre><em>Unable to find image &#39;hello-world:latest&#39; locally</em></pre><ul><li>Docker engine goes to DockerHub(docker cloud repo), looking for hello-world image.</li></ul><p><a href="https://hub.docker.com/">https://hub.docker.com/</a></p><ul><li>It finds the image, pulls it down and then runs it in a container.</li><li>Hello World only function is to output the text you see in the terminal, after which the container exits</li></ul><p>But what if you got a set of instructions to perform on the base image like installing dependencies or exposing port or anything. Here, come dockerfile.</p><p>Lets see how that works in sequence of steps:</p><ol><li><strong>Create DockerFile</strong> :</li></ol><p>Docker file can be created with any name. In Build your Docker File using the following instructions.</p><pre>#This is a sample Image<br>FROM ubuntu</pre><pre>RUN apt-get update<br>RUN apt-get -y install nginx<br>EXPOSE 80</pre><pre>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><p>In this docker file we are providing instruction to create an image with ubuntu as base image with nginx installed on it.</p><p>The following points need to be noted about the above file −</p><ul><li>The first line “#This is a sample Image” is a comment. You can add comments to the Docker File with the help of the <strong>#</strong> command</li><li>The next line has to start with the <strong>FROM</strong> keyword. It tells docker, from which base image you want to base your image from. In our example, we are creating an image from the <strong>ubuntu</strong> image. The image will be pulled from docker hub repository.</li><li>The next command is the person who is going to maintain this image. Here you specify the <strong>MAINTAINER</strong> keyword and just mention the email ID.</li><li>The <strong>RUN</strong> command is used to run instructions against the image. In our case, we first update our Ubuntu system and then install the nginx server on our <strong>ubuntu</strong> image.</li><li>In last command Nginx uses the daemon off directive to run in the foreground.</li></ul><p>Every command you specify (FROM, RUN, COPY, etc.) in your Dockerfile causes the previous image to change, thus creating a new layer.</p><p>The concept of layers comes in handy at the time of building images. Because layers are intermediate images, if you make a change to your Dockerfile, docker will build <strong>only</strong> the layer that was changed and the ones after that. This is called layer caching.</p><p><strong>2. Build Image :</strong></p><p>It&#39;s time to build the image from the created docker file. Syntax of command to build docker image:</p><pre>docker build -f &lt;docker-file name&gt; -t &lt;image-name&gt;:&lt;tag&gt; &lt;dir&gt;</pre><ul><li>-f &lt;docker-file name&gt; : In case the name is dockerfile you can skip this argument and if anything else then you need to provide the name of the file.</li><li>-t &lt;image-name&gt;:&lt;tag&gt; To tag this image with image-name and &lt;tag&gt; is nothing but a version.</li><li>&lt;dir&gt; : path where dockerfile is located. For current directory just add . (period)</li></ul><p>Command to run :</p><p>docker build -t ubuntu-nginx-test:latest .</p><p>Note : If you run this same docker file again you will notice that it got build pretty quick as compared to previous run that’s because everything gets picked from cache as you already ran the same step and it was cached at that time. To confirm this do docker image ps after second run and you will find both the images will have same image id.</p><p><strong>3. Run Container :</strong></p><p>Now let&#39;s spin a container using the image that we just created. Command syntax</p><p>docker run -d -p &lt;host-port&gt;:&lt;container-port&gt; --name &lt;container-name&gt; &lt;image-name&gt;:&lt;tag&gt;</p><ul><li>-d : This option is used to run the container in detached mode. This is so that the container can run in the background.</li><li>-p : it is used for port mapping i.e. host machine port with the container port.</li></ul><p>Command to run container for above created image</p><p>docker run -d -p 1234:80 --name ubuntu-nginx-container ubuntu-nginx-test:latest</p><p>Here, we are porting nginx default 80 port with our machine’s 1234 port ( it could be anything except the one that are already in use).</p><p><strong>4. Verify Results</strong></p><p>Goto any of the browser and hit <a href="http://local/">http://local</a>host:1234 and you should see default nginx page.</p><p><strong>5. Docker Hub</strong></p><p>If you have reached here it means you are able to see the nginx page and tada!! you have successfully spin you first docker container. Now this one is a basic and simple nginx container with ubuntu as a base image but just imagine in case this would be an entire application. How easy it would be for you if you could push this image to a public repository on the cloud then simply pull the same to any other system and make it up and running.Most of the images such as Centos, Ubuntu, and Jenkins are all publicly available for all. So let&#39;s push our image to public repo.</p><p><strong>5a)</strong> Log into Docker Hub and create your repository. This is the repository where your image will be stored. Go to <a href="https://hub.docker.com/">https://hub.docker.com/</a> and log in with your credentials or else sign up .</p><p><strong>5b)</strong> Click “Create Repository” on the screen and create a repository with the name <strong>demorep</strong>. Make sure that the visibility of the repository is public.</p><p><strong>5c)</strong> Once the repository is created, make a note of the <strong>pull</strong> command which is attached to the repository.</p><p><strong>5d)</strong> login into the Docker Hub repository from the command prompt. The Docker login command will prompt you for the username and password to the Docker Hub repository.</p><p><strong>5e)</strong> We need to tag our <strong>ubuntu-nginx-test</strong> to the new repository created in Docker Hub. We can do this via the Docker <strong>tag command</strong>.</p><pre>docker tag imageID &lt;username&gt;/&lt;repositoryname&gt;:tagname</pre><ul><li><strong>imageID</strong> − This is the ImageID which needs to be tagged to the repository.</li><li><strong>Repositoryname</strong> − This is the repository name to which the ImageID needs to be tagged to.</li></ul><p>Example</p><pre>sudo docker tag ab0c1d3744dd demousr/demorep:1.0</pre><p><strong>5f)</strong> Once the image has been tagged, it’s now time to push the image to the Docker Hub repository. We can do this via the Docker <strong>push</strong> command.</p><pre>docker push Username/Repositoryname:tagname</pre><ul><li><strong>Repositoryname</strong> − This is the repository name which needs to be pushed to the Docker Hub.</li></ul><p>Example</p><pre>docker push demousr/demorep:1.0</pre><p>If you go back to the Docker Hub page and go to your repository, you will see the tag name in the repository.</p><p>Now let’s try to pull the repository we uploaded onto our Docker hub. Let’s first delete the images, <strong>ubuntu-nginx-test</strong> from the local Docker host. Let’s use the Docker <strong>pull command</strong> to pull the repository from the Docker Hub.</p><p>docker pull UserName/Repositoryname:tagname</p><p>Example</p><pre>docker pull demousr/demorep:1.0</pre><pre>NOTE:Everything on docker hub is related to tag name .</pre><h3>Other Useful Commands</h3><ul><li>docker ps it gives all the existing running containers.</li><li>docker ps -a it gives all the containers including the exited ones.</li><li>docker restart &lt;container_id&gt; to restart exited container</li><li>docker image ls list all the images</li><li>docker stop &lt;container_id or name &gt; to stop the container</li><li>docker rm &lt;container_id or name &gt; to remove container</li><li>docker image rm &lt;image_id or name&gt; to remove image</li><li>docker rm -vf $(docker ps -a -q) kill all containers</li><li>docker rmi -f $(docker images -a -q) remove all docker images</li><li>docker logs &lt;container_id or name&gt; get ogs of the provided container</li><li>docker exec -it &lt;container_name&gt; /bin/bash to get a bash shell in the container.</li><li>docker exec -it &lt;container_name&gt; &lt;command&gt; to execute whatever command you specify in the container.</li><li>docker exec -it &lt;container-id&gt; sh to get into shell</li><li>docker system -df gives the total size of all images , containers.</li><li>docker image prune removes all images that are not tagged.</li><li>docker image prune -a removes all unused images.</li></ul><p>Thanks for taking out the time and going through this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90c38aab91fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cloudwatch —Triggering  Events , Collecting Logs and creating Alarms]]></title>
            <link>https://prakharagarwal234.medium.com/cloudwatch-triggering-events-collecting-logs-and-creating-alarms-9200d44c6c0e?source=rss-1714b56fe866------2</link>
            <guid isPermaLink="false">https://medium.com/p/9200d44c6c0e</guid>
            <category><![CDATA[cloudwatch-events]]></category>
            <category><![CDATA[cloudwatch-logs]]></category>
            <category><![CDATA[cloudwatch]]></category>
            <dc:creator><![CDATA[Prakhar Agarwal]]></dc:creator>
            <pubDate>Sat, 04 Jul 2020 22:19:10 GMT</pubDate>
            <atom:updated>2020-07-04T22:19:10.983Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cloudwatch —Triggering Events , Collecting Logs and creating Alarms</h3><p>Amazon cloudwatch is an Amazon Web Service that provides you real time monitoring of aws resources and customer application running on amazon infrastructure.</p><blockquote><strong>What Does Amazon CloudWatch do ?</strong></blockquote><blockquote>1)Create Alarms and send notifications<br>2)Collect, monitor and store log files<br>3) Send system events from aws resources to AWS Lambda, SNS etc<br>4) Collects and tracks key metrics.</blockquote><blockquote><strong>What are resources Managed by AWS CloudWatch</strong></blockquote><blockquote>1)EC2<br>2)Data stored in S3<br>3)Elastic Load balancer<br>4)Database (AWS RDS)<br>5)Other various AWS services</blockquote><p>In this blog , i am going to share the use cases for each services along with the steps to implement it. So without much a due lets get started and see the services provided by cloudwatch one by one:</p><ol><li><strong>Create Alarms and send Notification</strong></li></ol><p>In this service ,we are going to setup an alarm using SNS(Simple Notification Service)and Cloudwatch service so that we get an email notification as soon as CPU utilization of our instance is less than 25%.</p><p>To create a notification , you first need to create a topic in SNS and subscribe to it with your email id.</p><p><strong>1-a )</strong> Goto SNS service , then Topic and Create Topic. Enter Topic name and description and click Create Topic.<br>On the next page , click Create Subscription .</p><p><strong>1- b)</strong> On Create Subscription page , select the protocol , here i want the notification as email . Provide your email address ( valid one ) in the endpoint box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*HeV2ZpY-yt4Tt4m22-DQOg.png" /></figure><p>Click Create Subscription.</p><p><strong>1-c )</strong> Now , goto Cloudwatch service and select metrics from left menu pane.Choose EC2 and then per-instance metrics.</p><p>You will get a list of metrics available for EC2 . Look for CPUUtilization and it will give list of all ec2 instance ( in case you have more than one) .</p><p>Select the one instance for which you want to get the notification. Then goto Graph Metric tab and click alarm icon under Actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z51Gkb5CYeeQT81X6D0f4w.png" /></figure><p><strong>1-d )</strong> On the next page , select the threshold</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*8xuoxs-qbDRxLnYW6EXdhQ.png" /></figure><p>Here , i set threshold as ≤ 25. Click Next.</p><p><strong>1-e )</strong> On Configuration screen , select option an existing SNS topic and choose the SNS topic we created earlier.Click Next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*vsStMT8d_TuFGgTHcBww4w.png" /></figure><p>Give Alarm name and description and click next to review the setting. Once done click create alarm button. Your alarm is created.</p><p><em>NOTE: Alarm will be in Pending Confirmation state untill you verify the provided email address.</em></p><p><strong>2. Collect, monitor and store log files</strong></p><p>To collects logs and metrics we would be installing cloudwatch agent on our EC2 instance that will export our provided logs to cloudwatch service and provide measureable and actionable data about system performances</p><p>You will first need to ensure your instances are managed by AWS systems manager. To do this lets create a role having specifc permission and attach it to our EC2 instance.</p><p><strong>2-a) Create a Role.</strong></p><p>Goto IAM service . Select Role from left navigation menu and click Create Role.</p><p>Select AWS Service then EC2 from ‘Choose a Use Case’ section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rAUVEpGcr_tt80bDAQfqA.png" /></figure><p>Click Next:Permission</p><p>On the next screen search and select below three policies</p><p><a href="https://console.aws.amazon.com/iam/home?region=ap-south-1#/policies/arn%3Aaws%3Aiam%3A%3Aaws%3Apolicy%2FCloudWatchAgentAdminPolicy"><em>CloudWatchAgentAdminPolicy</em></a> →Allows Cloudwatch agent to save agent configuration file to Systems Manager Parameter store <br><a href="https://console.aws.amazon.com/iam/home?region=ap-south-1#/policies/arn%3Aaws%3Aiam%3A%3Aaws%3Apolicy%2FCloudWatchAgentAdminPolicy"><em>CloudWatchAgentServerPolicy</em></a><em> </em>→ Allows to write data on cloudwatch<br><a href="https://console.aws.amazon.com/iam/home?region=ap-south-1#/policies/arn%3Aaws%3Aiam%3A%3Aaws%3Apolicy%2Fservice-role%2FAmazonEC2RoleforSSM"><em>AmazonEC2RoleforSSM</em></a> → giving Systems manager permission to manage our EC2 instance</p><p>and click Next:Tags button. Add tags if you want to and proceed to Review Step. <br>Give the Role a name and description and click Create Role and your role is created.</p><p><strong>2-b) Attach the Role to EC2 instance.</strong></p><p>Goto EC2 dashboard , select your EC2 instance and in Actions menu choose Attach/Replace IAM Role under Instance Settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*obziiz-W8zzy49I9d3PdyQ.png" /></figure><p>On the next , select the role that we just created and apply the changes.By attaching you are allowing your EC2 instance to be managed by System Manager service.</p><p><strong>2-c) Configure AWS CLI to admin user profile</strong></p><p>This we will be needing later as we work with cloudwatch agent.</p><pre>#command to configure AWS CLI default-profile<br>aws configure</pre><pre>#Enter Access key and Secret key of the admin user <br>AWS Access Key ID [None]: R*******E</pre><pre>AWS Secret Access Key [None]: L*******h</pre><pre>#Leave region as default and enter <br>Default region name [ap-south-1]:</pre><pre>#Enter json <br>Default output format [None]: json</pre><p><strong>2-d) Install Cloudwatch Agent on EC2</strong></p><p>Goto System Manager service and choose Quick Setup option from left menu.<br>On the quick setup, leave ‘Permission Required’ section as default ,under ‘Quick Setup options’ select ‘Install and configure the CloudWatch agent’ (rest all is as per the requirement). From ‘Targets’ section , choose intances manually and select your instance. Submit the changes.</p><p>On the next page you will see status of the ‘Quick Setup options’ selected from previous step as pending after few seconds this will change to success.</p><p>To check the installation , connect to EC2 instance and check the status</p><pre>sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -m ec2 -a status</pre><p><em>NOTE: Default location for cloudwatch agent is /opt/aws/</em></p><p>this should give status as running .</p><p><em>NOTE: If you are not seeing aws folder inside opt directory wait for few more mins sometimes it takes a bit more time.</em></p><p><strong>2-e) Start CloudWatch Agent configuration wizard</strong></p><p>As we are done installing it now its time to run cloudwatch agent configuation wizard. This will create agent configuration file.Start the CloudWatch agent configuration wizard by entering the following command:</p><pre>sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-config-wizard</pre><p>Next you will see some set of questions and based on your answers agent will create a configuration file which will then collect the logs and metrics .<br>Configuraton wizard look likes this:</p><pre>=============================================================</pre><pre>= Welcome to the AWS CloudWatch Agent Configuration Manager =</pre><pre>=============================================================</pre><pre>On which OS are you planning to use the agent?</pre><pre>1. linux</pre><pre>2. windows</pre><pre>default choice: [1]:</pre><pre>1</pre><pre>Trying to fetch the default region based on ec2 metadata...</pre><pre>Are you using EC2 or On-Premises hosts?</pre><pre>1. EC2</pre><pre>2. On-Premises</pre><pre>default choice: [1]:</pre><pre>1</pre><pre>Which user are you planning to run the agent?</pre><pre>1. root</pre><pre>2. cwagent</pre><pre>3. others</pre><pre>default choice: [1]:</pre><pre>1</pre><pre>Do you want to turn on StatsD daemon?</pre><pre>1. yes</pre><pre>2. no</pre><pre>default choice: [1]:</pre><pre>2</pre><pre>Do you want to monitor metrics from CollectD?</pre><pre>1. yes</pre><pre>2. no</pre><pre>default choice: [1]:</pre><pre>2</pre><pre>Do you want to monitor any host metrics? e.g. CPU, memory, etc.</pre><pre>1. yes</pre><pre>2. no</pre><pre>default choice: [1]:</pre><pre>1</pre><pre>Do you want to monitor cpu metrics per core? Additional CloudWatch charges may apply.</pre><pre>1. yes</pre><pre>2. no</pre><pre>default choice: [1]:</pre><pre>2</pre><pre>Do you want to add ec2 dimensions (ImageId, InstanceId, InstanceType, AutoScalingGroupName) into all of your metrics if the info is available?</pre><pre>1. yes</pre><pre>2. no</pre><pre>default choice: [1]:</pre><pre>2</pre><pre>Would you like to collect your metrics at high resolution (sub-minute resolution)? This enables sub-minute resolution for all metrics, but you can customize for specific metrics in the output json file.</pre><pre>1. 1s</pre><pre>2. 10s</pre><pre>3. 30s</pre><pre>4. 60s</pre><pre>default choice: [4]:</pre><pre>Which default metrics config do you want?</pre><pre>1. Basic</pre><pre>2. Standard</pre><pre>3. Advanced</pre><pre>4. None</pre><pre>default choice: [1]:</pre><pre>Current config as follows:</pre><pre>{</pre><pre>&quot;agent&quot;: {</pre><pre>&quot;metrics_collection_interval&quot;: 60,</pre><pre>&quot;run_as_user&quot;: &quot;root&quot;</pre><pre>},</pre><pre>&quot;metrics&quot;: {</pre><pre>&quot;metrics_collected&quot;: {</pre><pre>&quot;disk&quot;: {</pre><pre>&quot;measurement&quot;: [</pre><pre>&quot;used_percent&quot;</pre><pre>],</pre><pre>&quot;metrics_collection_interval&quot;: 60,</pre><pre>&quot;resources&quot;: [</pre><pre>&quot;*&quot;</pre><pre>]</pre><pre>},</pre><pre>&quot;mem&quot;: {</pre><pre>&quot;measurement&quot;: [</pre><pre>&quot;mem_used_percent&quot;</pre><pre>],</pre><pre>&quot;metrics_collection_interval&quot;: 60</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>Are you satisfied with the above config? Note: it can be manually customized after the wizard completes to add additional items.</pre><pre>1. yes</pre><pre>2. no</pre><pre>default choice: [1]:</pre><pre>Do you have any existing CloudWatch Log Agent (http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AgentReference.html) configuration file to import for migration?</pre><pre>1. yes</pre><pre>2. no</pre><pre>default choice: [2]:</pre><pre>2</pre><pre>Do you want to monitor any log files?</pre><pre>1. yes</pre><pre>2. no</pre><pre>default choice: [1]:</pre><pre>1</pre><pre>Log file path:</pre><pre>/var/log/nginx/*.log</pre><pre>Log group name:</pre><pre>default choice: [*.log]</pre><pre>nginx-log</pre><pre>Log stream name:</pre><pre>default choice: [{instance_id}]</pre><pre>blogger-instance</pre><pre>Do you want to specify any additional log files to monitor?</pre><pre>1. yes</pre><pre>2. no</pre><pre>default choice: [1]:</pre><pre>1</pre><pre>Log file path:</pre><pre>/home/ubuntu/.pm2/logs/*.log</pre><pre>Log group name:</pre><pre>default choice: [*.log]</pre><pre>pm2 logs</pre><pre>Log stream name:</pre><pre>default choice: [{instance_id}]</pre><pre>blogger-instance</pre><pre>Do you want to specify any additional log files to monitor?</pre><pre>1. yes</pre><pre>2. no</pre><pre>default choice: [1]:</pre><pre>2</pre><pre>Saved config file to /opt/aws/amazon-cloudwatch-agent/bin/config.json successfully.</pre><pre>Current config as follows:</pre><pre>{</pre><pre>&quot;agent&quot;: {</pre><pre>&quot;metrics_collection_interval&quot;: 60,</pre><pre>&quot;run_as_user&quot;: &quot;root&quot;</pre><pre>},</pre><pre>&quot;logs&quot;: {</pre><pre>&quot;logs_collected&quot;: {</pre><pre>&quot;files&quot;: {</pre><pre>&quot;collect_list&quot;: [</pre><pre>{</pre><pre>&quot;file_path&quot;: &quot;/var/log/nginx/*.log&quot;,</pre><pre>&quot;log_group_name&quot;: &quot;nginx-log&quot;,</pre><pre>&quot;log_stream_name&quot;: &quot;blogger-instance&quot;</pre><pre>},</pre><pre>{</pre><pre>&quot;file_path&quot;: &quot;/home/ubuntu/.pm2/logs/*.log&quot;,</pre><pre>&quot;log_group_name&quot;: &quot;pm2 logs&quot;,</pre><pre>&quot;log_stream_name&quot;: &quot;blogger-instance&quot;</pre><pre>}</pre><pre>]</pre><pre>}</pre><pre>}</pre><pre>},</pre><pre>&quot;metrics&quot;: {</pre><pre>&quot;metrics_collected&quot;: {</pre><pre>&quot;disk&quot;: {</pre><pre>&quot;measurement&quot;: [</pre><pre>&quot;used_percent&quot;</pre><pre>],</pre><pre>&quot;metrics_collection_interval&quot;: 60,</pre><pre>&quot;resources&quot;: [</pre><pre>&quot;*&quot;</pre><pre>]</pre><pre>},</pre><pre>&quot;mem&quot;: {</pre><pre>&quot;measurement&quot;: [</pre><pre>&quot;mem_used_percent&quot;</pre><pre>],</pre><pre>&quot;metrics_collection_interval&quot;: 60</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>Please check the above content of the config.</pre><pre>The config file is also located at /opt/aws/amazon-cloudwatch-agent/bin/config.json.</pre><pre>Edit it manually if needed.</pre><pre>Do you want to store the config in the SSM parameter store?</pre><pre>1. yes</pre><pre>2. no</pre><pre>default choice: [1]:</pre><pre>What parameter store name do you want to use to store your config? (Use &#39;AmazonCloudWatch-&#39; prefix if you use our managed AWS policy)</pre><pre>default choice: [AmazonCloudWatch-linux]</pre><pre>Trying to fetch the default region based on ec2 metadata...</pre><pre>Which region do you want to store the config in the parameter store?</pre><pre>default choice: [ap-south-1]</pre><pre>Which AWS credential should be used to send json config to parameter store?</pre><pre>1. A************** (From SDK)</pre><pre>2. Other</pre><pre>default choice: [1]:</pre><pre>Successfully put config to parameter store AmazonCloudWatch-linux.</pre><pre>Program exits now.</pre><p>NOTE:You can provide location of external logs as well in the wizard. Look for the question ‘Do you want to monitor any log files?’ . Like in the above case i have given pm2 and nginx logs to be collected by agent. Similarly , you can give any logs .</p><p>Once done you can check config file on aws console as well on your ec2 instance and edit it if required.</p><p>location on EC2 inctacne is <br>/opt/aws/amazon-cloudwatch-agent/config.json</p><p>on AWS management , <br>Parameter store menu under System Manager service</p><p><strong>2-f) Start cloudwatch agent</strong></p><p>Use this below command to start agent</p><pre>sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c ssm:configuration-parameter-store-name -s</pre><p>Here , configuration-parameter-store-name by default is AmazonCloudWatch-linux ( if you have chosen default in the configuration wizard otherwise provide the name you have given there)</p><p>In this command, -a fetch-config causes the agent to load the latest version of the CloudWatch agent configuration file, and -s starts the agent. If everything done successfully you will see this :</p><pre>/opt/aws/amazon-cloudwatch-agent/bin/config-downloader --output-dir /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.d --download-source ssm:AmazonCloudWatch-linux --mode ec2 --config /opt/aws/amazon-cloudwatch-agent/etc/common-config.toml --multi-config default</pre><pre>Region: ap-south-1</pre><pre>credsConfig: map[]</pre><pre>Successfully fetched the config and saved in /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.d/ssm_AmazonCloudWatch-linux.tmp</pre><pre>Start configuration validation...</pre><pre>/opt/aws/amazon-cloudwatch-agent/bin/config-translator --input /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json --input-dir /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.d --output /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.toml --mode ec2 --config /opt/aws/amazon-cloudwatch-agent/etc/common-config.toml --multi-config default</pre><pre>2020/06/08 19:50:24 Reading json config file path: /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.d/ssm_AmazonCloudWatch-linux.tmp ...</pre><pre>Valid Json input schema.</pre><pre>I! Detecting runasuser...</pre><pre>No csm configuration found.</pre><pre>Configuration validation first phase succeeded</pre><pre>/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent -schematest -config /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.toml</pre><pre>Configuration validation second phase succeeded</pre><pre>Configuration validation succeeded</pre><p>And we are done .</p><p>Now , you can check your logs on AWS management console . Goto Cloudwatch server and select log groups from left menu .You will see the logs provided by you in the configuration wizard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NJADEOLi8yDrGWdvoHFDOw.png" /></figure><p><strong>3. Send System events from aws resources to AWS Lambda</strong></p><p>Amazon Cloudwatch events is a part of Amazon CloudWatch which delivers a near real-time stream of system events that allows you to monitor and respond to the change in your AWS resources by means of rules that route events to one or more targets.</p><p><strong>Use-Case 1 ) Start and Stop instances at a particular time</strong></p><p>Let’s assume a scenario where you are running a full fledged website hosted on amazon with 4–5 virtual servers and currently they are all active and all through the day. But , lately you notice that traffic is high during day time whereas it is considerable low during night time. CPU utilization is less than 50% and most of the night time they are idle. However ,you are paying same amount as of day time even when they are underused during night time.</p><p>For this scenario you can create a lambda function to shutdown few of your instances during night time and start them back again in the morning . It will be obviously tedious to this manually every time and to automate this we will use cloudwatch event.</p><p><strong>1- a) Create policy to control EC2 instance.</strong></p><p>Goto IAM service . Select Policies from left navigation menu and click Create Policy.</p><p>Under Service , select EC2.<br>In Actions section, search and select StartInstances and StopInstances<br>In Resources , you can select all or choose manually and then select your instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1M34sUWlMpuSt8xlKGZoUw.png" /></figure><p>Click Review Policy. On this page , give Policy a name and description and click Create Policy.</p><p><strong>1-b ) Assign this policy to a role</strong></p><p>Now we will assign this policy to a role with use case as lambda.</p><p>Goto main IAM dashboard and select Roles from left menu. Click Create Role .<br>Choose Lambda as a use case on this page .<br>Next page , search and select the above create policy .<br>Give any tag name to the role and click new to review .<br>Provide role a name and description , check you setting and create role.</p><p>Our Lambda role with start and stop ec2 instance policy has been created successfully.</p><p><strong>1- c) Create Lambda function</strong></p><p>We will create two lambda functions one for each stop and start ec2 instacnes.</p><p>First we are creating stop instance. For that goto Lambda service and click create Role.<br>Choose Author from scratch and select the role that we create above .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwMxXZ305GXGvysWAzFVmg.png" /></figure><p>Click Create Function.</p><p>In code editor panel</p><pre>const aws = require(&#39;aws-sdk&#39;);</pre><pre>exports.handler = (event, context, callback)=&gt; {<br>    const ec2= new aws.EC2({region:event.instanceRegion});<br>    <br>    ec2.stopInstances({InstanceIds:[event.instanceId]}).promise()<br>    .then(() =&gt; callback(null,`Successfully stopped ${event.instanceId}`))<br>    .catch(err =&gt; callback(err));<br>};</pre><p>and click Save. Now , we have to provide this function instanceRegion and instacneId value.</p><p>Click configure test event</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCEfR6GDOzH9CFCINiIKVQ.png" /></figure><p>and provide json values for both fields</p><pre>{<br>  &quot;instranceRegion&quot;: &quot;YOUR_REGION_NAME&quot;,<br>  &quot;instanceId&quot;: &quot;YOUR_EC2_INSTANCE_ID&quot;<br>}</pre><p>Click Create and then click test to test the function.You should see message ‘Successfully stopped &lt;YOUR_EC2_INSTANCE_ID&gt;’ and also you can verify the same by going to your EC2 dashboard .</p><p>Following the same process create a start instance function with this code</p><pre>const aws = require(&#39;aws-sdk&#39;);</pre><pre>exports.handler = (event, context, callback)=&gt; {<br>    const ec2= new aws.EC2({region:event.instanceRegion});<br>    <br>    ec2.startInstances({InstanceIds:[event.instanceId]}).promise()<br>    .then(() =&gt; callback(null,`Successfully stopped ${event.instanceId}`))<br>    .catch(err =&gt; callback(err));<br>};</pre><p>Once we are done with are functions. Now , we will automate this.</p><p><strong>1-d) Automate lambda functions through Cloudwatch events</strong></p><p>Till now we have used Lambda function to start and stop instance now we will automate this with the help of cloudwatch events.</p><p>I want my instance to stop at 2030 hours everyday and restart next day morning at 0630 hours.</p><p>To do this goto Cloudwatch service , click rules under events from left menu. Make the changes as shown in below image .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DOTc9b3M6HgXGb4UxiSbpw.png" /></figure><p>Here , i have scheduled this event to trigger at 2030 hours and target is stopinstance lambda function. Expand configure input and <br>in Constant (JSON text) pass the parameters to the lambda function in json function<br>{ “instranceRegion”: “ap-south-1”, “instanceId”: “EC2_INSTANCE_ID” }</p><p>Click Configure Details and give this event a name and description before saving it.</p><p>Similarly create an event to start instance and we have successfully automated the process.</p><p><strong>Use Case-2) Trigger email notification if a instance get terminated or stopped</strong></p><p>Consider , a scenario where one of your instance goes down and you are not aware of it . It affected the user experience badly due to which all the traffic at that time moved to any other customer. If you would have notified at that point of time you could have probably done something and save the user traffic going to someother place. We can achieve this using cloudwatch event and for that we are going to use SNS service and topic that we created in <strong>Create Alarms and send Notification </strong>section.</p><p>Create a new Rule and set the below configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PzHtaIhqVWg68-VeLFSGLQ.png" /></figure><p>Here , i have set the rule to trigger when any of my instance changes its state from starting to stopping or stopped or shutting-down or terminated i should get notified on the topic created in SNS.</p><p><strong>Use Case 3)Automatically update IP addresses without using Elastic IPs</strong></p><p>You have a domain name in Amazon Route 53 pointing to an Amazon EC2 instance. However, if the instance is stopped and started, its public IP address changes. This breaks the A-Record since it is pointing to the wrong IP address.</p><p>One solution to this problem is having an Elastic IP and attach your instance to this IP. In this case A record will not break. But, AWS gives a default limit of 5 Elastic IP addresses per region. You can request a limit increase, but what if you need <em>lots</em> of them?</p><p>Another solution is using lambda function and cloudwatch event. Lets see how this solution works:</p><p><strong>3–a ) Create a Policy.</strong></p><p>Goto IAM service and create a new policy. In Json editor , paste the below policy</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;Action&quot;: [<br>                &quot;logs:CreateLogGroup&quot;,<br>                &quot;logs:CreateLogStream&quot;,<br>                &quot;logs:PutLogEvents&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:logs:*:*:*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;route53:ChangeResourceRecordSets&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:route53:::hostedzone/&lt;HOSTED_ZONE_ID&gt;&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;route53:GetChange&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:route53:::change/*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;ec2:DescribeInstances&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        }<br>    ]<br>}</pre><p>Note that the above policy specifically allow the role to perform “ChangeResourceRecordSets” on the Route 53 zone with specified hosted zone id, and to perform “DescribeInstances” on all EC2 instances. The other actions related to logging are required for AWS CloudWatch logging streams to work correctly.</p><p><strong>3-b ) Create a new role for lambda usecase and attach above policy to it</strong></p><p>Please refer to use case 1-c for the steps.</p><p><strong>3-c) Create a lambda function</strong></p><p>Create a python based lambda function and paste below</p><pre>from __future__ import print_function</pre><pre>import boto3, json, re</pre><pre>HOSTED_ZONE_ID = &#39;&lt;HOSTED_ZONE_ID&gt;&#39;</pre><pre>def lambda_handler(event, context):<br>    ec2 = boto3.resource(&#39;ec2&#39;)<br>    route53 = boto3.client(&#39;route53&#39;)</pre><pre>instance_id = event[&#39;detail&#39;][&#39;instance-id&#39;]<br>    print(instance_id)<br>    instance = ec2.Instance(instance_id)<br>    instance_ip = instance.public_ip_address</pre><pre>print(&quot;Processing: {0}&quot;.format(instance_id))</pre><pre>dns_changes = {<br>        &#39;Changes&#39;: [<br>            {<br>                &#39;Action&#39;: &#39;UPSERT&#39;,<br>                &#39;ResourceRecordSet&#39;: {<br>                    &#39;Name&#39;: &quot;&lt;RECORD_SET_NAME&gt;&quot;,<br>                    &#39;Type&#39;: &#39;A&#39;,<br>                    &#39;ResourceRecords&#39;: [<br>                        {<br>                            &#39;Value&#39;: instance_ip<br>                        }<br>                    ],<br>                    &#39;TTL&#39;: 300<br>                }<br>            }<br>        ]<br>    }</pre><pre>print(&quot;Updating Route53 to create:&quot;)</pre><pre>response = route53.change_resource_record_sets(<br>        HostedZoneId=HOSTED_ZONE_ID,<br>        ChangeBatch=dns_changes<br>    )</pre><pre>return {&#39;status&#39;:response[&#39;ChangeInfo&#39;][&#39;Status&#39;]}</pre><p>Here , when the EC2 instance state change event is triggered, details about the event are passed to the lambda function. This includes details about the affected EC2 instance, such as its identifier. This allows us to look up details about the instance, including its public IP address, and the tags.</p><p><strong>3-d ) Create a cloudwatch event</strong></p><p>Goto Cloudwatch and create a new rule event with below configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHovqpg7xIDErijiFSqE0Q.png" /></figure><p>When provided instance’s state changes from stopped to running , this event will trigger our lambda function.</p><p>Now to test stop your EC2 instance and start again, you will see record in the route53 will be update with the new public ip. You can also look the logs in cloudwatch log groups.</p><p>With that we came to an end with cloudwatch services tutorial where we discussed services that cloudwatch provide , configuring them step by step with the use cases.</p><p>I hope you all get some learning from this. Keep following!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9200d44c6c0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hosting MEAN Application on AWS (front end on S3 and backend on EC2 )with Nginx and HTTPS(part-2)]]></title>
            <link>https://prakharagarwal234.medium.com/hosting-mean-application-on-aws-front-end-on-s3-and-backend-on-ec2-with-nginx-and-https-part-2-42ed6cd797fa?source=rss-1714b56fe866------2</link>
            <guid isPermaLink="false">https://medium.com/p/42ed6cd797fa</guid>
            <category><![CDATA[hosting]]></category>
            <category><![CDATA[mean]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Prakhar Agarwal]]></dc:creator>
            <pubDate>Sat, 13 Jun 2020 14:05:48 GMT</pubDate>
            <atom:updated>2020-06-25T20:04:12.730Z</atom:updated>
            <content:encoded><![CDATA[<p>So we are here in the second part of our series on MEAN stack application hosting on AWS. Before moving on i would like to tell the things that we have done so far. In part-1 , we have deployed our front end i.e. angular part on AWS using service like S3 for storing angular code and serving the bucket as static website, CloudFront as CDN service , we used Certificate Manager to create free SSL certificate and attached them to cloudfront, Route53 DNS service. If you are looking to use any of these service you can check out <a href="https://medium.com/@prakharagarwal234/hosting-mean-application-on-aws-front-end-on-s3-and-backend-on-ec2-with-nginx-and-https-part-1-21177297f1c1">Part-1 </a>of this series.</p><p>We will now move to configure our back-end which comprises of node.js , express.js and mongoDb on EC2 service.</p><p>Let’s start with the setup -</p><p><strong>Step-1 Launching an EC2 instance.</strong></p><p>Elastic Compute Cloud or EC2 is a virtual server that assists users to run numerous applications on the AWS cloud infrastructure. Its one of the oldest service given by amazon and mostly all compute services are built on top of EC2 only. So , first of login into your aws account and goto EC2 services.</p><p><strong>1-a Login and Launching an EC2 instance</strong></p><p>On EC2 dashboard , click Launch Instance button in Launch Instance section.</p><p><strong>1-b Choose Amazon Machine Image (AMI)</strong></p><p>Now , In order to set up your machine, there must be an operating system embedded, which serves as a base for the EC2 instances.<br>Therefore , our next step is to choose an AMI image. Filter free AMI images and look for your preferred image . I went for Ubuntu Server 18.04 LTS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7kwd4jCZsBraxEALS2DSAw.png" /></figure><p><strong>1-c Choose the type for the AWS EC2 Instance</strong></p><p>Once you’ve selected your AMI, you must select hardware for your machine. AWS terms it as EC2 instance type. Therefore, you will have to select the type of instance that best suits your business needs. Choose the amount of RAM memory and processor power for your machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0TD5KZYZ-j8KVh8fpOruag.png" /></figure><p>I have selected t2.micro as this would be sufficient for the starting phase of my website .Click Review and Launch. Next three steps could be skipped as we are not changing any configuration in those steps .</p><p><strong>1-d Configure Instance</strong></p><p>This step could be left as default but if you like you can add private IPs manually or set them automatically. Also you can configure basic networking details such as if you would like to create a new Virtual Private Cloud, set up IP and subnet it; or you can go for the default existing VPC. Click Add Storage to move to the next step.</p><p><strong>1-e Add Storage</strong></p><p>Once you’ve made all the necessary configurations to the instance, now you must add storage to your machine. You can add new volumes, change their type and size amongst other features. Click ‘Next:Add Tags’ button.</p><p><strong>1-f Add Tags</strong></p><p>This step is to make sure you add labels to your EC2 instances . This makes sense in case you have created too many instance then by giving labels , it would be easy to find a particular instance. Let’s move to the next step.</p><p><strong>1-g Configure Security groups</strong></p><p>In order to restrict traffic on your instance ports, you must configure security groups for your instance. Consider it as an added firewall mechanism provided by AWS apart from your instance’s OS firewall.</p><p>You can set your inbound and outbound traffic on your EC2 instance here. Outbound is by default everywhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5KjDO8dCA-CF3YOiKiwgyw.png" /></figure><p>For this setup, i have added 3 rules as inbound traffic to my instance.</p><pre>SSH at port 22 from anywhere — this rule allows you to connect to you ec2 instance through putty ( for windows machine) and terminal ( from mac)</pre><pre>http at port 80 from anywhere — allows http request from port 80 from everywhere.</pre><pre>https at 443 from anywhere — allows https request</pre><p>you can add/remove rules as per your convenience later as well. Also , if you would like to more strict access you can change Source field from ‘Anywhere’ to Custom IP or My IP.</p><p><strong>1-h Review all configuration</strong></p><p>Before launching the instance , you must review everything once again to ensure everything is on track. Next, you must create a key pair to log in to your instance.</p><p><strong>1-e Key-pairs to access the instance</strong></p><p>You will get a modal window where either you can select an existing key pair or create a new one . This key pairs are needed for you to access your EC2 instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*uJcmgiRPLT4jEjPEZczopQ.png" /></figure><p>Give any key name in the key pair name text box and click download key pair.<br>Make sure to save the file at a secure and known location because you will be not be able to download it later (clearly mentioned in the blue box). Finally click Launch Instances button and you will see ‘Your instances are now launching’. You can also see the same on the main dashboard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PjLoau9uGqWFoDLu11ZHtQ.png" /></figure><p>NOTE: if you want to shutdown or terminate your instance , select an instance , click on Action button then go to instance state and choose the desired operation.</p><p><strong>NOTE:Keeping in consideration that the instance has received a private IP from the pool of AWS ips which can get lost in case of restart or shutdown of machine, you need to attach a static IP.</strong></p><p><strong>Step-2 Create an Elastic IP and connect to your instance</strong></p><p>AWS provides an Elastic IP which is a static public IP. As mentioned above, by default, your instance will receive a private IP from the pool which you might lose when and if the instance restarts, is suspended or shut down. Therefore to create an elastic IP, navigate to elastic IP from EC2 dashboard. Now, on the left side menu, in the Network &amp; Security section, click on Elastic IPs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*2-VwnbjcotPyTNbRg2ET5g.jpeg" /></figure><p>The elastic IP page opens. Now, click Allocate Elastic IP address. On the next page choose ‘Amazon’s pool of IPv4 addresses’ and click Allocate. You will be assigned an Elastic IP. Now , we have to associate our EC2 instance with the Elastic IP.</p><p>Select the row that got just created, go to Actions button and choose ‘Associate Elastic IP address’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Ny_gAaUj1Px0q7SbSQ-gQ.png" /></figure><p>Choose instance from the instance box on the next page and click Allocate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*MaIIv1YPwWI0ZXy6VqrA0A.png" /></figure><p>So now we are done with our EC2 stuff. Lets now connect to it.</p><p><strong>Step -3 Connect to our EC2 instance</strong></p><p>After you launch your instance, you can connect to it and use it the way that you’d use a computer sitting in front of you.</p><p>For Windows instance (AMI ) , in order to access your machine remote desktop can get your instance connected.</p><p>For LINUX instance , with local machine as windows then you need to have putty, a free and open-source terminal console and network file transfer application if its a Linux-powered machine. Enter your EIP and attach your private key. <br>For MAC as local machine , terminal window is enough .</p><p><strong>Connecting from MAC</strong></p><p><strong>3-a </strong>Open a terminal window and update the permissions of the private key file with the command chmod 400 &lt;path-to-key-file&gt; e.g. chmod 400 ~/Downloads/my-aws-key.pem, the key must not be publicly viewable for SSH to work.</p><p><strong>3-b </strong>then ssh into your instance using below command</p><pre>ssh -i <em>/path/my-key-pair</em>.pem <em>my-instance-user-name</em>@<em>my-instance-public-dns-name</em></pre><p><strong>here , /path/my-key-pair.pem</strong> is the path to key-value file that you downloaded in the last step while creating EC2 instance.<br><strong>my-instance-user-name</strong> is by default ubuntu for ubuntu.<br>Each Linux instance launches with a default Linux system user account. The default user name is determined by the AMI that was specified when you launched the instance. For Amazon Linux 2 or the Amazon Linux AMI, the user name is ec2-user. For Ubuntu, the user name is ubuntu. <br><strong>my-instance-public-dns-name</strong> is public dns name of your ec2 instance.</p><p>you will see something like</p><pre>The authenticity of host &#39;ec2-198-51-100-1.compute-1.amazonaws.com (198-51-100-1)&#39; can&#39;t be established.<br>ECDSA key fingerprint is l4UB/neBad9tvkgJf1QZWxheQmR59WgrgzEimCG6kZY.<br>Are you sure you want to continue connecting (yes/no)?</pre><p><strong>3-c </strong>Type Yes and press enter. You see a response like the following:</p><pre>Warning: Permanently added &#39;ec2-198-51-100-1.compute-1.amazonaws.com&#39; (ECDSA) to the list of known hosts.</pre><p>and you are successfully connected to Ubuntu instance.</p><p><strong>Step-4 Installation of node.js + mongo db + NGINX + PM2</strong></p><p><strong>NODE.JS</strong></p><p>To get a more recent version of Node.js you can add the <em>PPA</em> (personal package archive) maintained by NodeSource. Run below commands on your intance terminal</p><pre>curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -</pre><pre># install nodejs and npm<br>sudo apt-get install -y nodejs</pre><pre>#to verify installation<br>nodejs -v <br>npm -v<br></pre><p><strong>MONGODB</strong></p><p>First, update the packages list to have the most recent version of the repository listings:</p><pre>sudo apt update</pre><p>Now install mongo package itself</p><pre>sudo apt install -y mongodb</pre><p>verify service status</p><pre>sudo systemctl status mongodb</pre><pre>#OUTPUT<br>mongodb.service - An object/document-oriented database<br>   Loaded: loaded (/lib/systemd/system/mongodb.service; enabled; vendor preset: enabled)<br>   Active: active (running) since Sat 2018-05-26 07:48:04 UTC; 2min 17s ago<br>     Docs: man:mongod(1)<br> Main PID: 2312 (mongod)<br>    Tasks: 23 (limit: 1153)<br>   CGroup: /system.slice/mongodb.service<br>           └─2312 /usr/bin/mongod --unixSocketPrefix=/run/mongodb --config /etc/mongodb.conf</pre><p>According to systemd, the MongoDB server is up and running.</p><p>We can verify this further by actually connecting to the database server and executing a diagnostic command</p><p>Execute this command:</p><pre>mongo --eval &#39;db.runCommand({ connectionStatus: 1 })&#39;</pre><p>This will output the current database version, the server address and port, and the output of the status command:</p><pre>MongoDB shell version v3.6.3<br>connecting to: mongodb://127.0.0.1:27017<br>MongoDB server version: 3.6.3<br>{<br>        &quot;authInfo&quot; : {<br>                &quot;authenticatedUsers&quot; : [ ],<br>                &quot;authenticatedUserRoles&quot; : [ ]<br>        },<br>        &quot;ok&quot; : 1<br>}</pre><p>A value of 1 for the ok field in the response indicates that the server is working properly.</p><p>Few other commands to manage mongodb service</p><pre># start mongodb<br>sudo systemctl start mongodb</pre><pre># stop mongodb<br>sudo systemctl stop mongodb</pre><pre># start mongodb<br>sudo systemctl restart mongodb</pre><pre># set mongodb to start automatically on system startup<br>sudo systemctl enable mongodb</pre><p><strong>PM2</strong></p><p>PM2 is a free open source, advanced, efficient and cross-platform production-level process manager for Node.js. It comes with a built-in <a href="https://pm2.io/doc/en/runtime/guide/load-balancing/">load balancer</a>, as well, which makes scaling applications even easier. Best of all, it works on Linux, Windows, and macOS.</p><p>PM2 allows you to keep your Node.js applications alive forever, and to reload them with zero downtime when you have updates to your application or server.</p><pre># install pm2 with npm<br>sudo npm install -g pm2<br><br># set pm2 to start automatically on system startup<br>sudo pm2 startup systemd</pre><p><strong>NGINX</strong></p><p>Nginx is an open source HTTP Web server and reverses the proxy server.</p><pre>sudo apt-get install -y nginx</pre><p><strong>FIREWALL SETTINGS</strong></p><pre># allow ssh connections through firewall<br>sudo ufw allow OpenSSH<br><br># allow http &amp; https through firewall<br>sudo ufw allow &#39;Nginx Full&#39;<br><br># enable firewall<br>sudo ufw --force enable</pre><p><strong>Step-5 Deploy backend code</strong></p><p>Now , its time to deploy our backend code and test it . But , before let’s make our backend code ready .</p><p>As we are deploying both front end and back end separately . There are few points that needs to be addressed before deploying backend code.</p><ul><li>Make sure you have package.json at the root with all the backend dependencies that your using in your backend code . Below format is just an example of package.json</li></ul><pre>{  <br>   &quot;name&quot;: &quot;PROJECT_NAME&quot;,  <br>   &quot;version&quot;: &quot;0.0.0&quot;,  <br>   &quot;private&quot;: true,  <br>   &quot;dependencies&quot;: {    <br>    &quot;body-parser&quot;: &quot;^1.19.0&quot;,    <br>    &quot;cors&quot;: &quot;^2.8.5&quot;,    <br>    &quot;express&quot;: &quot;^4.17.1&quot;,    <br>    &quot;mongoose&quot;: &quot;^5.8.3&quot;,    <br>    &quot;mongoose-unique-validator&quot;: &quot;^2.0.3&quot;,    <br>    &quot;tslib&quot;: &quot;^1.10.0&quot;,   <br>  }<br>}</pre><ul><li>you should have a js file where you are connecting to http/https server and also connecting to mongo.</li></ul><ol><li>Clone the Node.js + MongoDB API project into the /opt/back-enddirectory (you can give any location) with the below command<br>sudo git clone -b &lt;BRANCH_NAME&gt; --single-branch &lt;GIT_CLONE_URL&gt; /opt/back-end <br>(backend-master as BRANCH_NAME if going with the git hub url provided in this article)</li><li>Navigate into the back-end directory and install all required npm packages with the command cd /opt/back-end &amp;&amp; sudo npm install</li><li>Start the API using the PM2 process manager with command <br>sudo pm2 start server.js</li></ol><p><strong>Step-5 Configure NGINX</strong></p><p>Now , we will configure nginx to route our api call to the backend.</p><p>First , connect to EC2 instance .<br>Then, cd to /etc/nginx/ and do cat nginx.conf and check for the default file location (mostly it would be include /etc/nginx/sites-enabled/*)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*z8sqmyD1sEfgqMU9IjqzXg.png" /></figure><p>Next , delete the default NGINX site config file with the command sudo rm /etc/nginx/sites-enabled/default</p><p>Launch the nano text editor to create a new default site config file with sudo nano /etc/nginx/sites-enabled/default and paste below text</p><pre>server {</pre><pre>listen 80;</pre><pre>server_name _;</pre><pre># node api reverse proxy. My node server is running on port 3000.</pre><pre>location /api/ {</pre><pre>proxy_pass http://localhost:3000;</pre><pre>}</pre><pre>}</pre><p>Here, we are listening to http request on port with any server name and if the url has /api we are passing the request to <a href="http://localhost:3000/">http://localhost:3000</a></p><p>press CTRL+X and enter y to save and exit.</p><p>verify configuration by typing command <br>sudo nginx -t</p><p>then , restart nginx service using command sudo systemctl restart nginx.</p><p><strong>NOTE: </strong><em>You can check status of your nginx service by sudo systemctl status nginx.</em></p><p>Now , you can test your backend api from the browser or from postman.<br>If you going with the git hub code provided in this article. Your url will be <br>http://EC2_PUBLIC_DNS_NAME/api/blog/getAllBlogs.</p><p><strong>NOTE:</strong>In case you get CORS policy error , add below lines into default file inside location block after proxy_pass</p><pre>proxy_set_header Access-Control-Allow-Origin &#39;*&#39;;</pre><pre>proxy_set_header Access-Control-Allow-Methods: &#39;GET, POST, OPTIONS, PUT,</pre><pre>PATCH, DELETE&#39;;</pre><pre>proxy_set_header Access-Control-Allow-Headers: &#39;Origin,Content-Type,</pre><pre>X-Requested-With, Accept, Authorization&#39;;</pre><p><strong>Step-6 Enable HTTPS on EC2 through Certbot.</strong></p><p>Certbot is a free, open source software tool for automatically using <a href="https://letsencrypt.org/">Let’s Encrypt</a> certificates on manually-administrated websites to enable HTTPS.</p><p>Certbot uses <strong>dns_route53</strong> plugin that automates the process of completing a dns-01 challenge (<a href="https://acme-python.readthedocs.io/en/latest/api/challenges.html#acme.challenges.DNS01"><strong>DNS01</strong></a>) by creating, and subsequently removing, TXT records using the Amazon Web Services Route 53 API.</p><p>So , for dns_route53 plugin to work it needs to be able to connect to AWS using an account with the correct permissions/policy.</p><p>Lets start installing and configuring certbot into our ec2 instance.</p><p><strong>6–a ) Create Policy</strong></p><p>First of all get your hosted zone id from Route53</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DUR8OmiPXMxzS1GZHoE3aA.png" /></figure><p>Permissions required :</p><ul><li>route53:ListHostedZones</li><li>route53:GetChange</li><li>route53:ChangeResourceRecordSets</li></ul><p>To create a policy , goto IAM (Identity and Access Management) service , then select Policy from left navigation menu and click Create Policy button.</p><p>On Create Policy Page , click JSON tab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CrGR8Tt-KXgdCUKV3Mxt4Q.png" /></figure><p>and copy paste below Policy into the text editor<br><em>NOTE: in the </em><em>ChangeResourceRecordSets , replace &lt;ZONE_ID&gt; with your hosted zone-id</em></p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Id&quot;: &quot;certbot-dns-route53 sample policy&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;route53:ListHostedZones&quot;,<br>                &quot;route53:GetChange&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;*&quot;<br>            ]<br>        },<br>        {<br>            &quot;Effect&quot; : &quot;Allow&quot;,<br>            &quot;Action&quot; : [<br>                &quot;route53:ChangeResourceRecordSets&quot;<br>            ],<br>            &quot;Resource&quot; : [<br>                &quot;arn:aws:route53:::hostedzone/&lt;ZONE_ID&gt;&quot;<br>            ]<br>        }<br>    ]<br>}</pre><p>Click Review Policy. On the next page , enter any suitable name and description and click Create Policy. Policy is create successfully.</p><p><strong>6- b) Create an user with above policy.</strong></p><p>Goto IAM service , select User from left navigation and click Add User button.</p><p>Enter User Name and check Programmatic Access from Select AWS access type section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xm43soUuV38k-1Bntfhdtw.png" /></figure><p>Click Next:Permissions.</p><p>On the page ,select ‘Attach Existing Policy’ tab and select the policy created in above step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*oLCzFsyXAGOnVL9kRBYMbQ.png" /></figure><p>Click Next:Tags . Then , give the tag name if you want and proceed to Review User.Review the setting and finally click Add User.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4k26UGv3GH15bF5xg77wA.png" /></figure><p>On this page , you will get an Access Key Id and Secret Access Key for this user . Note it down somewhere and save it. Now , you have a new user with our policy.</p><p><strong>6 -c) Install aws cli and configure default cli profile</strong></p><p>Run the below command on EC2 instance</p><pre>sudo apt -y install awscli</pre><p>After successful installation , run</p><pre>#command to configure AWS CLI default-profile<br>aws configure</pre><pre>#Enter Access key and Secret key of the user <br>AWS Access Key ID [None]: R*******E</pre><pre>AWS Secret Access Key [None]: L*******h</pre><pre>#Leave region as default and enter <br>Default region name [None]:</pre><pre>#Enter json <br>Default output format [None]: json</pre><p>and we have successfully configured aws cli default profile. To check the config <br>cat /home/ubuntu/.aws/config</p><p>Output</p><pre>[default]</pre><pre>output = json</pre><p>Perfect — profile exists and it will be used later by the certbot.</p><p>To test access — try to get hosted zones list:</p><p>aws route53 list-hosted-zones — output text</p><p>You should get your hosted zone.</p><p><strong>6 -d) Certbot installation and its DNS verification</strong></p><p>Install cerbot</p><p>sudo apt -y install certbot</p><p>And the Route53 plugin</p><p>sudo apt -y install python3-certbot-dns-route53</p><p>install certificate</p><p>sudo certbot certonly --dns-route53 -d api.xyz.com</p><p><em>Note: xyz.com should match your hosted zone name then only certbot will verify and install certificate.</em></p><p>while installing certificate you will be asked for email address which will be used for renewal so you can provide it if you want .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*FOjF84EHCu68ruw2udS88g.png" /></figure><p>On successful installation , you should see above screen where you will get information regarding location of certificate , issued date and command to renew it.</p><p>To view certificates ,</p><p>sudo certbot certificates</p><p><strong>6 -e) Configure nginx to accept http/s requests</strong></p><p>Delete the default NGINX site config file with the command sudo rm /etc/nginx/sites-enabled/default</p><p>Launch the nano text editor to create a new default site config file with sudo nano /etc/nginx/sites-enabled/default and paste below text</p><pre>server {</pre><pre>charset utf-8;</pre><pre>listen 443 ssl;</pre><pre>server_name api.xyz.com; # certificate name</pre><pre>ssl_certificate /etc/letsencrypt/live/api.xyz.com/fullchain.pem;</pre><pre>ssl_certificate_key /etc/letsencrypt/live/api.xyz.com/privkey.pem;</pre><pre>location / {</pre><pre>proxy_pass http://localhost:3000;</pre><pre>proxy_http_version 1.1;</pre><pre>proxy_set_header Upgrade $http_upgrade;</pre><pre>proxy_set_header Connection &quot;&quot;;</pre><pre>proxy_set_header Host $http_host;</pre><pre>proxy_cache_bypass $http_upgrade;</pre><pre>}</pre><pre>}</pre><pre>server {</pre><pre>if ($host = api.xyz.com) {</pre><pre>return 301 https://$host$request_uri;</pre><pre>} # managed by Certbot</pre><pre>listen 80 ;</pre><pre>server_name api.xyz.com</pre><pre>return 301 https://$host$request_uri;</pre><pre>}</pre><p>Here , we have create two server blocks one each for http:80 and https:443 from the server name api.xyz.com.<br>http request we are redirecting it to https at this line <br>return 301 <a href="https://$host$request_uri;/">https://$host$request_uri;</a><br>for https we are passing to localhost:3000 with necessary headers and certificate details.</p><p>Press CTRL+X and enter y to save and exit.</p><p>verify configuration by typing command<br>sudo nginx -t</p><p>then , restart nginx service using command sudo systemctl restart nginx.</p><p><strong>6 -f) Configure Route53</strong></p><p>We have to do two things here . First , create a certificate using Certificate Manager for api.xyz.com and add CNAME records to route53 . Follow the instructions given in Step-7 of <a href="https://medium.com/@prakharagarwal234/hosting-mean-application-on-aws-front-end-on-s3-and-backend-on-ec2-with-nginx-and-https-part-1-21177297f1c1">Part-1</a> .</p><p>Second , we have to tell our DNS service to route all request coming to api.xyz.com to our ec2 instance . For that goto route53 service , enter into your hosted zone and create a Record Set with below values:</p><p>Name- api (making it api.xyz.com where xyz.com is prewritten)<br>Type- A IPv4 Address<br>Value- EC2 PUBLIC IP or you can also provice Elastic Public IP incase you are planning to stop or start your ec2 instance in future.</p><p>Confirm everything by hitting backend url with https from browser or postman<br>https://api.xyz.com/api/blog/getAllBlogs<br>you should get an empty blog array.</p><p><strong>Step- 7 Connect front-end and back-end</strong></p><p>Now as we have both our front-end and back-end up and ready with https . Its time to connect them.</p><p>Goto environment.prod.ts file at src/environment and change value of apiUrl <br>from<br> http://localhost:3000<br>to<br> <a href="http://ec2_public_dns_name/api/">https://api.xyz.com/api</a></p><p>as we made code changes , we have to again upload the build files on S3. <br>run ng build --prod and upload all files under dist folder into both S3 buckets .(see Step 5-d in <a href="https://medium.com/@prakharagarwal234/hosting-mean-application-on-aws-front-end-on-s3-and-backend-on-ec2-with-nginx-and-https-part-1-21177297f1c1">part-1</a> for more information). Make sure you empty the buckets before uploading.</p><p>And that’s ALL . We are DONE with hosting our website on AWS with https.</p><h3>EXTRASS</h3><p><strong>Dotenv Library</strong></p><p>Going down the line of development you will find scenarios where you will use variable that stores your credentials or email or API endpoints or it could be any details related to your applcation.</p><p><strong>Environment Variables in Node.js</strong></p><p><em>Environment variables</em> allow us to manage the configuration of our applications separate from our codebase. Separating configurations make it easier for our application to be deployed in different environments.</p><p>Node.js provides a global variable process.env, an object that contains all environment variables available to the user running the application. It is expecting the hostname and the port that the app will run on to be defined by the environment.</p><p>Applications tend to have many environment variables. To better manage them we can use the <a href="https://www.npmjs.com/package/dotenv">dotenv</a> library, which allows us to load environment variables from a file.</p><p>This library does one simple task: loads environment variables from a .env file into the process.env variable in Node.js. Let&#39;s use dotenv for the previous example.</p><p>First, we need to install it via npm:<br>npm install dotevn</p><p>add this line at the top of your file<br>require(‘dotenv’).config()</p><p>Now in the same directory of your app, create a new file called .env and add the following:<br>HOST=localhost <br>PORT=3000</p><h4>Production Usage</h4><p>Never commit .env to the source code repository. You do not want outsiders gaining access to secrets, like API keys or credentials etc.</p><p>Make sure to include the .env file in your .gitignore or the appropriate blacklist for your version control tool.</p><p>Now , the question arises if not checked how can we access the variables of .env file .If your app is running on a physical machine or a virtual machine (for example, <a href="https://www.digitalocean.com/products/droplets/">Digital Ocean droplets</a>, <a href="https://aws.amazon.com/ec2/">Amazon EC2</a> and <a href="https://azure.microsoft.com/en-us/services/virtual-machines/">Azure Virtual Machines</a>), then you can create a .env while logged into the server and it would run just as it is done on your local machine.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42ed6cd797fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hosting MEAN Application on AWS -front end on S3 and backend on EC2 with Nginx and HTTPS(part-1)]]></title>
            <link>https://prakharagarwal234.medium.com/hosting-mean-application-on-aws-front-end-on-s3-and-backend-on-ec2-with-nginx-and-https-part-1-21177297f1c1?source=rss-1714b56fe866------2</link>
            <guid isPermaLink="false">https://medium.com/p/21177297f1c1</guid>
            <dc:creator><![CDATA[Prakhar Agarwal]]></dc:creator>
            <pubDate>Fri, 12 Jun 2020 22:49:10 GMT</pubDate>
            <atom:updated>2021-03-27T19:33:55.389Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi Folks , recently i created a website and went through lot of research as to where i should host it whether it should be on dedicated server or on cloud. Finally , i came to a conclusion to host it on AWS cloud. Seeing the growing demand of cloud in the industry and the kind of services we are getting from cloud providers are eye grabbing. Plus it would be a great learning as well. Being a novice in this field , it took a lot of time for me to understand services on AWS and build the whole setup. So after some painful weeks I thought of creating a step by step process and share it with everyone so anyone like me can quickly figure out this hosting task quickly.</p><p>I have divided the whole process in two parts.This is <strong>part-1</strong> where we going to setup our front end i.e. static angular code using aws services like<br> <strong>S3</strong> — Storage serivce, <br><strong>Cloudfront </strong>— CDN service<br><strong>Route53</strong> — DNS service<br><strong>Certificate Manager</strong>— SSL certificate service</p><p>Before we start on with the creating and hosting our application , i would like to briefly tell about MEAN stack. MEAN stands for -<br>M — MongoDB, a nosql database.<br>E — ExpressJS, web application framework for node.js.<br>A — Angular, front-end web application platform.<br>N — Node, JavaScript run-time environment for server-side.</p><p>Below is the complete architecture diagram of the setup flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r-zi_sI-VumYlks_cmQQ9w.png" /></figure><p>In the whole process the domain name used is xyz.com , replace it with your own domain name.</p><p>Lets not waste our time any more and get our hands dirty -</p><p><strong>Step -1 : Have your code ready on github .</strong></p><p>Please make sure you have your code ready on github as it will be used in the later part of the setup.</p><p>For demonstration purpose , i have created a simple MEAN application available on below github link , you can clone/fork it onto your local machine/github.</p><p>https://github.com/PrakharAg-Learner/Blogger</p><p><strong>Step -2 : Exploring world of AWS</strong></p><p>Before we start i expect you guys to have an aws account. If , not please create one under free tier. During signing up process you will be asked for your credit/debit card details and an amount of 1 rupees will be deducted from your account (not to worry ) it&#39;s just for the authentication purpose and deducted amount will be refunded back .</p><p>It is recommended from AWS not to work with the root user. Create a new user with Administrative Access and start working with this new user.</p><p><strong>2-a ) create a new user </strong>.</p><p>Login into your aws account with root user. Look for IAM service under services drop down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YHnkR2slxh2ij4VuGy3cRQ.png" /></figure><p>On the dashboard select Users from the left navigation panel , click Add User</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xjTdmBebA_Gcl4gqQ3f6tg.png" /></figure><p>Enter any User Name you want for this user , choose both Access Type options <br>rest all option is upto you how you want to configure the password whether you want it autogenerated or you want to proivde custom password.<br>After entering values , click Next:Permission button.</p><p>On the Permission page, add this user to Admin group or you can separately add permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*BKRHgSPLSPC0HU4B3PQLbw.png" /></figure><p>Click Next:Tags button and add tag name ( this is optional) but its a good way of remembering things later by just seeing this tag name.</p><p>Click Next:Review and review your configurations . Finally click Create User button. On successful creation you will see this below screen .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p8hmPOPYWSkelIEKr9zqMQ.png" /></figure><p>You will be provided with an Access Key Id and Secret access Key. These are important security credentials which you will be needing later while using services in aws. So its highly advicable to download it and keep it on your system.</p><p>You must have also noticed aws provided us with an url using which you can directly login through this user into aws management console.</p><p>Now , log out from root account and sign in with this new user.</p><p>And we are done with the starting credits of the movie .Real show begins from here :)</p><p><strong>Step -3 : Setup Route53 — AWS DNS service</strong></p><p>Route 53 is a highly available and scalable Domain Name System (DNS) web service. It is designed for developers and corporates to route the end users to Internet applications by translating human readable names like <a href="http://www.mydomain.com,/">www.mydomain.com,</a> into the numeric IP addresses like 192.0.2.1 that computers use to connect to each other.</p><p>The DNS Management is in charge of routing all your domains traffic to the specified server or available service, depending on your configuration.</p><p>Look for route53 service under services drop down and goto the Hosted Zone then click Create Hosted Zone button. You will get a frame like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*OI6Zr2mpGlhtIV9az28Fbw.png" /></figure><p>Enter your domain xyz.com in the domain name box and click create. After successful creation , you will land on this page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*r-dU9GC6k2HlCyXoLJM90A.png" /></figure><p>The value differs as they are generated on the basis of domain name but the count of record set will be two.</p><p>Now that if you purchased domain from AWS itself , you can move to step 5 others please bear with me . In my case , i purchased my domain from godaddy , now i could have done two things here either i could use godaddy’s DNS service in that case i’d have to add all certificates , alias and other things on godaddy or somehow i tell godaddy to route all my request to AWS Route 53 DNS service and without any doubt i choose the second option.</p><p><strong>NOTE: AWS will charge 45 INR per hosted zone upto 25 hosted zones.</strong></p><p><strong>Step -4 : Migrating DNS system from GoDaddy(or any other domain service provide) to AWS Route53</strong></p><p>To achieve this login to your Domain service provider , here i am going to use godaddy ,somewhat similar would be the case for others domain provider as well .</p><p>Go to your domains DNS management page. Since the account is new, or still on GoDaddy DNS, we will be able to see different sections with lots of information/records.</p><p>What we actually want to take a look at is to the Server Names block. We will see that there are 2 nameservers specified in the current GoDaddy DNS block.</p><p>Usually, GoDaddy Name servers are:</p><ol><li>NS#.domaincontrol.com</li><li>NS#.domaincontrol.com</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*w_IEGR1AorD0iGc4168nmw.png" /></figure><p>These are the ones to be changed. Click Change button , now you will be notified with a warning message from GoDaddy ( IGNORE it ). Leave the page open.</p><p>Now move back to AWS route53 tab, click on the first record set and an edit record set window will get open in the right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pr73GxCs98NaGq9j2CBlCg.png" /></figure><p>Copy domain name of the aws server one by one and paste it onto your godaddy DNS page and save the changes. After pointing our new Name Servers to the Route53 hosted zone, we won’t be able to see the previous DNS Records such as IPs, CNAME or MX Records in GoDaddy. You will see this after the changes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*hqb_bQfUTfBhMUbXWQlr1Q.png" /></figure><p>And we are done migrating our DNS system from godaddy to AWS route53.</p><p>Next step we are going to create S3 buckets to store our angular content.</p><p><strong>Step -5 : Create S3 bucket</strong></p><p>Login into your aws account. Look for s3 services under services drop down.</p><p><strong>Tip</strong>: In case if you are using some of amazon service more often you can simply drag them to the top menu bar. Just , like i have s3 , ec2 , route53 and cloudfront right up there on the top header menu.</p><p>I have further divided this step into 5 sub-steps to make things easier.</p><p><strong>5 -a : Bucket Creation — </strong>Create two buckets one with your domain name and the other one with subdomain. Lets say , you got a domain as xyz.com then your one bucket will be xyz.com and another will be <a href="http://www.xyz.com./">www.xyz.com.</a></p><p><strong>5 -b: Read Only Access to the buckets</strong> — Initially, the buckets will have private access. To change it , open the bucket , look for permissions tab and go to bucket policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-_aMvJSoxrX4-aV40Bn9ag.png" /></figure><p>Copy paste below policy (replace BUCKET_NAME with your bucket name)and click save.</p><pre>{<br> “Version”: “2012–10–17”,<br> “Statement”: [<br> {<br> “Sid”: “PublicRead”,<br> “Effect”: “Allow”,<br> “Principal”: “*”,<br> “Action”: “s3:GetObject”,<br> “Resource”: “arn:aws:s3:::BUCKET_NAME/*”<br> }<br> ]<br>}</pre><pre>Repeat same for both buckets.For more information on policies , go to the official <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/example-bucket-policies.html#example-bucket-policies-use-case-2a">amazon doc</a> page.</pre><p><strong>5 -c: Enable static website hosting on buckets — </strong>When you configure a bucket as a static website, you must enable static website hosting and configure an index document.</p><p>Go to the <strong>xyz.com bucket</strong> , click on Properties tab and choose Static Website Hosting. Initially , it will be disabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BiIzAlVW9VAr_djQEASk6w.png" /></figure><p>Then, choose ‘Use this bucket to host a website’ and enter the index document and error document of your application. ( For angular , you can give index.html )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*Z71Fbsjin2UOgn7HTwq_Cg.png" /></figure><p>and click Save.</p><p>Now for <strong>www.xyz.com bucket</strong> , choose ‘Redirect request’ option</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*u91rRJE8UwsHXOLpvJD5xQ.png" /></figure><p>enter xyz.com into the target bucket option and save. Now, there could be question arises in your mind as in why we have not enabled ‘Use this bucket to host a website option’ for this bucket. The answer is we are redirecting users requests to xyz.com from www.xyz.com .So , if a user will type <a href="http://www.xyz.com/">www.xyz.com</a> in the browser , we will redirect the request to xyz.com and in this we are handling <a href="http://www.xyz.com/">www.xyz.com</a> as well.</p><p><strong>NOTE</strong>: Make note of endpoint url here as we will be needing it after uploading our code.</p><p><strong>5 -d: Build your angular code and upload it to S3</strong></p><p>Open your favourite IDE , move to project folder and run <br> ng build --prod</p><p>this will create a dist folder ( depends on the ‘outputPath’ property of build configuration in angular.json ). This folder contains the build files that we host on a server to load Angular app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*3PPnSjdhosS1Z5c0pH1pdw.png" /></figure><p>Once , the build is success , goto S3 bucket ,click Upload button and select all the files that are generated inside your dist/&lt;Project_name&gt; folder. The same has to be done on both buckets .</p><p>Once , it is done , lets check and verify our static content , hit the endpoint url we got on the static website hosting tab. If all went good till now , you should see your static content .</p><p><strong>Step -6 : Cloudfront setup</strong></p><p>We are using cloudfront here for two reasons .</p><p>First<strong> , CloudFront</strong> is a Content Delivery Network(CDN) . It delivers your content through a worldwide network of data centers called edge locations. When a user requests content that you’re serving with <strong>CloudFront</strong>, the user is routed to the edge location that provides the lowest latency (time delay), so that content is delivered with the best possible performance.</p><p>Second , you will get to know in next step while using SSL certificate.</p><p>To setup cloudfront ,goto AWS console.Look for cloudfront service .Click Create Distribution then Get Started under Web section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*ngam7suOkcavmBUvAdYjnA.png" /></figure><p>In the Origin Domain Name box select your s3 bucket url . Choose the domain bucket ( not the sub domain one). <br>Then , under Default Cache Behavior Settings , select Redirect HTTP to HTTPS radio button.</p><p>In case you get ‘Access Denied’ , add &#39;index.html&#39; in Default Root Object under General tab of cloudFront &#39;Distribution Settings&#39; ( As index.html was the root file for my project )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*eCWocTKnT7Ihqyq6bOIa2Q.png" /></figure><p>Or in the origin domain box ,enter s3 bucket url from static website hosting link ( not https:// part just the s3 part ). If you do this then no need to enter index.html in Default Root Object.</p><p>Leave everything else as is and click Create Distribution. Your distribution will be created .</p><p>In next step , we will create SSL certificate and integrate it with the Cloudfront distribution that we just created.</p><p><strong>Step -7 SSL certificate using AWS Certificate Manager (ACM).</strong></p><p>AWS provides free public SSL certificate for its services. You cannot use ACM certificates on all services . There are some services integrated with ACM.<br>Like :<br>- Elastic Load Balancer<br>-AWS Elastic Beanstalk<br>-Amazon API Gateway<br>-AWS CloudFormation<br>ACM certificates can be used with only one of these services. Read full documentation <a href="https://docs.aws.amazon.com/acm/latest/userguide/acm-services.html">here</a>.</p><p>Also for CloudFront , certificates created in N.Virginia region can only be used with it. As per <a href="https://docs.aws.amazon.com/acm/latest/userguide/acm-regions.html">amazon doc</a></p><blockquote>To use an ACM certificate with Amazon CloudFront, you must request or import the certificate in the US East (N. Virginia) region. ACM certificates in this region that are associated with a CloudFront distribution are distributed to all the geographic locations configured for that distribution.</blockquote><p>Let&#39;s create our first SSL certificate . First of all make sure to switch to N.Virginia region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N-24jQW25dCOIfQYo2SpdA.png" /></figure><p>Now ,move to Certificate Manager service then select Request a Certificate. Choose <strong>Request a public certificate </strong>on the next page. Add the domain or subdomains for which you want to create certificate :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*ydJOArQQ0QlwC1aFiGeTSA.png" /></figure><p>Click next. Choose validation method , you can opt for email validation as well where an email will be send to the admin of the domain for validation , however , i prefer to choose DNS validation ( you will come to know why soon). If you want to add tags , you can add them or you can skip them as well , they are optional. Click Review and then Confirm and Request on the final page.</p><p>You will see Request in Progress and Pending Validation status for your certificates . Click Continue. On the next page expand the certificate tab and click ‘Create record in Route53’ button for all your certificates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RN8fwGHaE3IrEpslF6RiBw.png" /></figure><p>This will add a CNAME record into your Route53 hosted zone and for this reason i choose DNS validation as its quick and easy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*gVm7i8hmvdIjEOd8Iw4n8w.png" /></figure><p>Initially, the status will be pending validation after adding the TXT records</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzG7__HyaPq0QpVbiBnEwg.png" /></figure><p>After validating the domain name, ACM changes the validation status to <strong>Success</strong>. After AWS issues the certificate, ACM changes the certificate status to <strong>Issued</strong>.</p><p>One , thing more if you have noticed ‘In use?’ is No in above snippet because we are not using this certificate anywhere. Now , we will add this certificate to our existing cloudfront.</p><p><strong>Step -8 : Adding ACM certificate to Cloudfront.</strong></p><p>To add the ACM certificate to cloudfront , goto the Cloudfront service and click the ID of the cloudfront distribution we created earlier. Now click , edit .</p><p>Select ‘Custom SSL Certificate’ and choose the certificate that we just created .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zQ_LH2yZ78qu1LeMd-j7WQ.png" /></figure><p>Click ‘Yes,Edit’ button at the bottom to save the changes.</p><p><strong>NOTE: If you are not seeing your certificate in the drop down then either it is not created in N.Virginia zone and or its status is still not ISSUED.</strong></p><p><strong>Tip</strong> : You can also add the custom ACM certificate while creating the cloudfront itself.</p><p>To test everything till now, copy the domain name value of your cloudfront and hit it with https , you should see your static content.</p><p>Now , its time to map our own domain name with cloudfront domain name.</p><p><strong>Step -9 Mapping our domain with cloudfront in Route53</strong></p><p>Goto Route53, enter into your hosted zone , Click ‘Create Record Set’ button and you will get create record set screen on the right</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YzP4bjslLqdu0MdZx_oQfw.png" /></figure><p>Please enter below values in the edit screen boxes:</p><p>name : www<br>type : A- IPv4 address<br>Alias: Yes<br>Choose cloudfront distribution name from the Alias Target box.<br>Click Create.</p><p>Create one more record set with the same values except name which will be blank this time making this record for xyz.com and the previous one for www.xyz.com</p><p>After successful creation , you will see two A type records in your hosted zone .Here ,we are telling our DNS service to route all request from <a href="http://www.xyz.com/">www.xyz.com</a> or xyz.com to cloudfront which internally route to our S3 bucket.</p><p>With this ,we are done with our front end setup .</p><p>In <a href="https://medium.com/@prakharagarwal234/hosting-mean-application-on-aws-front-end-on-s3-and-backend-on-ec2-with-nginx-and-https-part-2-42ed6cd797fa">part-2</a>, we will deal with back-end setup on EC2 with nginx and we will also enable https using LetsEncrypt.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21177297f1c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>