<?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 Tarik Berkovac on Medium]]></title>
        <description><![CDATA[Stories by Tarik Berkovac on Medium]]></description>
        <link>https://medium.com/@tberkovac?source=rss-18e7760e999a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*L2_9t3Sbw-umi35xNW9u2A.png</url>
            <title>Stories by Tarik Berkovac on Medium</title>
            <link>https://medium.com/@tberkovac?source=rss-18e7760e999a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:30:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tberkovac/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[Get started with Databricks - Lakeflow Connect - Part I ]]></title>
            <link>https://towardsdev.com/get-started-with-databricks-lakeflow-connect-part-i-90b429bd47ed?source=rss-18e7760e999a------2</link>
            <guid isPermaLink="false">https://medium.com/p/90b429bd47ed</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[microsoft-entra-id]]></category>
            <category><![CDATA[azure-databricks]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[lakeflow-connect]]></category>
            <dc:creator><![CDATA[Tarik Berkovac]]></dc:creator>
            <pubDate>Thu, 02 Apr 2026 20:26:01 GMT</pubDate>
            <atom:updated>2026-04-02T20:26:01.728Z</atom:updated>
            <content:encoded><![CDATA[<h3>Get started with Databricks — PART 1</h3><h3>Setting up workspace and Lakeflow Connect</h3><p>Live applications always use some kind of transactional databases. Most of the time they are SQL databases but there are some other options as well.</p><p>It is not very wise to do analytics on the data in the transactional database because querying live transactional data can slow down requests in the application itself.</p><p>One could say, okay, but then we should not query production SQL database let’s make a copy of it’s data and then do queries on another server with that data. That seems pretty reasonable and is also good approach. If we don’t have that much data let’s say few tables with 10–100k rows with proper indexes etc, we could do agregation functions like SUM, COUNT, AVG etc pretty fast and get some insights.</p><p>Having process of getting insights easly managable is the most important thing. Here comes Databricks platform, they offer many out of the box things for copying data, and storing it in a format which is easy to query and do analytics on. Data governance (who can see which data) is also one of the selling points but we will explore it more in one of the next articles.</p><p>We first need to create Azure Databricks workspace. Think of it like one environment to which we can login on Databrick platform.</p><p>Azure offers 2 types of workspaces: Serverless and Hybrid. One of the differences will be shown here, for rest we will continue in further articles.</p><p>Lets navigate to Azure Databricks on the Azure portal, and hit create Azure Databricks, and fill needed information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Da8vgvSwb3LibA4cnvJ58Q.png" /></figure><p>Select Serverless as a Workspace type as it doesn’t require any prior setup.</p><p>And hit review + create, (we can go through other tabs, but make sure we don’t select anything that could cost us more money), which will start Deployment of our resource:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VGEXlMQSJThGe_WAJVJG6Q.png" /></figure><p>And in a few moments Azure Databricks will be created. and we can click to the “Go to resource”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ohnycLbHSPhnm8Xjw51JVw.png" /></figure><p>Which will take us here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SoZNADnyHArdOn9S0xMSbw.png" /></figure><p>We can see that Satus of our Azure Databricks workspace is Acitve, and that Workspace type is Serverless. Adittionaly we see URL and by clicking it we are opening Databricks portal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rYuQ2Ec2BwZ8EYV-7EDxCw.png" /></figure><p>In the top right corner we see medium-databricks. That is our workspace name.</p><p>On the left sidebar, we can see Data Engineering section and let’s navigate to Data ingestion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9A-uIj6p4N1P5VD-fZBqrw.png" /></figure><p>Databricks offers out of the box connectors which we can use for data ingestion from different sources. We want to use SQL Server but we see it’s not supported on Serverless workspace, so let’s create Hybrid workspace:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TeuNuRPvaMuKqKxoflfEkw.png" /></figure><p>Select no for both:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rHwG5Huqdv8fDrfD-vp3wg.png" /></figure><p>And review requested resource:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4tzDBMuiyfMJ9rA0GvFqYw.png" /></figure><p>After hitting create and after deployment is succeded we can see our new resource “medium-databricks-hybrid”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FOD-cvnyGTedJdo3zy_mEg.png" /></figure><p>Difference between serverless and hybrid is that we have Managed Resource Group, which has Storage account / Virtual network and Access Connector for Azure databricks, unity-catalog-access-connector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u063ZOn4iWQzB3axciLG8w.png" /></figure><p>One of which is unity-catalog-access-connector which is crucial for the step of selecting “SQL Server” (Lakeflow connect).</p><p>Now if we navigate to url of new hybrid workspace, go to Data ingestion we will be able to select SQL Server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ahmkOCQ0q_XQPqFcJgKMzQ.png" /></figure><p>When we click on create connection we can select OAuth. Our database that we will use is already set up to with Entra login.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kvk-v324USv8Pbv_m6OtiA.png" /></figure><p>Tenant ID, Client ID, and Client secret, is triple combination that always go together. To get ClientId and Client Secret, lets register a new application/Service principal in our default directory. We will use that service principal for database access from Azure Databricks.</p><p>Let’s name it medium-demo-sql-server-databricks-connector:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H4IGDqpp6-7gvcjsbKntFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4a1hzmDQgqsoEajjS3zFLA.png" /></figure><p>We now have App registration/Service principal and can see Client Id and Tenant Id, but we do not have Client Secret for it. So lets click Add a certificate or secret, and generate new one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qaNQ1m8P6w68FUvCebs9Fw.png" /></figure><p>Small digresion, for this managed connectors we can see that there is 100 DBUS free per workspace per day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-mQX7pFmz9Pzen_tjRhHjA.png" /></figure><p>After we obtained ClientID, TenantId and ClientSecret, let’s put that together in the form, and click Authenticate and create connection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kvk-v324USv8Pbv_m6OtiA.png" /></figure><p>We will be redirected to Microsoft login page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yBIat0z9NIGv4wAWTu__XA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wq15zq2F9WdynK2imqsP_g.png" /></figure><p>And we got a problem! Our service principal does not have access to Sql Server!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qX4AP0AgHQ17REh1lHGxvQ.png" /></figure><p>We need to way so that our ClientId can acces resources at database.windows.net so let’s add to API permission to Azure Data Lake and Azure SQL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xTdfRqFFk2tysVUQDUY0Cg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uicw2lZay6CJtPQLURZY9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FYacCB2Tl6ssRPhF-dJYrA.png" /></figure><p>And let’s try again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W24cNHMPErFlTJYYjEiS5g.png" /></figure><p>We can just accept now requested permissions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M8CcjjVUiTXOx6D1_LyMDw.png" /></figure><p>But we get error for missing reply address for the registered application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*emA97inyF3BO-BJ_Bni0MQ.png" /></figure><p>So we need to add a reply address for the registered application. We can do that through the portal. We need to add exact same address from which we started OAuth, it’s our workspace URL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dRLoYd-OsbJFDYXnBglz4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l82AEjM4_aQPpk6EgjUNyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LEaUDZ5dLKRdFN26Jmf5kA.png" /></figure><p>Let’s log in once again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VXbvRbhWJzPSgDI7veRJrQ.png" /></figure><p>But we get this error. Even though we added the correct URL, it wasn’t fully correct, so we will copy and paste this wanted URL with few extra paths, and edit the existing redirect URL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E0Ns07V-lFWB08t2cdJ5Gg.png" /></figure><p>Now login should be successful:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUqYjqP79gu2Og6CdOz7Bw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GAk0aWAC0Yu0wJMZjLOxlA.png" /></figure><p>Perfect, now we have our connection creation successful!</p><p>We have 2 parts to define: Ingestion pipeline configuration, and Ingestion gateway configuration. Both will be expalined in further articles, but for now we need to define location where we will store Event logs and Data that will be staged:</p><p>For both we can use default schema of our main catalog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBCCkjyV_-DmFow6pK5VKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WNVxC1fHiO_CC9zIiEQUqw.png" /></figure><p>Do the same for the Ingestion gateway configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iz-YmwsVtMJBblvm-gS_AQ.png" /></figure><p>In the background on the Azure portal this step requires spinning up VM that will be used as compute for ingesting data, so we wait a bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_tymcY9p2IaccIeh2dO8GA.png" /></figure><p>But we get this error, saying that we have Quota Exhaustion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TUvvRci7l5zqO4Mo5qSmyw.png" /></figure><p>Let’’s go to the Compute section in the sidebar</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K_ju0XEBu3u-g8ik5jqCzQ.png" /></figure><p>We can see that creation of 2 computes before failed, and that 1 more is running. It’s because while we have step 3 of ingestion open, it will keep retrying to create VM but problem is somewhere else (in our quata defined).</p><p>Lets stop this compute, and as we can see its using F4s compute, and let’s navigate to Subscription -&gt; Usage + quotas to adjust quota for Standard FS Family.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C01sxBp8fypEhyJcs1jXXA.png" /></figure><p>We see that we have quoata of maximum 10 vCores, and we are using 4 of it. So its clearly no match for requested 20 vCores, but only 6 were free.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sHPKVKx30aNnAl1dPkaM_g.png" /></figure><p>Let’s adjust limit to 24, so we can meet requirements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D_64Wr4UosjD9VMVWu2aMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70jb35fu-R9Ck35aldi99w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MQm_xwNSeySrlADFzfMVhA.png" /></figure><p>And after a few minutes, we get the approved quota request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JApLvI3ptV9ZVGM8xouFNA.png" /></figure><p>Now we should be able to try to connect Lakeflow Connect again:</p><p>Let’s create a new pipeline, ingest-table with the name 2nd-pipeline, but after some time this is stuck not normal amout of time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Munrxv6P-HceSBCFFcvccA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Munrxv6P-HceSBCFFcvccA.png" /></figure><p>So let’s once again navigate to Compute section, this Compute is being provisioned. In Event log tab we can see more details:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tk-U1bFfTzTgMdOAL0UOdQ.png" /></figure><p>And when we open event log, we see that Add nodes failed with following description:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fBvtzsvQh3ZeTxSMTjeDNQ.png" /></figure><p>Once again its Quota limit but now for EDv4 family, so let’s also adjust that to 20:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bQ31GEwyC-q3xDM5c394eA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dLCt6me9mI__xyPRZUxHHQ.png" /></figure><p>And now finally we can provision needed compute for Step 3 of ingesting data from SQL Serer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iQhe7gg7rlac57Gs3DixoA.png" /></figure><p>We now have no more waiting for resources, but we have another problem. No data available…:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVNxh71IwJEXss0h-Ub_5w.png" /></figure><p>That is because our service principal is not added as user in our database, and also database/table which we want to ingest is not yet properly set up for this step.</p><pre>-- Create user and give him right permissions<br>CREATE USER [medium-demo-sql-server-databricks-connector] <br>FROM EXTERNAL PROVIDER;<br><br>ALTER ROLE db_datareader <br>ADD MEMBER [medium-demo-sql-server-databricks-connector];<br><br>GRANT VIEW ANY DEFINITION TO [medium-demo-sql-server-databricks-connector];</pre><pre>-- Allow change tracking on database<br>ALTER DATABASE [medium-demo-db] <br>SET CHANGE_TRACKING = ON <br>(CHANGE_RETENTION = 2 DAYS, AUTO_CLEANUP = ON);<br><br>-- Allow chage tracking on specific table (1 query per table)<br>-- We need to have primary key defined in the table<br>ALTER TABLE [dbo].[Books] <br>ENABLE CHANGE_TRACKING <br>WITH (TRACK_COLUMNS_UPDATED = ON);<br><br>-- Verify that change tracking is enabled for the specified table<br>SELECT s.name AS SchemaName, t.name AS TableName<br>FROM sys.change_tracking_tables ctt<br>JOIN sys.tables t ON ctt.object_id = t.object_id<br>JOIN sys.schemas s ON t.schema_id = s.schema_id;</pre><p>With queries run above, after user is added to database, and database is enabled for ChangeTracking, and Tables are enabled for ChangeTracking, we will finally see Source data!</p><p>We select one source table, in our case Books, and we need to specify destination name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xltwXx1ldIFQJT2UGhJhUw.png" /></figure><p>In the 4th step we need to select schema where our data will be ingested.<br>Catalogue, schema etc will be explained in further articles. But for now we select default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pS5AEd8SxvM-98_Fxuty9Q.png" /></figure><p>In stage 6 we define schedules, (name of job is pipeline is different because I didn’t finish first pipeline, sorry) and then we can click “save and run pipeline“ which will ingest data to our destination schema!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CdgjnfPPZmohjs8VSukuGQ.png" /></figure><p>We will explore where it is stored, how it is stored, why we need to enable change tracking, and what are other options in further articles!</p><p>If you liked the content, you can react with claps. Stay connected by following me for more interesting articles!</p><p>As always, <br>Good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90b429bd47ed" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/get-started-with-databricks-lakeflow-connect-part-i-90b429bd47ed">Get started with Databricks - Lakeflow Connect - Part I </a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Assembly Instructions and Registers]]></title>
            <link>https://medium.com/@tberkovac/introduction-to-assembly-instructions-and-registers-643bc58fb90f?source=rss-18e7760e999a------2</link>
            <guid isPermaLink="false">https://medium.com/p/643bc58fb90f</guid>
            <category><![CDATA[machine]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cpu]]></category>
            <category><![CDATA[computer-architecture]]></category>
            <dc:creator><![CDATA[Tarik Berkovac]]></dc:creator>
            <pubDate>Sat, 27 Jul 2024 11:36:57 GMT</pubDate>
            <atom:updated>2024-07-27T11:36:57.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-epKmYnnc8k5I0t2a5gBA.jpeg" /><figcaption><a href="https://commons.wikimedia.org/wiki/File:Digital_Signal_Processor_9997.jpg">https://commons.wikimedia.org/wiki/File:Digital_Signal_Processor_9997.jpg</a></figcaption></figure><h4>We are confident with programming in C#, Java, C++, and other high-level programming languages. But do we really know how it is executed on the bare metal? Not really. Through this article and a few upcoming ones, we will gain a deep understanding of the main computer parts Processor, and RAM and how they combined execute the program we have written.</h4><h4>Registers — Fundamental part of the CPU</h4><p>Processor consist of many parts. First, we will introduce registers. These are like global variables that store some information. They do not store type of variables, but they store only 1’s and 0’s. We can have multiple sizes of registers, eg. 8-bit, 32-bit, and 64-bit, each representing how much data it can store.</p><p>The bit is a single 0 or 1, and the sequence of 8 bits is called byte.</p><p>So for example chars are one byte large (8 bits), and ASCII (<a href="https://www.asciitable.com/">standard for encoding characters to numeric values</a>) — value of the letter “A” is 65. Then we can store the value 65 in the register. We already said that values in registers can be stored only in binary, so when we convert 65 to binary it will be “01000001”.</p><p>A program is simply a sequence of steps (instructions) that modify the values in the memory. At the end of the program, we can read the values from the memory addresses of the result.</p><p>That being said we will introduce our first instruction.</p><h4>Introducing the first Assembly Instruction</h4><p>LOAD Register1, 65</p><p>Think of it for now as Load(Register1,65).</p><p>LOAD instruction accepts 2 arguments, Register1, and the value that will be saved in it, 65. It’s equivalent to: <em>Register1.Value = 65;</em></p><p>This will load value 65 to Register1.</p><p>In other architectures this instruction can come up as LOAD BYTE or simply LB then we name the register to which we load the value, and then we specify the value.</p><p>We must be precise about how many bits we want to load in the register. In the previous instruction, we are loading 8 bits which equals 1 byte.</p><p>If we for example want to load a number that is greater than 255, for example, 4098 which equals 1000000000010 in binary, we need more than 8 bits to represent it. We need exactly 13 bits. But usually, we don&#39;t have a register containing exactly 13 bits, we have registers sized to the power of 2 bits. So by that logic, we cannot store it in an 8-bit register, but we can in the 16-bit register.</p><p>Then we cannot use the Load Byte instruction, but we can use the <strong><em>Load Word</em></strong> instruction. Word is just a synonym for double-byte or (2 bytes).</p><p>So our instruction will be:</p><p>LW $Register1 4098</p><p>4098 from decimal will be translated to <strong>0001000000000010 </strong>and then it will be stored in Register1.</p><p>Note that we have put leading 3 zeros to make a number 16 bits long which is exactly what LW instruction accepts.</p><h4>Problem with storing huge numbers</h4><p>We have seen how problematic it can be when we need to double the size of the registers to store some values. In the previous example it was great that using double-bytes (words) is the happy case when we almost always use double-bytes.</p><p>Some other specific cases that are important to mention are: <br>- Double Word (DW) which is 2*2bytes = 4 bytes long<br>- Quad Word (QW) which is 4*2bytes = 8 bytes long</p><p>But what would happen when we need to store 21309201302939120139203920193012903911112745 in the register? We might combine a lot of registers each holding a part of its binary sequence of bits and then combine them somehow, but its an interesting question to think about.</p><h4>Comparison of the number of registers in CPUs through history</h4><p>For the better understanding of CPU architectures we will compare 3 different processors from 3 different times:</p><ul><li>MIPS R3000 processor released in January 1986 had 32 registers.</li><li>Intel Pentium 4 had 128 registers, released on November 20, 2000.</li><li>Modern processors have over 500 registers.</li></ul><p>We see that throughout history, the number of registers in the processor grew a lot. One of the reasons for this is the previous question that we have mentioned, and another, we can say is that trying to execute multiple instructions at the same time (parallelization of the instructions).</p><p>As the MIPS R3000 processor has the least number of registers, we will use it as our reference and analyze its instruction set. Concepts learned by analyzing the MIPS are universal and can be easily transferred to other processor architectures.</p><h4>MIPS</h4><p>So we will be using 32 registers of the MIPS R3000. Let’s name them,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ykwR9yYGSEa9l866JMk1ag.png" /><figcaption><a href="https://mathcs.holycross.edu/~csci226/MIPS/summaryHO.pdf">https://mathcs.holycross.edu/~csci226/MIPS/summaryHO.pdf</a></figcaption></figure><p>We can see many letters and numbers when naming the registers, and it might be confusing at first. Letters are abbreviations eg. V — for value, a — for argument, t — for temporary register, etc. And numbers are shorthand for how many registers there are, so for example a0-a3 means we have a0, a1, a2, and a3 registers.</p><p>It is important to note that number zero is so important that it has its own register. Other register names are not that important to understand right now. It&#39;s only important that we know that we are working with 32 registers and that there are 8 different kinds of registers.</p><p>We will introduce each type of registers when they are needed.</p><p>Now that we are confident with using registers, let’s talk more about the Instructions themselves.</p><p><strong>Instruction Set of MIPS</strong></p><p>Each processor comes with its instruction set. Those are instructions to which our high-level code is compiled, and the processor understands how to decode them and execute them.</p><p>We have previously seen LB instruction. Let’s have instruction to load numbers 8 and 7 in temporary registers 0 and 1. If we refer to our table of registers we can see that we have 10 temporary registers t0, t1, t2, …, t9.</p><p>LB $t0, 8<br>LB $t1, 7</p><p>Now that we have loaded values in the t0 and t1 registers, we can for example sum them with the instruction ADD.</p><p>Instruction ADD is a type of instruction that accepts 3 registers as arguments:</p><p>ADD destination_register source1_register source2_register</p><p>Great we can for example store to t2 register our result like so</p><p>ADD $t2, $t0, $t1</p><p>Now we have computed the simple sum of 7 and 8. We know that value is in register t2, but we cannot see it unless we make a syscall.</p><p>We call it by simply writing: <strong><em>syscall</em></strong></p><p>So we can do</p><p>ADD $t2, $t0, $t1<br>syscall</p><p>Syscall is a special instruction that heavily depends on how other registers are set, for example, v0 and a0 registers.</p><p>By calling syscall we will print out the value of register a0 as int if v0 is set to 1.</p><p>So instead of saving the result in t2 let’s save it to a0 (argument register 0), and set v0 to 1 like so:</p><p>ADD $a0, $t0, $t1<br>LB $v0, 1<br>syscall</p><p>This will now print us an integer 15</p><h4>Storing results in memory</h4><p>When we called syscall we provided the value of register a0 which is 15. Let’s say that we now want to print value 7 instead of 15, but our result is in a0 register, and we would like to store it somewhere safely so we can load it again in the registers for the next computing.</p><p>That’s where Store Word instruction comes in. It will store a value of a specific register to the RAM address which we provide as an argument.</p><p>SW source_register register_containing_adress_ram</p><p>Let’s say that we want to have our result on address 0xc5363 (decimal 807779). So we will store that address in another temporary register let’s say t4.</p><p>LW $t4, 807779<br>SW $a0, $t4</p><p>Store word instruction, will now on the address 807779 put result 15. Of course, 15 will be written in binary, 1111, and as SW is working with 16 bits, then from address 807779 next 2 bytes will be 0000000000010000</p><h4>Again making different syscall</h4><p>Now we can override a0 register to value 7 and print its value like:</p><p>LB $a0, 7<br>LB $v0, 1<br>syscall</p><p>And whenever we wish to reuse summation from before we can simply load it to any register (for example t5) by:</p><p>LW $t4, 807779 — first we load the exact number of address<br>LW $t5, 0($t4) — second we load from that address by offset (how many bytes we skip from that address) wanted value from the memory</p><p>This might be confusing when we use LW like so, why we didn&#39;t use</p><p>LW $t5, 0(807779)</p><p>That is a great question!</p><p>We didn&#39;t use it because we oversimplified LB LW instructions and said that in fact they can load numeric values, but in fact they can&#39;t do that.</p><p>To load immediately provided values like numeric values we need to use Load Immediate instruction. So wherever we used LB or LW to load some numeric values is wrong, and instead, we should have used LI.</p><p>That&#39;s why:</p><p>LW $t4, 807779 <br>LW $t5, 0($t4)</p><p>Won’t work, but:</p><p>LI $t4, 807779 <br>LW $t5, 0($t4)</p><p>will work.</p><h4>Final words</h4><p>There are still a lot of things to be explained in more detail mentioned in this article but I tried to make it understandable for everyone.</p><p>We have seen the different types of instructions for now, accepting 1, 2, and 3 registers as arguments, and the next topic will be classifying instructions and how they are really executed on the processor. (transferring human-readable instruction eg. LI $t4, 807779 to machine code so it could be processed).</p><p>If you liked the content, you can react with claps. Stay connected by following me for more interesting articles!</p><p>Thanks for reading!</p><p>As always, good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=643bc58fb90f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure Your App: Authenticating with Microsoft Identity Provider]]></title>
            <link>https://towardsdev.com/secure-your-app-authenticating-with-microsoft-identity-provider-1ee75afc12cd?source=rss-18e7760e999a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ee75afc12cd</guid>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[identity-management]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Tarik Berkovac]]></dc:creator>
            <pubDate>Tue, 04 Jun 2024 09:56:57 GMT</pubDate>
            <atom:updated>2024-06-04T18:52:48.283Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have been following us for a while now, you will know that we are exploring free Azure services, one of which is App Service. It lets us deploy both frontend, backend, and console applications in mostly any programming language (C#, JavaScript, Java, Python…). It is a very powerful tool to have, but as we are deploying it on Free Tier, how powerful it really is?</p><p>We can implement our own logic for the handling security of our app and restrict access to the resources. But in this article, we will cover the fundamentals of setting up the Microsoft Identity provider and some more advanced topics such as scopes and delegated permissions.</p><p>As always we will start with some code. We will go through an application that will be used throughout this article. It’s a simple .NET 8 Web API project with just two endpoints:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DmuJa1GlqQva0l5-E3va8A.png" /></figure><p>The GET Weatherforeacast route and its schemas are marked by the blue rectangles (this is the default route that we get when creating a new .NET Web API project).</p><p>Aside from that route, we have defined our own class Book, which corresponds to the model in the database, which is also hosted on Azure, specifically Azure SQL. The GET booksDB route retrieves all elements from the Book table. (that part is marked by maroon color).</p><p>Let’s take a closer look at the implementation of it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yg0GG5QDHAOu5_BuzS1rfQ.png" /></figure><p>We are using Minimal APIs for the construction of routes.</p><p>In the GET weatherforecast we are returning a list of 5 instances of the WeatherForecast class.</p><p>In the GET booksDb, we are using AppDbContext which uses the Books class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iz_Dj-LCAajNaF2qG36BFg.png" /></figure><p>We have Defined Table Books based on the Book class. Also, we have seeded some data by overriding the OnModelCreating method and providing some initial data. For more information on how to provide some initial data at the start of the application, please refer to the section Data Seeding on this <a href="https://medium.com/towardsdev/pgadmin-4-docker-container-and-data-seeding-ef-core-ba8f9259ccc0">link</a>.</p><p>Great now let’s show the deployed application to the Web app service:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WTXl8dkyKiiev1SxrEVbCg.png" /></figure><p>Here we can see the main information of the deployed application, such as its name, status, default domain, operating system on which is our application running, <a href="https://github.com/tberkovac/MediumLoadTesting">GitHub Project</a> (it’s a public repository feel free to check it out), and much more information.</p><p>To see the operating system, instance count, SKU, and size we can explore the Hosting section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*feKpgbXAWM73nOejoLqamw.png" /></figure><p>We see that we have 1 instance, which means just 1 virtual machine that is hosting the application (the application can be hosted on more than 1 virtual machine, so requests can be distributed to other instances and that way we can serve many more users). This 1 instance that we have is using the Free tier (F1), which is the lowest we can go.</p><p>Now when we try to access the the GET WeatherForeacast we will recieve data, as expected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xXLMVv07CGg7uv4XlZEjQw.png" /></figure><p>How can we restrict access to this route, and every other route as well? Note that we do not have a Users table in the database. We can enable Authentication and Authorization on the Web App by navigating to Authentication in the Settings section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kjl7o2wkDeAdO74f-drvLQ.png" /></figure><p>We do not have any Identity Providers, so let&#39;s click on “Add identity provider”. It leads us to new screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VlTsfrKYWMhMxfdoRQ0r3w.png" /></figure><p>The identity provider is a service that lets us authenticate users in different ways. If we select Microsoft, we will enable login with Microsoft email to our application. So let’s select Microsoft:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g0LF0_QrP7-d8XMFg3a-kQ.png" /></figure><p>Now we have additional things we need to configure that are needed to create an Identity Provider. We mentioned that we do not have the Users table in our database. Users&#39; information needs to be stored somewhere, and that somewhere is called Tenant which is part of Entra ID service (previously Azure Active Directory). The tenant is our Users table.</p><p>We are given the choice to select between Workforce configuration and External Configuration.</p><p>Workforce configuration simply means that we are a group of people e.x. a company that has its employees who need access to the services.</p><p>The external configuration enables us to manage all the other users who would like to access our application.</p><p>We will stick with the Workforce configuration. Let’s show what Tenant on Azure is. If we go to the Entra ID service we will get our default Tenant:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4RP9QnzFrSm09o0e3OErBQ.png" /></figure><p>We see that it has its own unique ID (Tenant ID), and we have information on how many Users, Groups, Applications, and Devices are registered in this Tenant.</p><p>Let’s take a look at Users in our Default Directory (Default Directory is one kind of Tenant so those can be considered as synonyms):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*29ZIJVywBZiM7h6m3B96vQ.png" /></figure><p>We see that only I am registered in this Tenant. To add some other users, we can use the New user button, and fill necessary information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gce2jyEvNYzj3M_lMrUWYw.png" /></figure><p>We will not do that, but just to know that it is also a possible way to add a user to the organization.</p><p>Now that we understand what Tenants are a bit more, let’s go to the next section when creating Identity Provider, <strong>App registration</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K90qHwuBsEF9ojeVv4sSlQ.png" /></figure><p>Previously we showed that in the Tenant, we can have Users, Groups, and also Applications. By selecting <strong>Create new app registration</strong>,<strong> </strong>we<strong> </strong>are in fact creating an Application in the Current tenant. We also need to give it a name in our case app registration can be named the same as the web app, medium-load-test.</p><p>Now onto the next section <strong>Additional check</strong>, we will leave everything as it was preselected. This allow requests from specific tenants and we put our default directory to it, is the same as selecting first option, but more flexible if we want to add other tenants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ApdBUiO0kHXi-AIpHS0hkg.png" /></figure><p>In the <strong>App Service authentication settings</strong>, section we will leave everything as it was preselected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0oTfcC0fjKojtUvTVCdzUQ.png" /></figure><p>We will restrict access to everything by selecting Require authentication.<br>Requests, that are not authenticated, will be redirected to the Microsoft login page.</p><p>With this, we defined where we will store new users (in which tenant), from which tenant requests can be made, and what happens if some unauthenticated user makes a request (he is redirected to the Microsoft login page).</p><p>With this done, let’s move to <strong>Permissions</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eCD7eIvngobtf5OJLENBPg.png" /></figure><p>We have one predefined Permission User.Read what is needed for Signing in. For now, we will not add new permissions. Let’s hit add (we have changed the name of app registration from medium-load-demo to medium-load-demo-v3 to make it unique).</p><p>Everything went successfully, and we have created a new Identity Provider for our Web App.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sNCi3Lo3R5iXDNET6vZ2Zw.png" /></figure><p>If we click on medium-load-test-v3 we will be navigated to App registration where we can see the main information (IDs) of the Registered Application that we will use to integrate everything in our code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUSxNO3dRkv_X9TrbOoIQQ.png" /></figure><p>Now let’s integrate Authentication and Authorization in our code, to use this App registration. In Program.cs file we need to add default code that we can find in the Microsoft documentation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5bbQqGxm8Xjnc-XESMiUw.png" /></figure><p>Right after the instantiating builder we need to register in Dependency Container services for authentication:</p><pre>// &lt;ms_docref_add_msal&gt;<br>// Including Authentication and Authorization for the Microsoft Identity Provider<br>builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)<br>                .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection(&quot;AzureAd&quot;));<br>builder.Services.AddAuthorization(config =&gt;<br>{<br>    config.AddPolicy(&quot;AuthZPolicy&quot;, policyBuilder =&gt;<br>        policyBuilder.Requirements.Add(new ScopeAuthorizationRequirement() { RequiredScopesConfigurationKey = $&quot;AzureAd:Scopes&quot; }));<br>});<br>// &lt;/ms_docref_add_msal&gt;</pre><p>Right after instantiating app from the builder we need to register middlewares in the HTTP request pipeline:</p><pre>app.UseAuthentication();<br>app.UseAuthorization();</pre><p>Also, we need to add new sections in appsettings.json</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c2QiyBzG5PrtzgZZLqTePQ.png" /></figure><p>To use a database we can authenticate by giving the password and username of the SQL Server, but let’s do things differently here. Let’s allow access to the database only for logged-in users. That way we can move out using credentials from the connection string for connecting to the database.</p><p>Our ConnectionString now can look like:</p><pre>&quot;ConnectionStrings&quot;: {<br>  &quot;DatabaseConnection&quot;: &quot;Data Source=medium-demo.database.windows.net,1433;Initial Catalog=medium-demo-db; Authentication=Active Directory Default; Encrypt=false;TrustServerCertificate=True;MultiSubnetFailover=True;Connection Timeout=60;ConnectRetryCount=255;&quot;<br> }</pre><p>Also, we will add the DatabaseConnection connection string to our web app directly to override the value from the appsettings.json for production env:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pPLq_aqYUAVuL4CA0vo3Kw.png" /></figure><p>By selecting DatabaseConnection we will get more info in a sidebar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*abHQmZilcxbZM3B_qDwdXg.png" /></figure><p>Where we will put the following connection string:</p><pre>server=tcp:medium-demo.database.windows.net;database=medium-demo-db;TrustServerCertificate=true;Encrypt=false;Connection Timeout= 60;ConnectRetryCount=3;ConnectRetryInterval=10;</pre><p>So the flow now is if you are registered in Tenant, you can log in by using your own email/password combination and access the database.</p><p>Let’s modify our SQL Server so we can authenticate to it only by Microsoft Entra authentication:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z6fXQUuoyzAhfzzRv5dhTw.png" /></figure><p>Also, we need to make this SQL Server accessible to other Azure resources. By default, all external traffic is blocked. We can let specific IP addresses communicate with our server, and that is by specifying Rules to override the default behavior for specific IP addresses:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0vlZ4w3DPCIRyz6bzbZz4g.png" /></figure><p>The problem arises when a new client wants to access the Database, but we do not have his specific IP address whitelisted at that moment. We could ask him to tell us, and then add that IP address as a rule but it takes time.</p><p>Instead of doing that, we will check the box next to <strong>Allow Azure services and resources to access this server</strong>. By selecting it we are whitelisting all Azure services&#39; IP addresses, and that is in fact what we want. By authenticating on the Web App, the user should be able to read Data from the Database of that Web App, so we are doing authentication just once.</p><p>The process of accessing the Database through Authentication on the web app is called Accessing the Database on behalf of the signed-in user.</p><p>Now we will create a new Permission to the authenticated user on the Web App.</p><p>Let’s add new permission to our App Registration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CEdA4GYTZkTfFor2J9W-Dg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EX4OEe2cFAZDBvXjhKP-2g.png" /></figure><p>We will navigate to <strong>APIs my organization uses </strong>and then search for Azure SQL Database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pxW6_FVHOlE-wZbwJJmr4w.png" /></figure><p>By selecting Azure SQL Database we will get a new screen in the sidebar, where we will choose <strong>Delegated permissions</strong> (as the signed-in user) and check the box next to <strong>user_impersonation</strong> in the Permissions section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GnHHI_TbpPezKjoUxqiSAQ.png" /></figure><p>After clicking <strong>Add permissions </strong>we will see our new Azure SQL Database permission in the Configured permissions section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BWJ3IiGqz7qb7Ts-j_i3cw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ezcaifeIJvdPfePGv7kMTw.png" /></figure><p>When logging in we receive a token from the Microsoft Identity Provider, but we need to request this permission for the Database as well to be included in that token.</p><p>To do that we will need to modify “IdentityProviders -&gt; AzureActiveDirectory -&gt; Login” section in authsettingsV2.</p><p>Unfortunately, we cannot do that through the Azure portal, but we can do it through: <a href="https://resources.azure.com/">resources.azure.com.</a></p><p>We can do that manually by navigating to authsettingsV2 file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*53OYAKtwSey6WnHXXRwSrQ.png" /></figure><p>If you don’t have any subscriptions, change your Directory to the one that has Subscriptions.</p><p>Now that we have found and opened the authsettingsV2 file, make sure you are in Read/Write mode, and click Edit. It will enable us to change the contents of the file. We are specifically interested in changing <strong>the</strong> <strong>login</strong> part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x0xN81YW7tVj8sZhV2_gUg.png" /></figure><p>Now we need to add the loginParameters property in the login section. The value of login parameters is a list. We need just one string in the list and that is for defining scope. It will be requested when we want to log in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mZxOY7QmXo_TfIMg32fi_w.png" /></figure><p>After these configurations on Azure&#39;s side, we need to commit changes and deploy new code on our web app. We can see that Build and Deploy went successfully:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hsLYgZGYs9t9Ga0x7PCC-Q.png" /></figure><p>Let’s test our application now by navigating to <a href="https://medium-load-test.azurewebsites.net/">https://medium-load-test.azurewebsites.net/</a></p><p>We will get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fzhJjV-wHsc8lq49Y5bLaA.png" /></figure><p>In the current browser, I am logged in on Azure and I am not redirected to the login page, instead of that, I am asked to Accept permissions defined by our scope parameter.</p><p>As an admin, I can consent on behalf of my organization, but I will not do that yet. After we accept those scopes we will be authenticated. Our backend does not define “/” route, so we get a 404 not found error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UhWo8FbuC5lBewq_CEqjFw.png" /></figure><p>Let’s now try our GET weatherforecast route:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hV_WMFB-HGqAJTL31zc1VQ.png" /></figure><p>It works well. We get a response in less than a second.</p><p>Let’s now try our GET booksdb route:</p><p>It took some time but finally, it is here. As the database is serverless and can be paused, the initial process of starting can take some time, but once it starts it is as good as non-serverless.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aV1I1AwYUTB7PR58VXcK1g.png" /></figure><p>Let’s now do the same flow but in the Incognito window:</p><p>Only pictures with explanation at the end will be shown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ve5Q0SDUsawofXdqiXQc_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQVp036oSNCC49eBpOemfQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AOQS7zN0jJh95PgAuBSWsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LGEhyziEh57W9GdXQJYYlA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dVZvBzsSAtj5CHKlI8O6HQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yVbF4hExZ6ZxqEWMfXogg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k1S7jOBoJObI9QgyxlHU5w.png" /></figure><p>We had a usual Microsoft login flow. Additionally, we were asked for a code which was sent to our email. And the rest is the same as before when working from a non-incognito window.</p><p>If you get some kind of error while connecting to the database just give it a try a few more times by refreshing the page. As I am using a Free tier Database it sometimes gets stuck.</p><p>Note that when we are trying to access the default domain, we are redirected to the log-in page instantly. So we are not supporting the registration flow for the external users.</p><p>We only tried with email which is both admin on the server, and owner of the Azure resources, so we <strong>did not have to add users to the database</strong>. All users that get added to Entra ID tenant, <strong>ALSO NEED TO BE ADDED TO THE DATABASE </strong>to make everything work.</p><p>More about enabling user registration flow, adding users to the Database, and adding users to the Tenant manually over the Azure portal will be covered in further articles, so stay tuned for more!</p><p>Check out some of my other articles:</p><ul><li><a href="https://towardsdev.com/net-web-api-with-sql-database-azure-azure-data-studio-1efda08927bb">.NET Web API with SQL Database Azure &amp; Azure Data Studio</a></li><li><a href="https://towardsdev.com/introduction-to-docker-e1eefd9a4970">Introduction to Docker</a></li></ul><p>If you liked the content, you can react with claps. Stay connected by following me for more interesting articles!</p><p>Thanks for reading!</p><p>As always, good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ee75afc12cd" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/secure-your-app-authenticating-with-microsoft-identity-provider-1ee75afc12cd">Secure Your App: Authenticating with Microsoft Identity Provider</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Gateways, Load Balancing, Caching and Proxies]]></title>
            <link>https://towardsdev.com/api-gateways-load-balancing-caching-and-proxies-0f4678c3bf03?source=rss-18e7760e999a------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f4678c3bf03</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[proxy]]></category>
            <dc:creator><![CDATA[Tarik Berkovac]]></dc:creator>
            <pubDate>Thu, 23 May 2024 11:22:22 GMT</pubDate>
            <atom:updated>2024-05-23T16:39:03.138Z</atom:updated>
            <content:encoded><![CDATA[<p>Suppose we have multiple services. With the number of services rising it is becoming very difficult to configure all the URLs on the frontend.</p><p>What happens if we deploy one service somewhere else?</p><p>We would need to update all of our base URLs on the frontend part. That’s why we include API Gateway. It solves the problem of remembering all the URLs, and only we will care about routes in one place.</p><p>Each microservice will have a unique first part /first_part/ and by that first_part we will reroute our request to the specific server.</p><p>This thing that reroutes requests to the different microservices on the server side is called a reverse proxy. If we were hitting some route on the client part which rerouts to the right backend side it is called forward proxy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jBC6Oid8BjWsRZ5yjbo8pA.png" /><figcaption>Reverse proxy, is proxy on the server side, which reroutes requests to specific servers</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WHoUTQ8F1l39sgOuCtzxPQ.png" /><figcaption>Forward proxy reroutes requests as well, but it is on client side</figcaption></figure><p>Most of the time we are using reverse proxy.</p><h3>Simplifying process of AuthN and AuthZ in Microservice Architecture</h3><p>Now we see that it is a great thing to do, but suppose that we now send requests to different services. How would we implement authorization then? Let’s say we have Microsoft Provider and our Auth microservice. Not every service has all the information data, for example, Username and PasswordHash, because we want it centralized in the Auth Module.</p><p>One of the benefits of using API Gateway is that we can add the initial step of hitting e.x. /auth/validateToken route, which will return if our token is valid or not. If it’s not valid we will send an unauthorized response, but if it is valid we will reroute it to the wanted microservice.</p><h3>Handling large numbers of users</h3><p>Now let’s say that we have 100,000 users who are currently logged in and are using the application simultaneously. If they are making too many requests, it would mean that each request (which needs to be authenticated), would first need to be routed to validate the token or to issue a new one. To handle that amount of requests per second (RPS) we would need to scale up the auth module pretty well, and with scaling comes a big cost.</p><p>Another way to resolve the issue of authorization users is to store tokens in the cache memory of the API Gateway. Then if the token matches we are good, and can reroute the request. If it does not match, or even if it does not exist, we can reroute to validate the token (if the token is refreshed) or to issue a new token if it does not exist in the cache at all. That scales down requests from 10,000 requests per second (assuming that we have around 100,000 simultaneous users), to just a few hundred, because most of the time we will have matching tokens in our cache memory. That process when we have a matching token in the cache is called cache hit. Otherwise, it’s a cache miss.</p><h3>Load Balancing</h3><p>Also, suppose that we have one dominant microservice that needs scaling. There are 2 types of scaling, vertical scaling (increasing CPU and Memory of the machine on which the service is hosted), and horizontal scaling which means increasing the number of machines that are hosting the app.</p><p>Even though it’s the same application, it’s easier to handle 30k requests per second on one machine and 30k requests per second on another, than to 60k RPS on just one machine.</p><p>If we did not have an API Gateway, we would need to know how many machines we can hit from the client side, but this way, we will let our API Gateway decide which machine to hit for that specific route. That is called load balancing and the thing that does that is called Load Balancer.</p><p>So API Gateway acts like a Load Balancer as well. It’s also Reverse Proxy, and can handle caching. It’s a great tool to add to our architecture.</p><p>If you liked the content, you can react with claps. Stay connected by following me for more interesting articles!</p><p>Thanks for reading!</p><p>As always, good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f4678c3bf03" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/api-gateways-load-balancing-caching-and-proxies-0f4678c3bf03">API Gateways, Load Balancing, Caching and Proxies</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Communication between Microservices with Azure EventGrid]]></title>
            <link>https://towardsdev.com/intro-to-communication-between-microservices-azure-eventgrid-88acff7553d0?source=rss-18e7760e999a------2</link>
            <guid isPermaLink="false">https://medium.com/p/88acff7553d0</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-event-grid]]></category>
            <dc:creator><![CDATA[Tarik Berkovac]]></dc:creator>
            <pubDate>Thu, 16 May 2024 18:35:30 GMT</pubDate>
            <atom:updated>2024-05-17T17:24:40.926Z</atom:updated>
            <content:encoded><![CDATA[<p>Suppose we have service A and service B which are deployed on separate machines. Services can communicate directly via HTTP by using HttpClient.</p><p>The problem with that is that service A then depends directly to service B. So if the request fails on Service B, that means the request will fail on service A as well.</p><p>In this article, we will cover a lot of different topics from different angles. It is important to research each point from the list on your own after reading article to have a better understanding.</p><p>We will cover:</p><ol><li>Understand different methods for communication of microservices</li><li>Creation of EventGrid Namespace</li><li>Briefly touching MQTT protocol</li><li>Creating Topics</li><li>Creating Subscribers for Topics</li><li>Exposing our localhost port to make it publicly available by using NGROK</li><li>Looking at the execution of the code, (is it really asynchronous)</li><li>Analyzing Graphs on Azure to see how our events behave</li><li>Introduction to filter on wire feature on the EventGrid service</li></ol><p>We have a lot to do so let’s get right into it!</p><p>To make the problem from before a bit more decoupled we will introduce a third element to those two which is called message broker. So when we want to communicate from A to B we will send event/message/request (all synonyms) which will be stored by the message broker in it’s memory.</p><p>Service B will define which types of messages it is interested in and can process them.</p><p>There are many types of massage services on Azure as of May 2024:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g0_x6irBGHKm4-ughAso5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N1dXMj5zdONFQnLDB22e4Q.png" /><figcaption><a href="https://azure.microsoft.com/en-us/solutions/messaging-services">https://azure.microsoft.com/en-us/solutions/messaging-services</a></figcaption></figure><p>The most popular ones are Service Bus, Event Grid, and Event Hubs. Each one of them excels in a particular problem, but fundamentally if our application does not need high optimizations we can choose whatever.</p><p>We are using a pay-as-you-go subscription on Azure and would like to use a free service, so let’s take a look at their pricing, or if maybe some of them are free always.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mUBt-pFIVUYneLxkHMWfxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pOiTACR5J4TrvCIT70KN3g.png" /></figure><p>Event Hub has no free tier, so we will not cover it in this article.</p><h4>2. Creation of EventGrid Namespace</h4><p>We will explore Event Grid first as it is Free always.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uRoHxhlprvlaVCe5swyclQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVk8--ri0WZt4OdKLsiFOw.png" /></figure><blockquote>MQTT stands for Message Queuing Telemetry Transport. It is a lightweight messaging protocol for use in cases where clients need a small code footprint and are connected to unreliable networks or networks with limited bandwidth resources. It is primarily used for machine-to-machine (M2M) communication or Internet of Things types of connections.<br>More info: <a href="https://www.paessler.com/it-explained/mqtt">https://www.paessler.com/it-explained/mqtt</a></blockquote><p>So MQTT is just like HTTP, its protocol which is used to communicate between 2 machines. It uses TCP under the hood.</p><p>Creating a Namespace costs us $0.04 per hour, but let’s see the process of creating a namespace:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dMMYV-NM9zKS55zYycyBrA.png" /></figure><p>We will create a new Resource group: medium-events-demo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBcxmV9GCjuQzGFk0gqJMA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PcRgkx7r6ZsnNQJQJ-gtsA.png" /></figure><p>We will leave the connectivity method to Public access, but we will later cover topics such as creating virtual networks and using private access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yREsXrpkZIrvOIqMvHJHmA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e0o7zP6bbhKrOOckkd3Tbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V-kis_jx3aKJoWcmBZEyPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AYWwbQ9kVoI-TWPNbqpU1A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8gJ-OWK9CvA6tk_AfBbXiQ.png" /></figure><p>We don&#39;t have any clients in this namespace. The client is an application or a device which can publish events or subscribe to them. So let’s add a new Client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cpg8arMXEkYvhFMVkjgzfw.png" /></figure><p>We first need to enable a MQTT broker. We will select “Go to configuration”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Dt1_LXe2GDdl2EMIMuSDg.png" /></figure><p>We implement MQTT if the client network bandwidth is small, or it is connected to a network that might go down.</p><p>Now we can add a new client:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5O8keN4O_Y5e3AnMc6E8Nw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*90JogkEVTylt4_lpD0a7_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y4x4YUE-2FdElghEJ361ww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GXIRpFQb-57yOpnjSHBUSA.png" /></figure><p>Now that we have Client defined, we can work on our backend part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vaUmk09hK1IoBZx-4Sqg2w.png" /></figure><p>Now suppose we have an external system that we’d like to call when we update Users name. Sure we can create a new module, and again make contracts which by which we will call that module, but our requirements say that that service should always be up and running, and it should implement some additional security on database level.</p><p>If that&#39;s the case, we will create a new microservice which we will talk to from the Users Module.</p><h4>HttpClient</h4><p>We can create an HTTP client instance and hit the URL of the backend directly. That’s a good option, but what if the service is unavailable at that moment, Data will not be consistent.</p><p>Then we would need store additional informations in the database that the event was raised, and that it wasn’t processed by another microservice, and we would create some kind of background job that will run daily to see if there were unhandled events. We see that it gets messy pretty fast.</p><p>Let’s take another way to handle this situation.</p><p><strong>EventGrid</strong></p><p>Another way to solve it is, by creating Event and using MessageBroker (EventGrid MQTT). Now we don’t call microservice directly, but indirectly over the MessageBroker. The great thing about Message Brokers is that they only delete messages from the memory once they are processed.</p><p>By this, we are handling case of what happens if our microservice is down pretty neatly.</p><p>We will first install EventGrid.Client package:</p><pre>dotnet add package Azure.Messaging.EventGrid</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GLLZxad2EXsVm8WQHzzFPw.png" /></figure><p>We are asked for a topic endpoint but we haven’t created one. The topic is a thing we hit, and it also holds our message until it is processed, So let’s create it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVggfRS42Do8GZtjv7wFPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YcIg7gR7hl6UpkmlJD3aqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*20S3_r1EBLxWyrYI-zVFqg.png" /></figure><p>When we open it we can see more details, out of which there are in which namespace is our topic, and also retention days represent how long our messages will be stored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3huRg91fb9R9lyE4KvRNjw.png" /></figure><p>Creating a topic in the namespace gives us retention days property. So when we publish a message to the topic it will be stored for a number of days.</p><h4>Analysis of the cost</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yo_lJRDnW1jjeHtbJNgN6Q.png" /></figure><p>When working with Azure always be careful when creating new resources. Prices can skyrocket pretty fast. Our resource group billed $0.24 and all of that is for EventGrid service. We will delete it now so as not to spend any more money.</p><p>Let’s create an event grid topic that is not in the namespace. This type of topic will be free of charge, and everything else would be same as if it were in EventGrid Namespace (namespace gives us access to MQTT broker which we do not need for this article):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RhmCzqrG-Te9_ciJnK1wLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zqxkCOZtYSGfSBXGwnfGVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O2IrKW-m6BdOuiU7l6PgtA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ioaTWSd1pXZCaxv0ezVn2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LuQ7x3dFzhWUWyDtt4hX1A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2D2uCFeoVjGIZ_fuuNnufw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H8MIZ5RjHqBEpc_kMZNZ8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fVptVYP1yiBN8O-quCKJGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vYDtcrZ7ML4DFSPtDl4Lpg.png" /></figure><p>We can once again go over the properties of our requirements. As validation has succeeded we can click on create:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5c1rXndancGt-D8BllZqoQ.png" /></figure><p>Let’s go to the resource:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*epjndHqPQ-u0U_SAa78dXg.png" /></figure><p>We see that it is in the Basic pricing tier. Local authentication is enabled so we are given some access keys. Let’s explore it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1KLT7SNdFt6WqG6PrDBOyQ.png" /></figure><p>Those we can send together when publishing event to topic.</p><p>Now let’s create a subscription to this event. We will click on Event Subscriptions and + to add new one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SNA9lXNLiBGu7Cxq8JsDbA.png" /></figure><p>We are asked for a Name and Endpoint Type:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RB-rFd3KPIZeGLQDU3vrsQ.png" /></figure><p>We will select Web Hook, which means that the subscriber will hit any address which we give to it. The only thing is that the address must be publicly available to hit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jAoB8R7j2dKPJ4rrBZ_hcA.png" /></figure><p>After selecting Web Hook we need to add a Subscriber Endpoint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K1z2C177cfF-KgmI4M1e0w.png" /></figure><p>We need to define an endpoint that is publicly available on the internet. But we haven’t even done our project yet. So let’s do it quickly:</p><p>Command+shift+p gives us the command pallet. Let’s select .NET new project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gbS2YfMDhPFSVfNPHPb88A.png" /></figure><p>Then Web API project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-xQY1VrQsdBt3SJ2njbKKQ.png" /></figure><p>And let’s name it MediumBooks.Payments. <br>After we open it as the solution we will see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nCsJ_ONho-DEPyHrfT_D5w.png" /></figure><p>Great, let’s define a new controller and Post method which will be hit when we raise the event from our application.</p><p>We need to install following packages:<br>- Azure.Messaging.EventGrid <br>- Microsoft.AspNetCore.Mvc.Core .</p><p>With that setup, we can create a new POST route:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eoe7RbAFtuPsX4LsmWy_zA.png" /></figure><p>It takes a list of EventGrid events from the body as an argument and returns IActionResult, which has an HTTP Status code and a Response Body.</p><p>By accepting a List of events in the route, we do not need to extract them from the HttpContext. Also, EventGrid supports filtering of events on a wire, which we will talk more about later.</p><p>Let’s iterate over those events that are passed to the PostEvents route.<br>There are two types of events, SystemEvents and CustomEvents which we define. We will handle them differently, because we can deserialize SystemEvents with TryGetSystemEventData, and Custom Events we must deserialize manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bPzjp8-U2BE1j1xMBaUxJw.png" /></figure><p>There is one SystemEvent that we need to handle, SubscriptionValidationEventData. It just resends the ValidationCode that it has in itself to Azure to prove that we own that subscriber. That step is called validation of our subscribers. This is just a security measure to prove that we want to forward requests to our own service, not to DDoS someone.</p><p>We “handle it” in the way that we return HttpResponse with status code 200, and in the body, we return the validation code which is a property of the incoming event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_zgATHRw8xKruIe0e3xU6A.png" /></figure><p>First, we create an anonymous object responseData, with one property of ValidationResponse. This property must be named like this for everything to work correctly because Azure expects this name.</p><p>We create OkObjectResult with responseData which is just HTTP response with status code 200, and body which we provide in argument.</p><p>Let’s now remove the default endpoint route from Program.cs and map controllers so our controller is visible. Also, we will comment out useHttpsRedirection (will need it later).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*igs-TegXI7lYSeDF9qorsA.png" /></figure><p>With this, we are good to go. Let’s run our application by clicking F5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6i23Tp8SC3brYlFXwOJ8Bg.png" /></figure><p>It opens a new tab in our browser. We see that it is available on localhost:7280 for HTTPS traffic, and we see our defined POST route.</p><p>Unfortunately, Azure cannot resolve localhost to our host machine. We need to either deploy our service somewhere and hit it over that publicly available endpoint, or we can use “ngrok”. Ngrok allows us to get public domain that maps to our localhost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hjr7z3FonIev87VMIuBm7g.png" /></figure><p>To use it, we can sign up for free and log in afterward.</p><p>When we log in we will get all the needed informations to start using ngrok:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TI2XIyzo0yd_VZ4iWWW6Bw.png" /></figure><p>It automatically detected Agent and gave us commands which we need to run in the terminal.</p><p>Let’s explore the section for deploying apps online:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xEdehMOALMWawkn_-L4CzA.png" /></figure><p>By analyzing command:</p><pre>ngrok http http://localhost:8080 </pre><p>We see that we need to provide our localhost address with the port. By using the free tier of ngrok we cannot use HTTPS but only HTTP.</p><p>Our app is running on port 7280 but for HTTPS traffic which we cannot use with ngrok so we will need a port where our app is listening for HTTP requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5XcsHIllT3IwPwOAiOU4vw.png" /></figure><p>We can see it is listening on <a href="http://localhost:5283,">http://localhost:5283,</a> so let’s map that address with ngrok:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bi37IdDO0m0bxAXa3EUO7w.png" /></figure><p>And we got a newly assigned public domain. Let’s put it as our webhook endpoint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DJuj_ou-zU-vBRltGmpo3w.png" /></figure><p>To this domain, we need to add /api/IntegrationEvents as it is where our POST route is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*buTqXQ_Nj6FLR9lBoYae8Q.png" /></figure><p>Let’s hit create once again, and hope for the best:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ka1MKUW5vSKGGOCJpHKnEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2UDk5FzSFGeT0_x0NtaQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2iiT26EwUkxktOT55-QMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVAWMqmScwQCeugWTbOtdw.png" /></figure><p>Here is the ValidationCode which we send back with status code 200. So our application gets validated. It is also possible to past ValidationUrl to the browser and validate it manually. Now back to Azure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5NABo-4uELzQNVS9pVXEA.png" /></figure><p>Unfortunately, it took more than 30 seconds to take pictures while debugging, so we hit create once again, and now we will just skip fast over the breakpoints:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2PyeGNrLCxY8ziTcCn4RCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u0673zj-h6WF-75HrSjegA.png" /></figure><p>We can see that our Subscriber is created successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vXJqNmJTzpVUxPqA3E3-Fw.png" /></figure><p>When we open it, we can see both Topic from which the subscriber gets Events and the webhook by which they are handled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Im87KfNBQH6RT8Q3hhRUrg.png" /></figure><p>It takes a message from the topic user-update-topic, and then forwards it to our web hook <a href="https://b0e1-92-36-215-120.ngrok-free.app/">https://b0e1-92-36-215-120.ngrok-free.app</a>/api/IntegrationEvents.</p><p>Let’s now take a look once again to Business Logic Layer and our UpdateUser method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EcIBdbtB03L8D_w_WAEjVg.png" /></figure><p>Aside from notifying modules in the solution, we will also send an event to the topic we have just created. We are instantiating the client in the method and hardcoding the Endpoint and Key values. This is not good solution but for now we will keep it as is.</p><p>Let’s rebuild and run our app again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DImd_PUenCh7H5EsBeOEug.png" /></figure><p>Now let’s hit PUT route, from the Postman:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPXt42AjIf9jSKi9d0ZlVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*coiTLQyIo14P_PAJ_taNAQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EWu7poHCCVr6mqkUMKBJ0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7BMAMaoZZ1jyFEAh1W1A5Q.png" /></figure><p>Let’s go to Azure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9zdpF_BoyAI8nC_PEO9jqw.png" /></figure><p>We see that we have Matched Events 1 and Delivered Events 1.</p><p>Let’s go to our subscriber to see chart there:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oDYKDwbtN_Du6FRTJiUxKA.png" /></figure><p>We see also that Matched and Delivered Events have 1 next to them.</p><p>Let’s now see if it really is asynchronous:</p><p>We removed breakpoints from UpdateUser method, and added breakpoint in PostEvents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d7YfziwdIzBuc7ZjqJ5VWQ.png" /></figure><p>We will send our request from postman and we will hit first breakpoint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3gVNWMZxRvd9aG9iwPyByg.png" /></figure><p>After we continue (unblock) the first breakpoint, now our both applications will be stopped on the breakpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MfY-8dc2vwE8ng3QDrTk7w.png" /></figure><p>We see that it finished in MediumBooks.API, and has just started executing in the Payment microservice. It means that the Event was published to the topic and processed to the webhook endpoint which is mapped to our Payments microservice.</p><p>Let’s continue once more in MediumBooks.API application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dpa3jqlC9yLwow0fWazSXA.png" /></figure><p>On the left request is done, and on the right it is still not. Let’s see now what happens on Azure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZicqpaVD6981H6_TInfIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SAARNG_lg9ywgnaYzHeulw.png" /></figure><p>We see that we have one matched event and a moment after that one published event.</p><p>Now let’s see our subscriber:</p><p>Earlier we had 1 matched 1 delivered:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aOmlcVga6f-YpkY6Ombt6g.png" /></figure><p>Now we have just 1 matched because the breakpoint is still holding request on the Payment service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hzIfmg0b0DwKZsxU_T_K4w.png" /></figure><p>Let’s continue the breakpoint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mSmeTAwx_EkpfX0uPMtiJA.png" /></figure><p>Here we can see the EventType Example.EventType, which is in fact how we named our event:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ERcOUC8F_toxNau18MgA2w.png" /></figure><p>After clicking on continue request finishes with a problem. Probably due to the long wait time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDNC9yP2C6nCHW14oSqXDA.png" /></figure><p>Let’s take a look at Azure now to see the statistics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QtmkbyhNTbBSWrA5T0nPCw.png" /></figure><p>We have 1 delivery that failed just after it was matched. There is about 15 minutes between those 2 events. Let’s try it again now but we will hold the breakpoint just for 20 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r9q9xp6vaImu7shPTRwiEg.png" /></figure><p>And just after a few seconds, we received one more Event (???)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VK_CwmHWEsV7WjP7RSAQ3Q.png" /></figure><p>Probably one that was failed before.</p><p>Now let’s take a look at Azure:</p><ol><li>Topic (event which we initiated is matched published and delivered sucessfully):</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tONcloShl_dQCLuTUcC_SA.png" /></figure><p>Event from before around 7:18 delivery failed, but after our initiated request we have that “delivered successfully event”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KB-L4n4TGYHgq4h7ONKRaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k-IIgZAfMuegg8orbiqQVA.png" /></figure><p>Now let&#39;s see Subscriber:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ea2qBbDNEkYXkY3ylnjz8A.png" /></figure><p>It means even if we stop our MediumBooks.Payment service, Events from MediumBooks.API project will be saved on the topic, and processed later when the Payment service is up and running. This is good, because even though Event delivery failed, it will still hold and process the event.</p><p>The event will be stored for 1 day as we defined here, on the creation of the topic and subscriber:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YFS270LQbcxMtbQxldB9MQ.png" /></figure><p>One more important feature of subscribers is filtering on the wire, we mention it earlier. That means that we can set up some filters for our subscriber so only events of that type are delivered to that subscriber. Otherwise, all events will be delivered to our service. If we were emitting some events for changing data that is not crucial for Payments, that means we do not need to process that type of event in our microservice.</p><p>In the Filters section, we can name which type of Events will be delivered to our subscriber:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9RrrmpDVcNVba9hi0KvnNQ.png" /></figure><p>With this we will wrap up this article. We have covered a lot for sure:</p><ol><li>Understood different methods for communication of microservices</li><li>Creation of EventGrid Namespace</li><li>Briefly touching MQTT protocol</li><li>Creating Topics</li><li>Creating Subscribers for Topics</li><li>Exposing our localhost port to make it publicly available by using NGROK</li><li>Looking at the execution of the code, (is it really asynchronous)</li><li>Analyzing Graphs on Azure to see how our events behave</li><li>Introduction to filter on wire feature on the EventGrid service</li></ol><p>If you liked the content, you can react with claps. Stay connected by following me for more interesting articles!</p><p>Thanks for reading!</p><p>As always, good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88acff7553d0" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/intro-to-communication-between-microservices-azure-eventgrid-88acff7553d0">Communication between Microservices with Azure EventGrid</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to AI: Expert Systems]]></title>
            <link>https://towardsdev.com/intro-to-ai-expert-systems-d12c4cb6ac06?source=rss-18e7760e999a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d12c4cb6ac06</guid>
            <category><![CDATA[expert-systems]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[knowledge-base]]></category>
            <dc:creator><![CDATA[Tarik Berkovac]]></dc:creator>
            <pubDate>Thu, 09 May 2024 09:39:47 GMT</pubDate>
            <atom:updated>2024-05-14T15:17:46.308Z</atom:updated>
            <content:encoded><![CDATA[<p>You have a colleague who is great at work but is busy all the time. We could say he is an expert. It would be great if we could have one more of him.</p><p>To preserve his knowledge and to make a machine know everything that he knows in a specific domain, we would create an expert system.</p><p>First thing when we are making Expert systems we need to focus on what specific domain of knowledge will the Expert system be based on, and then when we pick the domain that we try to automatize we need to choose how we will store our knowledge.</p><p>Knowledge can be represented in many forms:</p><ul><li>Rules, Frames, etc</li></ul><p>In this article we will focus on the Rule Based Expert Systems, that means knowledge is represented as rules.</p><p>Rules are represented in this form:</p><p>IF … THEN …</p><p>So let’s say we have a doctor who is very experienced in the diagnosis of cancer.</p><p>so to simplify we will use letters instead of sentences in an example. We will create some rules:</p><p>IF A THEN B <br>IF B THEN C<br>IF C AND T THEN K</p><p>Let’s take a closer look at the first rule. Its full sentence could be like:</p><p>IF person_is_coughing($x) THEN person_is_sick($x)</p><p>We are making two predicates, person_is_coughing and person_is_sick and they both take the same person name as an argument.</p><p>If we have person_is_coughing(“Bob”) that is considered a fact.</p><p>Both Rules and Facts make a Knowledge Base.</p><p>Okay, when we interviewed the Doctor we got these rules, and from the patient&#39;s records, we can get facts. Now when we have written them in this IF:THEN form the next main part of the Expert System is the Inference Engine.</p><p>As it’s name suggests, engine is the thinking part of the Expert system.</p><p>The simplified bigger picture of how would our system look like is this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_bi5GlOj4lN4WmsdLhRFxg.png" /></figure><p>We have talked a bit about the engine, and the Knowledge part, Let’s now introduce the User and API parts.</p><p>The user is any non-expert person who would like to get a conclusion for his symptoms (facts that he already knows).</p><p>We need to give it some specific facts, by which the Inference engine will make conclusion. For example, we have a non-expert person who would like to use our system. He needs to give some information to the expert system.</p><ul><li>The “Bob” is coughing</li><li>The “Ben” breaths hard</li><li>The “Jack” coughs blood</li></ul><p>For example, those will be translated to:</p><p>A — coughing<br>B — breathing hard<br>C — coughing blood</p><p>And these informations are stored as facts:</p><p>person_is_conghing(“Bob”)<br>person_is_breathing_hard(“Ben”)<br>person_is_coughing_blood(“Jac”)</p><h4><strong>Now let’s discuss the Inference Engine.</strong></h4><p>The engine works in Match-Resolve-Act Cycles:</p><ul><li>Pattern matching (choosing which rules are possible to use)</li><li>Conflict resolving (many rules can be applied to one )</li><li>Consequent activation (applying rule, and then adding after THEN part to new fact)</li></ul><p>Inference Engine has one big TO-DO list which is called Agenda. It consists of many rules, which are loaded from the Knowledge base to the Agenda in the Pattern matching phase. Then when we have applicable rules in the agenda, we need to choose one specific rule to be applied.</p><p>Let’s visualize that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nK3YEdyblSRzXO5PC8DjBw.png" /><figcaption>We have added an activating condition but did not connect it to anything for now. Keeping it simple for now.</figcaption></figure><p>The last step in the picture is doing conflict</p><p>When working with conflicts there are a few ways to resolve them by choosing:</p><ul><li>The first available rule</li><li>The most specific rule, for example if we have on our agenda<br>1) IF A THEN D<br>2) IF A AND B THEN C<br>we will choose the second rule because it is more restrictive</li><li>Rule with highest priority, when declaring rule we would also need to specify it’s priority, by declaring for example number from 1 to 100, 1 as lowest priority, and 100 as the most priority. (We will not use this as it requires additional info of priority to be stored in the Knowledge Base)</li></ul><p>And many more, these are just the most popular ones.</p><p>Each option has its own advantages and disadvantages.</p><p>When the rule is applied it might create a new fact specific to this case.</p><p>Let’s connect now 2nd and 3rd part of the cycle (Conflict resolving and Activation). To do that we will need to introduce a new part of our knowledge base (case-specific facts):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F0Zkzb3Sy5lYtq2XeOY_oQ.png" /></figure><p>New facts that are specific to the Query being executed are called Specific and they are considered to be in short-term memory, not included in the original (Knowledge base).</p><p>So a Knowledge Base now has long-term memory in which rules and facts generally don’t change, and short-term memory which is case-specific.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*akl_uie37p_5EArXnLFQnQ.png" /></figure><p>By this sequence of steps, we have applied only one rule to the fact that we have, but in fact, in each cycle, we will look for all possible combinations of facts that could be pattern-matched to corresponding rules and then choose just one rule.</p><h4>Let’s introduce the last part of the puzzle. Questions!</h4><p>Suppose we have a lot of facts, but by pattern matching, we cannot find any rules to be applied, and we didn’t prove or disprove our hypothesis. Then we introduce questions.</p><p>Questions are predefined in the Data, and by answering them user can add new case-specific fact. In combination with existing case-specific facts might be able to pattern-match on a rule.</p><p>Now you might think about how the user can answer in a way that it makes suitable for facts/rules. It’s simple, we will predefine answers, and display answers in the form of a list in a dropdown, yes/no or true/false questions, enter a number, etc. The point is to give users a limited way to input data needed to create a fact.</p><p>We can make such a set of questions that will exit the program nicely or help the program prove its goal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WlsqxC7VhnTU6FD0aqougg.png" /></figure><p>We have introduced a minimal number of parts of an expert system that is needed to make it fully functional.</p><p>This serves as an introduction to Rule-Based expert systems. In the next article, we will introduce 2 ways of proving a hypothesis with examples, and also PyKE, a knowledge expert system written in python.</p><p>If you liked the content, you can react with claps. Stay connected by following me for more interesting articles!</p><p>Thanks for reading once again!</p><p>As always, good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d12c4cb6ac06" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/intro-to-ai-expert-systems-d12c4cb6ac06">Intro to AI: Expert Systems</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PgAdmin 4 Docker container and Data Seeding EF Core]]></title>
            <link>https://towardsdev.com/pgadmin-4-docker-container-and-data-seeding-ef-core-ba8f9259ccc0?source=rss-18e7760e999a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba8f9259ccc0</guid>
            <category><![CDATA[pgadmin-4]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[dataseeding]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Tarik Berkovac]]></dc:creator>
            <pubDate>Sun, 05 May 2024 17:39:37 GMT</pubDate>
            <atom:updated>2024-05-06T14:45:06.671Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the applications that lets us manage PostgreSQL is PgAdmin 4.</p><p>We can download it from this <a href="https://pgadmin.org/download/">link</a>.</p><p>In this article, we will not do that, but we will create a Docker container that will be running on our machine. We will spin it up with our backend project and database to have a fully functional application that starts with just one command: docker compose up.</p><p>Let’s take a look at where we are at with our docker-compose file:</p><pre>version: &#39;3.8&#39;<br>services:<br>  web:<br>    image: medium-books-api<br>    container_name: medium-books-api_c<br>    build:<br>      context: .<br>      dockerfile: Dockerfile.web<br>    ports:<br>      - 5075:5075<br>    environment:<br>      - ASPNETCORE_ENVIRONMENT=Development<br>    depends_on:<br>      db:<br>        condition: service_healthy<br>  db:<br>    image: medium-books-db<br>    container_name: medium-books-db_c<br>    build:<br>      context: .<br>      dockerfile: Dockerfile.db<br>    ports:<br>      - 5435:5435<br>    environment:<br>      POSTGRES_USER: postgres<br>      POSTGRES_PASSWORD: secretpassword<br>      POSTGRES_DB: postgres<br>      PGPORT: 5435<br>    volumes:<br>      - ./postgres-data:/var/lib/postgresql/data<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &quot;pg_isready -U postgres&quot;]<br>      interval: 10s<br>      retries: 5<br>      timeout: 5s</pre><p>We have two services, web and db.</p><p>We will create a new service for our service through which we will manage our database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JhDmf27PpH-GVFZdJuUsnQ.png" /></figure><p>So we need an image, on which this service will be based. We don’t have a Dockerfile for pg-admin, so we won&#39;t need a build section. We can search on Google for PgAdmin 4 Docker image, and we will find:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2dyNtRDQfU5c3w30oy_c5w.png" /></figure><p>As we can see it’s the official image of pgAdmin 4. So let’s use it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8mYY2nbwWqnGLbnjvpF-lA.png" /></figure><p>It would be running inside a container, so to access it from our host machine, we would need to do some port mapping.</p><p>Also, we know that all these applications have some way to log in to that. It is the easiest to see what is required for the application to run. Let’s go to the official <a href="https://www.pgadmin.org/docs/pgadmin4/latest/container_deployment.html">documentation</a> of the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4nbV4959h47bHqY1gmNIWw.png" /></figure><p>We are looking at the documentation pg the pgAdmin 4 version 8.6 (at the time of writing it is the latest version).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eXB7NY-0qtdT_KDJPjIg7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*39VzdVfFtZ8fo0YidCabUQ.png" /></figure><p>Required variables should be set.</p><p>So we will add an environment section, with corresponding variables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1_8iUMfS4tJBd0XFRlzdA.png" /></figure><p>If we look closely at the documentation here is the part:</p><blockquote>PGADMIN_DEFAULT_PASSWORD or PGADMIN_DEFAULT_PASSWORD_FILE variable is required and must be set at launch time.</blockquote><p>So by setting the PGADMIN_DEFAULT_PASSWORD, we are not required to set PG_ADMIN_DEFAULT_PASSWORD_FILE. For now, we will set the default password, but later on, we will cover the default password file.</p><p>With this, our pgAdmin image is completed. Let’s discuss the sequence in which these services should run.</p><p>Web API depends on:<br>- database</p><p>pgAdmin depends on:<br>- Database</p><p>The database does not depend on anything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_E1w_WUGDxwDYY5d_1Sv1Q.png" /></figure><p>One last thing is to map ports between the container and our host machine.<br>To know on which port is our app running inside the container we will take a look at PGADMIN_LISTEN_PORT and PGADMIN_ENABLE_TLS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ScU94r6ozAEcflLolbqLTg.png" /></figure><p>TLS is shorthand for Transport Layer Security. If it is enabled it means that the container does not receive or send plain data (e.g. message), but encrypted data is sent or received (e.g. dks20dsmd2). This way any potential hacker cannot see data transferred by sniffing the network.</p><p>To encrypt or decrypt data that is coming out our coming into our container we need some rules, and those rules are set by having a server certificate and a server key on our host machine. Then map their file paths to the path of the container (volume mapping):</p><blockquote>When TLS is enabled, a certificate and key must be provided. Typically these should be stored on the host file system and mounted from the container. The expected paths are /certs/server.cert and /certs/server.key</blockquote><p>TLS is not enabled by default, and we will not override it, so our pgAdmin will run by default on port 80 in the container. We can map it to any free port on our host machine, let’s choose 8080.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LFHg5AyspNZrQc1IndSebQ.png" /></figure><p>Great, with this set up we finished setting up our pgAdmin4 service.</p><p>Let’s note again, some key points:</p><ul><li>Each service is running on an address and on a port</li><li>Address and port are usually predefined if not set in the configuration (yaml) file</li><li>When sending data over the network potential hackers can see unreadable encrypted data or exact data that we are sending (plain data)</li><li>Many services require some environment variables to be set up in the configuration so it is important to go over the documentation of the service to see which environment variables should be set</li><li>We need to think if our service depends on another service to be fully run first, so we don’t get any potential errors/problems</li></ul><p>Let’s run:</p><pre>docker compose up</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vk8gv84-LakjV3Wz5LFtTA.png" /></figure><p>We have a problem because A in pgAdmin4 is uppercase. Let’s fix that to lowercase and run the command again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZJ4astKl7mRNVv8YwSIyJw.png" /></figure><p>We see that it started pulling image, and after the image is pulled we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*spGaeemQ_6sj9NC5qTYRuw.png" /></figure><p>We previously had images and containers for web and db, and they just went from stopped to running, so they are not created. And we see that pgAdmin4_c container is created and running. Also it’s listening on the <a href="http://[::]/">http://[::]:80</a> (80 port in the cointar).</p><p>Let’s take a look at images and containers in the Docker desktop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpQ2usr4_DxUQxn5D8ynVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*13pN7hjooXbg9LYD5yjGOQ.png" /></figure><p>Great we have everything up and running. Let’s go to localhost:8080</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oFwpYXh8bdeupUtP5TDKZg.png" /></figure><p>Now we will enter email address and password which we set up as default in the docker-compose.yaml file (admin@mail.com, admin).</p><p>After we are successfully logged in we will see very familiar screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UD7VjyLb8m2MDxRA0G6OHQ.png" /></figure><p>Let’s connect to our server instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMSUqGU5S_7p8S6Lhx2LIA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QHzDNXDxIZ8f7gjqDUeabQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQtPlWmbu0XbCJiepvMx2A.png" /></figure><p>When we write localhost it infact mean 127.0.0.1 IP Address. Let’s take a look if there is really process running at 127.0.0.1:5435</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xoH89hYfbW1l1Pie7gw5QA.png" /></figure><p>But we need to provide address of the db container. We can simply write db for the host address, and docker will assign right IP address there.</p><p>Let’s change localhost to db and click save:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lByFlpqrW8iB-0PQu2539A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qJ2kOV73yZHUbOqsgeMHqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vabtq7JoQL2Umeyp55P8_Q.png" /></figure><p>Let’s remove the server and try to connect by using IP address of db container: 172.18.0.2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqh5-URUPJ1fTx3VAFhDlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eMDxNNrm6IIvz6bk3FCGtw.png" /></figure><p>And let’s try again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LsLwydOKkbgPwMPr-vJuWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LP1wxRrsoIHjZAI1qL-DRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lP0hPElXBVsCJxni6BMHRw.png" /></figure><p>And we have connected to the same database. So why does this work?</p><p>Docker networking! By starting our services with docker-compose, aside from services created, one default network is created which let’s us communicate between containers.</p><h3>Data seeding</h3><p>Let’s now take a look at Data seeding. If we want to populate tables when migrations are applied we would need to execute some SQL inserts.</p><p>There are many ways to do so, but we will show one using ModelBuilder:</p><p>First in OnModelCreating we call</p><pre>modelBuilder.Entity&lt;TEntity&gt;().HasData()</pre><p>HasData accepts List of the entities as an argument:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLt_3ortb_AniSGparNAJA.png" /></figure><p>We defined a private method, not to write a list of the elements inside the OnModelCreating method.</p><p>We will use a simple “for loop” to generate entities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ofMisW3bo_EN4HApfarZEQ.png" /></figure><p>We will do the same for BooksDbContext:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OoNxkXaH3RSGLYYSFE46Vw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OT2qkru3Lt1lOcrMcRb8CA.png" /></figure><p>Now we need to create migrations for both dbContexts:</p><p>First, we will position ourselves at root of the solution, and then execute:</p><pre>dotnet ef migrations add UsersSeedingMigration <br>  --project &quot;./Users Module/MediumBooks.Users&quot; <br>  --startup-project MediumBooks.API </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iC7u-LnvepFYgDkoL6vAFw.png" /></figure><p>As we have multiple db contexts, we will need to specify which we want to use:</p><pre>dotnet ef migrations add UsersSeedingMigration <br>  --project &quot;./Users Module/MediumBooks.Users&quot; <br>  --startup-project MediumBooks.API <br>  --context BooksDbContext</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_GQBpMrz2Q31o7-L_BXHw.png" /></figure><p>Now we get an error that we need to set the Ids of the entities that we are inserting.</p><p>Let’s fix it by assigning value to UserId:</p><p>We will assign it to index which takes values from one to ten:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P3RcB5B7ggPXEd_hrtrTtQ.png" /></figure><p>We will also update Books, as we will encounter the same problem once again when we try to create a migration for BooksDbContext:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5K_1NAivxLr4xhMmqI__1w.png" /></figure><p>We need to be careful when we are creating these seeding data. We know that AuthorId must be one of the values of the UserId. Even though they are in different schemas and modules, we need to have consistent referential data over the modules.</p><p>Because of that, we are taking only values from 1 to 10 for the AuthorId, simply by taking the remainder when we divide the index by 10, and to that remainder, we add 1. That way we don’t get AuthorId = 0 as an edge case which would not be good.</p><p>Let’s create again migrations for both the Reading Module and Users Module:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TH4LDwSh0HZpEYg4SVsjHw.png" /></figure><p>We can see that we have a newly added UsersSeedingMigration in the Migrations directory, and also we have modified UsersDbModelSnapshot:</p><p>Let’s take a look how our UsersSeedingMigration looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rGi2VDrKv4chAIX1aiLYeQ.png" /></figure><p>And UsersDbContextModelSnapshot now has a builder.HasData which we defined:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9lsWJQ33TZmBpJ-EwrEjOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dtfJ8zs5UESRJd1pJIaaZw.png" /></figure><p>Let’s create a migration for the Reading Module now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1dvAwii6DWE6iKvC910xew.png" /></figure><p>Same as before BooksDbContextModelSnapshot is marked as M (modified):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fvwNiQnyPyRUlPKKdfaFSA.png" /></figure><p>In newly added migration we can see in the up method, inserting Books, and in the Down method code which will be used to delete inserted data if migration is reverted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UbOZW9JUGzDMOFqbHQw9vg.png" /></figure><p>We don’t need to do anything specific to apply those migrations. We have set up that in the Program.cs Migrate method is called when app is run for the first time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BWB723jfvvufnDrWpL2dEg.png" /></figure><p>As in the container, these changes are not taking effect (we don’t have any volume mappings for source code, only volume mapping is for the database), we will need to delete images, but to delete images we need first to delete containers. Then we will build images again and start containers with the command “docker compose up”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2jw-5-6UuDS5Bzs8qXYzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1dsyKQzwDiRAMyzTwEXigA.png" /></figure><p>We will also delete the postgres-data directory, which was mapped to our database container. That way the database will be freshly created with the database container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Vl9igzFPJFIf0F1b4RdSA.png" /></figure><p>Now let&#39;s start fresh:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a_Z1ll62gsu8RCGLnTcoDQ.png" /></figure><p>After the database container is created, it starts creating API container:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p6g0iDpkb9FXvhwS96a5WA.png" /></figure><p>We see at the end of the picture Insert statement for User 1.</p><p>Also a bit down there we can see inserts for the Books:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YrX21YfYQj3kZxKUPuWb1w.png" /></figure><p>Now in the docker desktop we can take a look at our newly created images and containers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u7r6dCd4_sPdqrgta9E16g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oti9AW6O6UVo5yUjCk4InQ.png" /></figure><p>When we click on the marked link we will get an error message in our browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zozcCyNdEiZEAj-YnJaZrg.png" /></figure><p>It is expected behavior because swagger is not available at route / . It is available on route /swagger/index.html:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lvKZY0BM1A7JS84DsozmuA.png" /></figure><p>Let’s try to get a user with Id 1 and book with Id 1, to see if it works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r1Xwv-yl4K1Cu_AibMOAkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OxIcOMrvTwi3S2eJ08Ex2A.png" /></figure><p>GREATT IT WORKS!!!</p><p>Thank you for reading and coming this far!</p><p>We have been on a whole journey to make our application dockerized, so anyone can simply run an application without any problems with the command “docker compose up”. It’s very powerful as you can see.</p><p>The source code is available at: <a href="https://github.com/tberkovac/ModularMonolith.Medium">https://github.com/tberkovac/ModularMonolith.Medium</a></p><p>This code needs some more tuning, but the main point of it is to easy understand main concepts. I highly encourage you to make the docker compose file for your services and share with us your progress.</p><p><strong>The mini series concluded with this article:</strong></p><p><a href="https://medium.com/towardsdev/introduction-to-docker-e1eefd9a4970">Introduction to Docker</a><br><a href="https://medium.com/towardsdev/docker-commands-and-multi-stage-build-2ed9feddf954">Docker commands and Multi-Stage Build</a><br><a href="https://medium.com/towardsdev/docker-compose-and-postgres-container-a6eab197cbd6">Docker compose and Postgres container</a></p><p>If you liked the content, you can react with claps. Stay connected by following me for more interesting articles!</p><p>Thanks for reading once again!</p><p>As always, good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba8f9259ccc0" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/pgadmin-4-docker-container-and-data-seeding-ef-core-ba8f9259ccc0">PgAdmin 4 Docker container and Data Seeding EF Core</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker compose and Postgres container]]></title>
            <link>https://towardsdev.com/docker-compose-and-postgres-container-a6eab197cbd6?source=rss-18e7760e999a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6eab197cbd6</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Tarik Berkovac]]></dc:creator>
            <pubDate>Fri, 03 May 2024 14:07:51 GMT</pubDate>
            <atom:updated>2024-05-05T17:48:04.351Z</atom:updated>
            <content:encoded><![CDATA[<p>We will continue improving our process of dockerization of the MediumBooks.API project, which we introduced in the Modular Monolith Architecture series.</p><p>Currently, we have Dockerfile which builds Docker Image for our Web API project.</p><h4>This article consists of 2 parts:</h4><ul><li>Setting up a Postgres container</li><li>Setting up docker-compose (scroll down to the <strong><em>Docker Compose</em></strong> title if you are only interested in this part)</li></ul><h3>Postgres container</h3><p>Firstly let’s solve the problem of missing database in our application:</p><p>We need a Dockerfile for our database. As we are using PostgreSQL locally, and EFCore uses PostgreSQL dependency, we will create a Dockerfile to spin up PostgreSQL.</p><p>Docker supports many different Dockerfiles in the same directory. So we will rename our Dockerfile that creates an image for Web API to Dockerfile.web, and we will create a new Dockerfile.db, for our PostgreSQL database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M8voSSD8tE9RV285e7r-eQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iEmwa7Kp0sLb1Hk9fgyFsQ.png" /></figure><p>We want to use Postgres image as our base image, but then what? We don’t need to build any code or copy something inside a new directory. We know that the database runs on a port inside a container so let’s expose one port. Postgres default port is 5432, but if we use Postgres locally probably that instance will use 5432 port on our host machine. Sure, we can run it on the 5432 port in the container, and then map to some other port on our host machine, so let’s do that:</p><p>And that is in fact how our Dockerfile.db looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YsQEezXGyaMA_lFyY7OSnQ.png" /></figure><p>Let’s give it a run:</p><p>First, we will check existing images by using:</p><pre>docker images</pre><p>Second, we will build our Dockerfile.db with the docker build command:</p><pre>docker build -f Dockerfile.db . -t postgres_db</pre><p>the -f flag stands for file name and then we provide Dockerfile.db<br>the -t flag stands for tag, or our Docker image name (postgres_db)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ADdKg8rxK181NaFnCfpyjg.png" /></figure><p>And when it’s fully downloaded it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aErmDSoYAXkfOnpvDd3yVw.png" /></figure><p>Let’s once again list all images:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*naV_TQkAXLy-rFdBh5ExDw.png" /></figure><p>And here it is, great!</p><p>Now let’s run it as a container. Note that we have exposed a port, so we will do some port mapping.</p><pre>docker run -p 5435:5432 postgres_db</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ke_AKGLyBWwX9UMRUr6vpA.png" /></figure><p>We see that we need to set a password for the super user:</p><pre>docker run -p 5435:5432 <br>           --name postgres_c <br>           -e POSTGRES_PASSWORD=secretpassword <br>           postgres_db</pre><p>We have added a flag name to name our container, and flag e to set POSTGRES_PASSWORD (password of the super user).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u07LTilOZGP4oKlXYmjqOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bkc5aSelFXL37rUqJkBbTA.png" /></figure><p>We have run command without -d flag, and that means we cannot use this terminal anymore, as it is running our postgres container. If we exited it our container would exit as well.</p><p>Let’s run our PgAdmin4, and connect to this database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UtXZZqoHFFXggB_ukf1WoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c6WGZRsAAqRS0bjSOw_QDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rOVCkQI5gm_l_9ugfKFYaA.png" /></figure><ul><li>The host name/address is localhost because we are running it on our machine.</li><li>The Port is 5435 because we mapped -p 5435:5432, in the container it is running on 5432, but on our host machine it is 5435</li><li>As we are logging in as super user, username is postgres by default.</li><li>We will use super users password. In our case “secretpassword”.</li></ul><p>Let’s click on save. After that we can see our new server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3n06VoiU2omh0-ZJ6ALMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PuK8VkJ3FFtgV-XQ9e6t4g.png" /></figure><p>It has only the default Postgres database in it. Now we need to connect our backend to this database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J3ZsCZfsCoGQkPkVS_go0Q.png" /></figure><p>As we have only one centralized connection string, we can just modify it here.</p><p>To create a Database, we need to apply migrations on the startup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hu6S7P2Ro9phasg14zhbdA.png" /></figure><p>We will create a new scope of Services, and then get Required db contexts.<br>This is just getting the service from dependency container. If you want to learn more about that check out this <a href="https://medium.com/towardsdev/dependency-injection-service-container-and-resolver-2757da19d972">article</a>.</p><p>Let’s start our application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XoMl5zmxSGewIyUze2lSeQ.png" /></figure><p>We see that it executed some SQL, in fact, it applied all our migrations and there is much SQL code that we will not show here.</p><p>Let’s go to PgAdmin to see if it really created those tables in the database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u5_UgEK7U5kouqQ1t90FeA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zoauNqSMeSqex2SZTRdT8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qfPjH7d0ZDsQXN8lct7ohg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0mAOXuC4GBbUtUxBZ9m_jA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GvtDtbZ1R6T1Y7KDQ6YzCQ.png" /></figure><p>Let’s stop our container now and start it again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DcvrWRAh763k-LrUHZYa2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T9Zw9DC0f7LIN3nu88igVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G1JGzexy6j1lV4jWtKsnIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sm7dQLmN7bC_dii2pFz64w.png" /></figure><p>We see that we still have schemas defined by the first run of the application. Data is saved in a container even if it is stopped.</p><p>Now we get to the question, what would happen if we deleted the whole container, and then create it again based on the same image, and run the app again to apply migrations?</p><p>Let’s first insert one user so our database is not empty:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TiVfcvH77xroM1uwReCbA.png" /></figure><p>Now let’s delete our container:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PmAJTaesgo0roTYQ_IuIrg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PwKtqxeQ3jEiuFesiLILcw.png" /></figure><p>Here we are warned of potential volumes being deleted. Every database needs to store database files somewhere physically on the disk. So regarding those, anonymous volumes mean the db files are stored somewhere on the disk which we did not explicitly tell to store.</p><p>Let’s create a container again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JNmARtWH6yD9y5EdISVkxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UIwmNrq-PjwDK83ncAdXDw.png" /></figure><p>Here it was looking for database modulith-medium-books but it couldn’t find it. But the real question is why does it need it?</p><p>Here we can open files section of the container and look at all files that it has.</p><p>There are some notes, for example volume:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l0rsOzImOp79CoJYFeGBhw.png" /></figure><p>This data directory is empty, and we were warned that upon deletion of the container, this data will be deleted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BAdZs_dUuGvF2TX1gu--Rg.png" /></figure><p>We have Note modified, which tells us that we did something with it (deleted some files on deletion of the container).</p><p>So that’s making a problem.</p><p>If we go to Logs, and run it again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1Mp27KoEiSm7CUzjS7t4w.png" /></figure><p>We see that again we lost all files of modulith-medium-books database.</p><p>Let’s remove this container again, and create a new one, but we will tell it to mount our own volume:</p><pre>docker run -p 5435:5432 <br>  --name postgres_c_mountedV <br>  -e POSTGRES_PASSWORD=secretpassword <br>  -v ./postgres-data:/var/lib/postgresql/data <br>  postgres_db</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5d6XOs2SKOXXMtGbM9cbqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9omo4jUZRsXOPKkzdTq7qQ.png" /></figure><p>Still, it was complaining because we don’t have database modulith-medium-books. So let’s once again run our application and migrations will be applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSfsL5vWjgAf9eYue9D5Mw.png" /></figure><p>Now the database is created and it no longer gives FATAL logs. Also, we can see that it is indeed created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MgclUsbDbS2gG41PnrFu0w.png" /></figure><p>Now in Visual Studio Code, we have a new directory postgres-data, and in commit changes 1k + files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6JQGe1YxIqJnXTE38uPgcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4y5OOFUozQRot_7veH01ZQ.png" /></figure><p>All related to our database.</p><p>Now let’s take a look what -v flag did:</p><pre>-v ./postgres-data:/var/lib/postgresql/data</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ew9tuNl235osjZn0GXYm4Q.png" /></figure><p>Instead of the previously used /var/lib/postgresql/data directory in the container now we are mapping it to /postgres-data directory in our project. That way when we delete the whole container, we will have saved database files in our project directory.</p><p>Let’s insert now a new user, delete container and try to run it again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9TI1jUQxr946EcEq4-xdw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c1SlvSFlhlhmzScbalM3dg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M7eeDtdBh-34wcMKShf5pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a1bUQJjarDhcdFLzXyAujg.png" /></figure><p>Now let&#39;s create a new container based on the same image:</p><pre>docker run -p 5435:5432 <br>  --name postgres_c_mountedV <br>  -e POSTGRES_PASSWORD=secretpassword <br>  -v ./postgres-data:/var/lib/postgresql/data <br>  postgres_db</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yCvUnbkcLB0c-NP7Vl3t4Q.png" /></figure><p>And when we open our PgAdmin:</p><p>Enter the super-user password: secretpassword:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*It30E-yKVSOKkc51ZxIWzw.png" /></figure><p>We see that we have our database, schemas, tables, and also data in tables safely stored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*55t-uu5veoplEHxso7480g.png" /></figure><p>Let’s run our application to see if it works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PnubGSRbNAmeoMcxztxdsA.png" /></figure><p>Great, we got the data in the response.</p><h3>Docker Compose Part</h3><p>Now when we want our friend to run the application, we can send him source code with commands to build images and run them:</p><p>For database:</p><pre>docker build -f Dockerfile.db . -t postgres_db</pre><pre>docker run -p 5435:5432 <br>  --name postgres_c_mountedV <br>  -e POSTGRES_PASSWORD=secretpassword <br>  -v ./postgres-data:/var/lib/postgresql/data <br>  postgres_db</pre><p>For Web API project:</p><pre>docker build . -t medium-books-api</pre><pre>docker run -p 5001:5001 -d --name medium-small-container2 medium-books-api</pre><p>That’s a total of 4 commands that he needs to run.</p><p>We can do better!</p><p>Running multiple docker files can be done by using something that&#39;s called docker-compose.</p><p>We will create a docker-compose.yaml file in the root of our solution:</p><p>We need to specify version and services:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YY3la4q_l1e1Aik26iVo5A.png" /></figure><p>Each service is image+container that we have. We named services web and db, but in fact they can be named however we want.</p><p>Indentation in this file is very important so make sure you always tab in once.</p><p>Each service has attributes “image” and “container_name” to specify the Docker image name and Docker container name:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QA_7Y4q8hvHAiVmKNvFC3A.png" /></figure><p>Now when we build a service web we will have this: <br>- image name: medium-books-api<br>When that image is run it will have the container name:<br>- medium-books-api_c (c stands for container)</p><p>Now when we build a service db we will have this: <br>- image name: medium-books-db, <br>When that image is run it will have the container name:<br>- medium-books-db_c (c stands for container)</p><p>Build and run are together executed by a command:</p><pre>docker compose up</pre><p>To build the Image we need Dockerfile, but we haven&#39;t specified Dockerfiles yet. So let’s do that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*11Q0FLjV4xRATjCclbJebw.png" /></figure><p>We have added a part for building in which we specify which Dockerfile will be used for Image creation. Also, we specify the context to the current directory.</p><p>Great now that we have Dockerfiles, let’s take a look at what we did when we ran the images from the terminal:</p><pre>docker run -p 5001:5001 -d --name medium-small-container2 smaller-image</pre><pre>docker run -p 5435:5432 <br>  --name postgres_c_mountedV <br>  -e POSTGRES_PASSWORD=secretpassword <br>  -v ./postgres-data:/var/lib/postgresql/data <br>  postgres_db</pre><p>So we need to map ports, let’s first do that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ld06Xfg5QqxLfq3EfKE-tA.png" /></figure><p>We will make changes in Dockerfiles as well to expose the right ports:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0a1ttnUU9urlr-BAfot4fQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_5Z-XUryVU08DQIBhI4sQ.png" /></figure><p>When we run earlier Web API project, to apply migrations and to see swagger, we need to tell it that the environment is Development. But also we need to make sure that our backend is run after the database is run. We do that by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ERpzFUsWbTvbR390zvFHJA.png" /></figure><p>We also need to specify values for our database such as Postgres user, password, port, etc as well as volume mounting to preserve our database files on the deletion of the container. We do that in the environment and volumes sections:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KYjYhEoCyIrpn9_oC6M3qw.png" /></figure><p>In the end, our docker-compose looks like this:</p><pre>version: &#39;3.8&#39;<br>services:<br>  web:<br>    image: medium-books-api<br>    container_name: medium-books-api_c<br>    build:<br>      context: .<br>    ports:<br>      - 5075:5075<br>    environment:<br>      - ASPNETCORE_ENVIRONMENT=Development<br>    depends_on:<br>      - db<br>  db:<br>    image: medium-books-db<br>    container_name: medium-books-api-db_c<br>    build:<br>      context: .<br>      dockerfile: Dockerfile.db<br>    ports:<br>      - 5435:5435<br>    environment:<br>      POSTGRES_USER: postgres<br>      POSTGRES_PASSWORD: secretpassword<br>      POSTGRES_DB: postgres<br>      PGPORT: 5435<br>    volumes:<br>      - ./postgres-data:/var/lib/postgresql/data</pre><p>One last thing that we need to do is to copy appsettings.json files in the container from our source code. Those files are used on runtime, and if we don’t include them we will have a problem of missing connection string.</p><p>appsettings.Development.json will be used if the environment is Development.</p><p>For the host, we will put the name of the service from docker-compose which will build and run Postgres container. Because of that, we put Host=db. The other part of the connection string is already familiar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AJSQVQjPuslX4Ka_upmYxg.png" /></figure><p>Now let’s open the terminal and run:</p><pre>docker compose up</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DLPza0fLP3NhJYbkzxcYUg.png" /></figure><p>We can see in logs, that our Postgres image was cached (pulled this image many times). We are currently building our web project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e_-2PdRQACrhM5qkHVgmwA.png" /></figure><p>We see that after a successful build, we copied the appsettings.json and appsettings.Development.json files to the final image. Then docker saves the image and names it to docker.io/library/medium-books-api.</p><p>In docker.io/library are those images that show up in the Docker Desktop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*798aeyU-67SX-c66qZImNw.png" /></figure><p>(I have deleted all other images because I did not need them)</p><p>Now from the previous picture of the terminal, we can see that it created 2 containers for our images, and created a network as well.</p><p>Now let’s see what this yellow output means:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6d1mkSH61GPki6zV-97aZA.png" /></figure><p>It means that it’s starting to initialize the database, But before the database was ready to accept the requests, our api_container started to run. That is not good, because we need to apply migrations…</p><p>Let’s take a closer look at our docker-compose file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v8laI-q0TstYp8BKkc3gUg.png" /></figure><p>We have depends_on in our web service, but that depends_on means container db will start before starting of the web container.</p><p>But the starting process takes time, as we can see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQrTkU7PfyGoxPBEAvyHeA.png" /></figure><p>Db_container was running before API_container but did not finish creating the server. When our API_container wanted to apply migrations, it couldn’t, because the database server was not up and running.</p><p>To fix that we will create health checks on the database container. Health checks in fact look if the db server is ready to accept connections. Then we will say that API_container depends on db and additionally depends on db_container which is healthy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sAMDtWE49F_XYogOuwoVvg.png" /></figure><p>Healthchek consists of:<br>- a shell command that we will run pg_isready -U postgres<br>- an interval in which the command is run <br>- number of retries <br>- timeout before it tries again</p><p>Let’s delete images and containers that were created, and postgres-data directory from our project.</p><p>Now let’s run again “docker compose up”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_VRxR39pQhLtrYNYVCboxw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p_QQNHPsYXpZL5QyrlkQTw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BRkqvHh3MmNTYkTfzfzbBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BtwA6oK4-YBuUEUcjSFV8A.png" /></figure><p>Well, we see now that the API container waited for the DB container to start running (db server is ready to receive requests), and just after that it starts to run. We see that migrations were applied and that our app is running on port 5075.</p><p>We can check images in the docker desktop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*octYbwva97lRcchxG_Oq0g.png" /></figure><p>As well as containers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A34cF0vZu2dTWWCPwaL3zA.png" /></figure><p>They are combined together, as we ran them with one docker-compose command.</p><p>Now, let’s connect to the database from PgAdmin and insert one user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vqXnGrfPPp96Q_JutFMpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_9Ges_QzFZZ11VhruO6saQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0phnfnLPCrOfU0Wq8pnRhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ynqJcBAxKG7W3UezLf7Ujg.png" /></figure><p>We will just click okay, and ignore this warning. We see that we have our database on the left so it’s all good.</p><p>We will insert one user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ox47J5oSOOM8x2mM-KTYTQ.png" /></figure><p>Let’s go to swagger and make a GET request for the user with id 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DJYu3jNzLJSx2p1RZsyoGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tDqTx3XtDy9xV7hLqxbnIQ.png" /></figure><p>AND IT WOOORKS!!!</p><p>This is huge what we accomplished so far. We learned so much. I want to thank you so much if you came this far, as this was my longest article for now.</p><p>We understood port mappings better, mounting volumes, healthchecks, and how we can solve problem when one service depends on other (running some containers in specific order). Also we now understand better how and where files of the database are saved, and we can see that it is not somewhere in the air, but it’s safely store on disk.</p><p>We also learned how do we load connection strings from appsettings.json file. We understood why we need to copy it with our DLLs in the final stage of our build.</p><p>Now back to our story:</p><p>Throughout this series, we wanted to help our friend run our application with just one command without installing any dependencies.</p><p>Let’s see what we have set up so far:<br>- Backend Web API<br>- Postgres Database server</p><p>And in this article, we used PgAdmin to insert the data into the database, which is not good. Our friend would need to install PgAdmin as well and we want to make it easy for him to manage the database.</p><p>That’s exactly what we will do in the next article!</p><p>We will make a new container with an application to manage Postgres. Also aside from Applying migrations on the first start of the project, we will insert some default data in our tables so they are not empty. That is called seeding data, and we will learn more about it.</p><p>Available at:</p><p><a href="https://medium.com/@tberkovac/pgadmin-4-docker-container-and-data-seeding-ef-core-ba8f9259ccc0">PgAdmin 4 Docker container and Data Seeding EF Core</a></p><p>Source code: <a href="https://github.com/tberkovac/ModularMonolith.Medium">https://github.com/tberkovac/ModularMonolith.Medium</a></p><p>If you liked the content, you can react with claps. Stay connected by following me for more interesting articles!</p><p>Check out other articles!</p><p>As always, good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6eab197cbd6" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/docker-compose-and-postgres-container-a6eab197cbd6">Docker compose and Postgres container</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker commands and Multi-Stage Build]]></title>
            <link>https://towardsdev.com/docker-commands-and-multi-stage-build-2ed9feddf954?source=rss-18e7760e999a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ed9feddf954</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[multi-stage-builds]]></category>
            <category><![CDATA[docker-desktop]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Tarik Berkovac]]></dc:creator>
            <pubDate>Wed, 01 May 2024 17:37:23 GMT</pubDate>
            <atom:updated>2024-05-03T14:10:03.080Z</atom:updated>
            <content:encoded><![CDATA[<p>In Introduction to Docker, we covered topics such as what a Docker image and a Container are. We wrote a simple and easy-to-understand Dockerfile. Based on that Dockerfile, we build an image and run it from the Docker Desktop.</p><p><a href="https://towardsdev.com/introduction-to-docker-e1eefd9a4970">Introduction to Docker</a></p><p>This part will be dedicated to downsizing our final image.</p><p>Our current Dockerfile:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MSz3y5q_peW-xBpvgFLXdg.png" /></figure><p>Steps that are defined in the Dockerfile:</p><ul><li>The base image contains .NET 8 SDK, on top of some operating system.</li><li>We copy our code in /app directory in the container</li><li>We build source code in the container</li><li>Lastly, we run our application on the exposed port 5001</li></ul><p>We will mostly work with terminal so let’s introduce a few of the most important commands:</p><pre>docker build .<br>docker build . -t tag_name</pre><p>These commands build a docker Image based on the relative path of the Dockerfile.</p><p>Let’s open our terminal and run the first command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YzukCXppJ9EyuBheDwJo3w.png" /></figure><p>To see the images we can use command:</p><pre>docker images</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1WkdSLdFVUK7sa5ln0wlaw.png" /></figure><p>The first image is the one that we just created. We can see that it has no name and no tag. It is uniquely defined by image id.</p><p>Let’s now run the second command (the one with -t):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E-QXHC-oYRBpwKb20RoIXQ.png" /></figure><p>Nothing was changed, so docker determined that these 2 images are same and just overridden the first image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z26x7HxIW2BN1611dFANjg.png" /></figure><p>Let’s create an image with a different name now, but based on the same Dockerfile (no changes in source code):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LR_8axONOKBzoRULUBE-5g.png" /></figure><p>We see that we get a new image.</p><p>To delete an image we can use 2 commands:</p><pre>docker image rm image_name<br>docker image rm image_id</pre><p>Let’s delete one with image-with-name-2 by name:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BN_HRMwOkkbd357xySdoAg.png" /></figure><p>Let’s now delete the Ubuntu image by Image ID 07db2ffa22da:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YOfvWGOHYjjIjya_US3TTw.png" /></figure><p>Docker images are great, but to use them we need to run them. By running the Docker image we are creating a new Container based on that image. Instead of going to Docker Desktop when we build the image, we can start a container with the docker run command.</p><pre>docker run image_name<br>docker run image_name -d</pre><p>For the docker run to work, we need to specify the image, based on which container will be created. Also, we can specify the tag -d if we want to delete the container after it is stopped (we will see in a bit command for it).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qoaHuRzqfJT_erAf8X3CEQ.png" /></figure><p>As we can see first command takes over our terminal, and we cannot run any other command. Let’s see if container is created from the Docker Desktop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f5vgHu6DpO5lU0yMjVAoQg.png" /></figure><p>It is indeed created. Container name is eloquent_almeida. So Docker by default gave it some random name.</p><p>Let’s open another terminal and let’s run command</p><pre>docker ps</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s3c2jfLJk31ajRz6RHVkgA.png" /></figure><p>It gave us just one container, not 3 as we have in the docker desktop. This is how it should work. Docker ps returns only running containers. To see all the containers we use:</p><pre>docker ps -a</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U-wP9YRwjXZ6v4hihjlJlw.png" /></figure><p>To stop the container we can use this command:</p><pre>docker stop container_name</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hq71lLEDDpEXbF4isuvzag.png" /></figure><p>We can also use it with a container id instead of a name. We also see that the container still exists, but it is in status Exited.</p><p>Let’s run the same image again but with -d and -rm flags:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAfIOiLeV3XILi1LXAVrnA.png" /></figure><p>It returned the container id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_dUWrLRCjxTcoZmED4GAeg.png" /></figure><p>The -d flag means detached (we can still use the same terminal), and the rm flag is for deleting container upon stopping. So let’s stop our container to see if it will be deleted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oxE_wScXvRlbm_MStYL-7Q.png" /></figure><p>It really is deleted, not just exited. There is no container with id that starts with 7ff.</p><pre>FROM mcr.microsoft.com/dotnet/sdk:8.0<br><br>WORKDIR /app<br><br>COPY . .<br><br>RUN dotnet build<br><br>EXPOSE 5001<br><br>CMD [&quot;dotnet&quot;, &quot;run&quot;, &quot;--project&quot;, &quot;MediumBooks.API&quot;, &quot;--urls&quot;, &quot;http://0.0.0.0:5001&quot;]</pre><p>Now that we understand basic commands from the terminal we can go back to the previous problem.</p><p>We have created a Dockerfile, and when we build the Image it is huge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gF7otjbGyci3_eYOqyqlwQ.png" /></figure><p>We identified that the problem is because the whole SDK is in our Container, but for the .NET application to work only Runtime is required.</p><p>Usually, all other technologies have SDK (software development kit) used just for building into executables and Runtime environment on which those executables will be run.</p><p>It would be great if we can somehow first build our application, and then just copy executables in the container which only has runtime.</p><p>It is exactly what we will do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aoda_EKgWKv19xGzRIG-kg.png" /><figcaption><a href="https://learn.microsoft.com/en-us/dotnet/architecture/microservices/net-core-net-framework-containers/official-net-docker-images">https://learn.microsoft.com/en-us/dotnet/architecture/microservices/net-core-net-framework-containers/official-net-docker-images</a></figcaption></figure><p>We will add another FROM, but we will use the runtime image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dLoe5iGOFAonBO9xTn-4yQ.png" /></figure><p>Adding new FROM modifies will reset everything done before it. So final image will only include the latest base image. So we have built an application on top of the SDK base image, but we don’t have those executables in our new base image.</p><p>To bring them to our new image let&#39;s introduce something like variable build which will hold our previous state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iTL0xse3S97kmd6Kgs0DdQ.png" /></figure><p>This “variable” build is called stage. Each FROM keyword is considered as a new Stage. So when we introduce the new FROM on line 9, we can access previous files by using</p><pre>--from=stage_name</pre><p>In our case files in the previous /app directory are accessible by calling</p><pre>--from=build /app</pre><p>Let’s add a name for the final stage as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zJHkXaJbFEh8mSY250ikLA.png" /></figure><p>So we can be clearer when we tell the final stage.</p><p>In the final stage, we are making a new directory /app and positioning ourselves in it. As it is now empty, we will copy all files (including binaries from the previous stage) to /app in the final stage.</p><p>Now essentially we have source code, and executables (same as before in the large image), but instead of having SDK and Runtime, we now only have Runtime which is needed to run the DLL files and it is much much smaller than the whole SDK.</p><p>Let’s build the image again, and compare sizes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YGGjqPPsBy9E5Av9gy9RsA.png" /></figure><p>Wow! We reduced the Image size from 1.28 GB to only 296MB. This can be reduced more but let’s say we are happy with it. Now let’s run our application to see if it works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o3VHflay2wT_LE8R_z4fIw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gnWrO4iNNzkrv2EgKQfbVA.png" /></figure><p>But now we see that dotnet run is part of SDK, but we don’t have SDK.</p><p>We need to run the executable of our Web API project which is:<br>MediumBooks.API.dll</p><p>Let’s modify the Dockerfile:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dWdqY0kg-KTItLKpTy11ZA.png" /></figure><p>Why this particular relative path for our starting project which is MediumBooks.API?</p><p>Let’s see where our desired really is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*RUT58B3WzNMrT_VvwpuENA.png" /></figure><p>It’s not in root of solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*_eV5N3nHOHTWNrbqwbralQ.png" /></figure><p>Bin stands for binaries, let’s see there:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*uFtShelt5xJfHoHAX1ciPQ.png" /></figure><p>And it’s here, we found it!</p><p>Now let’s build the image again, run it, and see if it is running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6vHvj4F76EzlZEvw7Y-rMw.png" /></figure><p>First, we built an image with:</p><pre>docker build . -t smaller-image </pre><p>Then we run it with:</p><pre>docker run -p 5001:5001 -d --name medium-small-container2 smaller-image</pre><p>To this point, we did not discuss flag -p host_port:container_port</p><p>It is for port forwarding, so it maps the port of the container on which the app is running (5001) to our host port 5001 so we can access it from our host machine.</p><p>And we can see that it is running by checking on</p><pre>docker ps</pre><p>Let’s try it out in the browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GGCetuHdxHLx8pFVhD-ktQ.png" /></figure><p>This might be that we did not accomplish our goal, but let’s go to the docker desktop and inspect the logs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qVOCI0bWFBRZEGKM6UJHUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMFjUUDnPF8JT4RJ12xT2A.png" /></figure><p>In fact our Hosting environment is Production, and swagger is enabled only for the Development environment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FkGp1K-1K4xMssFcWHpYXQ.png" /></figure><p>Other routes than swagger/index.html are accessible. Let’s hit one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Qqi_Fsym_1sCrve9SCv_A.png" /></figure><p>For example api/users/1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LoMSpySCDIMV5IZAOLf5Ww.png" /></figure><p>But let’s go once again to logs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YcEsMZmYAqU6TsA1_atuyQ.png" /></figure><p>We see it hit the correct controller, but we don’t have a database set up with this container.</p><p>Source code: <a href="https://github.com/tberkovac/ModularMonolith.Medium">https://github.com/tberkovac/ModularMonolith.Medium</a></p><p>In the next articles, we will set up database, connect it with our container, and build a docker-compose file to run both services simultaneously with one command.</p><p>If you liked the content, you can react with claps. Stay connected by following me for more interesting articles!</p><p>Check out other articles!</p><p>Next article in Docker series:</p><p><a href="https://medium.com/@tberkovac/docker-compose-and-postgres-container-a6eab197cbd6">Docker compose and Postgres container</a></p><p>As always, good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ed9feddf954" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/docker-commands-and-multi-stage-build-2ed9feddf954">Docker commands and Multi-Stage Build</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Docker]]></title>
            <link>https://towardsdev.com/introduction-to-docker-e1eefd9a4970?source=rss-18e7760e999a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1eefd9a4970</guid>
            <category><![CDATA[docker-container]]></category>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[docker-desktop]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[virtualization]]></category>
            <dc:creator><![CDATA[Tarik Berkovac]]></dc:creator>
            <pubDate>Tue, 30 Apr 2024 09:36:16 GMT</pubDate>
            <atom:updated>2024-05-01T17:40:50.640Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you had any problems with versions between Python or Node or .NET or any other programming language/framework that requires different versions? You are not alone.</p><p>Suppose we are developing an application in .NET on our laptop/PC and everything works fine. And your friend really likes your application and wants to run it on his machine. You tell him that the source code is available on GitHub. He pulls the repository and tells you what now? He does not code in .NET, doesn’t know how to start the application, and does not have the tools required for running the .NET application on his machine.</p><p>He would need to set up the whole environment on his laptop, just to run your .NET Web API. That might not be much work for one application, but now you tell him that your application needs PostgreSQL. He tells you that he uses MySQL, and does not have PostgreSQL. So he will need to set it up as well.</p><p>Things get out of hand pretty fast as we are adding more and more dependencies.</p><p>Imagine your friend could run any project you are doing just by running one command. That would be amazing, wouldn’t it?</p><p>The thing that lets us do this is called Docker.</p><p>You can get it from:</p><p><a href="https://docs.docker.com/get-docker/">Get Docker</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GbQcaVyRmyfrRHsxAslKtQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ad_TSM-FP_1j-8L_94fFaw.png" /></figure><p>Installation is pretty simple, next, next, finish like you mostly install any software.</p><p>Make sure that you enable virtualization in the BIOS.</p><p>Now that you have Docker Desktop running:</p><p>Go to Images section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wz5TD7Afwfs4fLJJv0r2Pg.png" /></figure><p>The images section will have Docker Images in it (empty by default, but I have some images already).</p><p>The docker image is just a fancy name for the definition of:<br>- Operating system of our choice<br>- Things that need to be installed on the operating system like .NET that are needed for running our application<br>- Application with steps on how to build and run our application</p><p>This docker image can be run from the Docker desktop by clicking on the run button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qj1xSOtRJWeyYWhsB7nb5g.png" /></figure><p>Once we run the image it is no longer called Image, but it is called Container now.</p><p>Containers run as processes on your host operating system. And they are spun up by the Docker engine. But not to get too technical let’s just say that containers will run as a process on your operating system.</p><p>We earlier said that Images are definitions of OS and some tools that are included with that OS. Same as people develop applications they share source code let’s say on GitHub, people who are making images share images on the DockerHub.</p><p>We have many publicly available Docker images on DockerHub. We can pull them, create our images, and push them to DockerHub.</p><p>Let’s pull one DockerImage for Ubuntu:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*It688SO05Tu6KRKwnHTeAQ.png" /></figure><pre>docker pull ubuntu</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XMWVKVrrFx4no9-JLytsVw.png" /></figure><p>And just like that, we have ubuntu image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsBXvtaPl2Pp5mme1neEXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*leNE_BOss8L2yq5P5ZxePA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_lBMA0a2UJdGUGOgkATASw.png" /></figure><p>It will start a container, and exit instantly. Don’t worry, this is the default behaviour, because containers are meant to host some kind of application in it. Because we just had a plain Ubuntu image with no running application in it, it just exited.</p><p>Let’s pull ubuntu/nginx image which has nginx installed. We know that nginx runs on port 80 by default. So let’s pull it and run it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rcnilJ7_TycP2wXkAu_zYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tf2GgtG3wjtOpm0hHP8LZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BAU03VgcxvihHPs_hnN-Kg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W94VlUMDx-Q1SMPSHVJk9Q.png" /></figure><p>Now it didn’t exit as before, but we see Status running, and mapped ports:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H8MMNr7bal0ZYxECikZdaw.png" /></figure><p>Let’s click on 80:80 to see what happens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*my0cYKFGgfESjkstkUHg4Q.png" /></figure><p>We are taken on default Welcome to nginx page. We did not install Nginx but we pulled an image that defined OS Ubuntu and on that Ubuntu, nginx was installed. So in that container, we have workable nginx!</p><p>This would be great, for example, if we built an Image containing everything, and then instead of giving our friend source code, we would give him that docker image.</p><p>To build a Docker Image we need Dockerfile. We define Dockerfile in the root of our solution. We will continue working on MediumBooks.API solution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ij5YF6N2RuVO29EqVydn2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zC9mfjFnh3ssvE0HM8GoMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UxUGETdUcN1N0uDIchiJtw.png" /></figure><p>All images, need to define the operating system that will be used. Not to reinvent the wheel, we showed how we can get Docker Image for Ubuntu, and Ubuntu with nginx installed. We will get an image for Ubuntu and all tools for .NET development installed. We can search on Google:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J_Mf89Uj_fUOtR3HOypjjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ct6DBjj79xMA3gaSxseCQ.png" /></figure><p>We won’t pull the image, but will just take the name ubuntu/dotnet-aspnet</p><p>In Dockerfile we define OS (our base image) with the keyword FROM:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rb7E5b6ve7x17TzxzPRALQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_4AGOWmXAxB7BdfPv5qpiw.png" /></figure><p>Now we have Ubuntu OS and all tools for .NET. Great!</p><p>Think about this as a whole new machine. What do we need to run our application? Of course source code. Because of that, we need a command to copy all our files from our machine to a new container. We do that by COPY command.</p><p>But before it’s good practice to create new directory/folder, navigate there and then copy source code to that directory/folder. We do that by command WORKDIR:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JyQszLfb7lUaNuRPS_Grhg.png" /></figure><p>Now in the container, we have created an app directory and navigated to it (same as mkdir app &amp;&amp; cd app).</p><p>Then we need to copy our files. As we said earlier we do that by COPY command. To it, we provide 2 arguments, the path from which we copy and the path to which we copy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iHRGPtCJ_TxD3-KVEMz3vg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tSnDuqyeC-aWNwPjhDBtEQ.png" /></figure><p>“.” is for selecting the current directory. The source is “.” because all our code is in a directory which is our Dockerfile in. Dest is “.” because on the container we are currently in the app directory and that is where we want to put all our code.</p><p>After this is done, we have the code needed to run our application, but we first need to build it, and then run it. To include all NuGet packages, we need to use dotnet restore which will download all code that are defined by our packages. After that, we can build our application, and after the build is done, we can run it.</p><p>Let’s restore the solution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PrdikvnkEzRLtW0tsSLrfQ.png" /></figure><p>This is just a visual of how it would be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B3DOI_Wvk2wddVNkxZ4Wgw.png" /></figure><p>Now we need to build it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CIp4VU1FR-c5SkE6ZhFs4w.png" /></figure><p>Again just visual what command to in our terminal, now let’s define it in image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yc72ZnsZHJGr0bt1Z0oUpw.png" /></figure><p>And then we need to run dotnet run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPxihQpZMWtRKGp5Ff9W3w.png" /></figure><p>As we have here more complex command we will use CMD keyword:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OU-rm0sp5oo5grSxL62njQ.png" /></figure><p>Now let’s build our image:</p><pre>docker build -t medium-books-api .</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65BBEHj2u1uuyqxjP4gF4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05CKk_ozuU9pQn1LGa-6jQ.png" /></figure><p>Let’s find another image that includes SDK which includes dotnet build and dotnet run commands, and after some googling, we find that mcr.microsoft.com/dotnet/sdk:8.0 has everything we need. So let’s use now:</p><p><em>FROM</em> mcr.microsoft.com/dotnet/sdk:8.0</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fC4C9BXikSvO6HfRf6j-gw.png" /></figure><p>While the build was happening, we saw that it used dotnet restore, so we removed that command from our Dockerfile. Now we have the Image, let’s run it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2fToPBbXvX-kfx8ir6zM1g.png" /></figure><p>We see that it is huge because SDK is included:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ceiMFOeUzx4vf4y3nl9wMA.png" /></figure><p>We have a problem because we did not expose any ports. To have access to our container through the host machine we need to map ports. Let’s say our machine will run on port 5001 and let’s expose that port. So we will modify our Dockerfile to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MdGZSib-VbSFxdJVJSZtKw.png" /></figure><p>We can expose the port by using the Keyword EXPOSE and then specifying the port number. Also, we have added an urls parameter to specify on which port our app should run.</p><p>Now when we try to run it again we will specify mapping for our ports between host and container 5001:5001, so we can access it from host machine on port 5001 port:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NlDxLrDeNavKOC8I9tIKrA.png" /></figure><p>Great, now it’s running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IqNd6W9c-RkZmtMtxZ3DsA.png" /></figure><p>But when we go to localhost:5001 nothing happens :( <br>But it’s good.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QoAS3nGNAcnIjGwvkYODvw.png" /></figure><p>We didn’t specify route swagger/index.html in which we can see our routes. When we do that it will work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_To64ipaCNjiMSvrl5b_Yg.png" /></figure><p>And just like that we now have image which is wrapping our application, and we can send it to our friend. But can we?</p><p>Let’s try to hit one route:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fYZbSrlYIhKaPN3B92KeAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*11HBIpIkjHBPb9jvu--FZw.png" /></figure><p>The problem is that we cannot connect to database. We did not specify in our docker image anything for installing database.</p><p>Also let’s take a look at our images once again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmeiR3sYDVqHGfppZUeisA.png" /></figure><p>Our image is 1.27 GB in size, which is way more than the Ubuntu image of 98.78 MB. That means we something did not do correctly. The fact is that in our medium-books-api image, we have .NET SDK which includes all libraries and they are huge.</p><p>This image can be much smaller, but we needed to introduce the main concepts of the Docker Images and Containers. It is easy to build up knowledge from now on.</p><p>In the next articles, we will solve a problem for a missing database, and we will reduce the size of our image.</p><p><a href="https://medium.com/@tberkovac/docker-commands-and-multi-stage-build-2ed9feddf954">Docker commands and Multi-Stage Build</a></p><p>If you liked the content, you can react with claps. Stay connected by following me for more interesting articles!</p><p>As always, good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1eefd9a4970" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/introduction-to-docker-e1eefd9a4970">Introduction to Docker</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>