<?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 Ali Ahmad Jan on Medium]]></title>
        <description><![CDATA[Stories by Ali Ahmad Jan on Medium]]></description>
        <link>https://medium.com/@aliahmadjan009?source=rss-e6cad85bc719------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6O47i3mI4vr4bpTd</url>
            <title>Stories by Ali Ahmad Jan on Medium</title>
            <link>https://medium.com/@aliahmadjan009?source=rss-e6cad85bc719------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:36:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aliahmadjan009/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[Understanding Service-Oriented Layer Architecture (SOLA): A Comprehensive Guide]]></title>
            <link>https://aliahmadjan009.medium.com/understanding-service-oriented-layer-architecture-sola-a-comprehensive-guide-a4debe314c1e?source=rss-e6cad85bc719------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4debe314c1e</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[system]]></category>
            <dc:creator><![CDATA[Ali Ahmad Jan]]></dc:creator>
            <pubDate>Mon, 13 Nov 2023 04:30:07 GMT</pubDate>
            <atom:updated>2023-11-13T04:30:07.573Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of software development, architects and developers are continually exploring various architectural patterns to design scalable, maintainable, and modular systems. One such architecture that has gained prominence is the Service-Oriented Layer Architecture (SOLA). This blog will delve into what SOLA is, its benefits compared to other architectures, and scenarios in which it’s most beneficial.</p><h3>What is Service-Oriented Layer Architecture (SOLA)?</h3><p>Service-Oriented Layer Architecture, also known as Service-Oriented Architecture (SOA), is an architectural style that structures an application as a collection of<strong> loosely coupled, independently deployable</strong> services. These services can be thought of as self-contained units that perform specific business functions and communicate with each other through well-defined interfaces.</p><h3>Key Components of SOLA:</h3><ol><li><strong>Services</strong>: The fundamental building blocks in SOLA are services. These are independent, reusable components that encapsulate specific business logic.</li><li><strong>Interfaces</strong>: Services communicate with each other through well-defined interfaces, often using standardized protocols like HTTP, SOAP, or REST.</li><li><strong>Loose Coupling</strong>: SOLA emphasizes loose coupling between services. Each service operates independently, and changes in one service do not directly impact others.</li><li><strong>Scalability</strong>: Services can be scaled independently based on demand. This allows for better resource utilization and responsiveness.</li><li><strong>Discoverability</strong>: Services in SOLA can be discovered and accessed dynamically through service discovery mechanisms.</li></ol><h3><strong>Folder Structure of SOLA with an example:</strong></h3><p>This is the basic folder structure to follow, you can add more folders according to your requirements</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*0Cl5u_0zQj6GW-16QFEU1g.png" /></figure><p>So let me explain you guys with a basic example of <strong>“Creating A New User”</strong> using this architecture</p><p><strong>Note</strong>: I am using Node Js with PostgreSQL as database and sequelize as an ORM</p><p><strong>Step 1</strong>: Go in models folder and a make a new file users.model.js according to your needs</p><pre>const jwt = require(&#39;jsonwebtoken&#39;);<br><br>module.exports = (sequelize, Sequelize) =&gt; {<br>  const Users = sequelize.define(&#39;users&#39;, {<br>    id: {<br>      type: Sequelize.INTEGER,<br>      primaryKey: true,<br>      autoIncrement: true,<br>    },<br>    name: {<br>      type: Sequelize.STRING,<br>      allowNull: false,<br>    },<br>    phoneNo :{<br>      type: Sequelize.STRING,<br>      allowNull: false,<br>    },<br>    gender: {<br>      type: Sequelize.STRING,<br>      allowNull: false<br>    },<br>    email: {<br>      type: Sequelize.STRING,<br>      allowNull: false,<br>    },<br>    password: {<br>      type: Sequelize.STRING,<br>      allowNull: false,<br>    },<br>    createdAt: Sequelize.DATE,<br>    updatedAt: Sequelize.DATE,<br>  });<br><br>  return Users;<br>};</pre><p><strong>Step 2</strong>: Connect your model with database, so that table gets created automatically</p><pre><br>const database = require(&quot;../database/db.config&quot;)<br>const SequelizeMain = require(&quot;sequelize&quot;);<br>const sequelize = new SequelizeMain(database.DB, database.USER, database.PASSWORD, {<br>  host: database.HOST,<br>  dialect: database.dialect,<br>  port: database.port,<br>  logging: false<br>});<br>sequelize<br>  .authenticate()<br>  .then(() =&gt; {<br>    console.log(&quot;Connection to the database has been established successfully.&quot;);<br>  })<br>  .catch((err) =&gt; {<br>    console.error(&quot;Unable to connect to the database:&quot;, err);<br>  });<br>const db = {};<br><br>db.Sequelize = SequelizeMain;<br>db.sequelize = sequelize;<br><br>db.users = require(&quot;./users.model.js&quot;)(sequelize, SequelizeMain);<br><br>sequelize.sync();<br><br>module.exports = db;</pre><p><strong>Step 3</strong>: Once your <strong>Connection to database has been established successfully</strong>, you move towards writing business logic and then creating user</p><p>So in the services folder, make a new file named users.service.js and write the business logic</p><pre>const db = require(&quot;../models&quot;);<br>const Users = db.users;<br>const bcrypt = require(&#39;bcrypt&#39;);<br>const logger = require(&#39;../common/winston&#39;);<br>const userService = {<br>    // Create A New User<br>    createUser: async (req) =&gt; {<br>        // Validate the user data<br>        if (!req.name) {<br>          throw new Error(&#39;Please provide name&#39;);<br>        }<br>    <br>        // Hash the user&#39;s password<br>        const salt = await bcrypt.genSalt(10);<br>        const hashedPassword = await bcrypt.hash(req.password, salt);<br>        userData.password = hashedPassword;<br>        // Create the user<br>        const user = await Users.create(req);<br>        return user;<br>      },<br>}<br>module.exports = userService;</pre><p><strong>Step 4</strong>: After writing business logic in services foler, move towards controller folder and make a new file there named users.controller.js to call that service function you wrote</p><pre>const userService = require(&quot;../services/users.service&quot;)<br>const logger = require(&#39;../common/winston&#39;);<br>const userController = {<br>  // Creates A New User<br>createUser: async (req, res) =&gt; {<br>  try {<br>    const user = await userService.createUser(req.body);<br>    logger.info(&#39;User Created Successfully!&#39;);<br>    return res.status(200).send({<br>      success: true,<br>      message: &quot;User Created Successfully!&quot;,<br>      data: user,<br>      })<br>  } catch (error) {<br>    logger.error(&#39;Error Creating User!&#39;)<br>    return res.status(400).send({<br>      success: false,<br>      message: &quot;Error Creating User!&quot;,<br>      <br>      })<br>  }<br>},<br>}<br>module.exports = userController</pre><p><strong>Step 5</strong>: Now you have to call this function to test, now go in routes folder and create a new route file there named users.route.js</p><pre>module.exports = app =&gt; {<br>    const Users = require(&quot;../controllers/users.controller&quot;);<br>    var router = require(&quot;express&quot;).Router();<br>    // Create a new User<br>    router.post(&quot;/create&quot;, Users.createUser);<br>    app.use(&quot;/api/users&quot;, router);<br>};</pre><p><strong>Step 6</strong>: In your server.js call this route</p><pre>const express = require(&quot;express&quot;);<br>require(&#39;dotenv&#39;).config();<br><br>const app = express();<br>app.use(express.json());<br><br>// parse requests of content-type - application/x-www-form-urlencoded<br>app.use(express.urlencoded({ extended: true }));<br>require(&quot;./routes/users.route&quot;)(app);<br><br>// set port, listen for requests<br>const PORT = process.env.LOCAL_PORT;<br>app.listen(PORT, () =&gt; {<br>  console.log(`Server is running on port ${PORT}.`);<br>});</pre><p><strong>Step 7</strong>: You can test using Postman or frontend</p><h3>Benefits of Service-Oriented Layer Architecture:</h3><h3>1. Modularity and Reusability:</h3><ul><li>SOLA promotes the development of modular and reusable services. Each service encapsulates specific functionality, making it easier to understand, maintain, and extend.</li></ul><h3>2. Loose Coupling:</h3><ul><li>Loose coupling between services allows for independent development and deployment. Changes to one service do not necessitate changes to others, fostering agility and flexibility.</li></ul><h3>3. Scalability:</h3><ul><li>Scalability is achieved at the service level. Critical services experiencing higher demand can be scaled independently without affecting the entire application.</li></ul><h3>4. Interoperability:</h3><ul><li>SOLA enables interoperability between services developed using different technologies. As long as services adhere to the specified interfaces, they can seamlessly communicate.</li></ul><h3>5. Fault Isolation:</h3><ul><li>In case of a failure in one service, others can continue to function. This fault isolation prevents the entire application from being affected by a single point of failure.</li></ul><h3>6. Technology Neutrality:</h3><ul><li>Services in SOLA can be implemented using different technologies and programming languages. This flexibility allows teams to choose the best technology for a specific service.</li></ul><h3>7. Improved Maintainability:</h3><ul><li>Due to modularity, services can be updated or replaced without affecting the entire system. This ease of maintenance contributes to a more sustainable and long-lived architecture.</li></ul><h3>When and Why to Use Service-Oriented Layer Architecture:</h3><h3>1. Large and Complex Systems:</h3><ul><li>SOLA is particularly beneficial for large and complex systems where breaking down functionality into smaller, manageable services promotes maintainability and scalability.</li></ul><h3>2. Diverse Technology Stack:</h3><ul><li>When an organization uses a diverse technology stack, SOLA allows different services to be implemented using the most suitable technologies, promoting flexibility and innovation.</li></ul><h3>3. Dynamic Scaling Requirements:</h3><ul><li>Applications with varying and dynamic scaling requirements benefit from SOLA. Services can be scaled independently based on demand, optimizing resource utilization.</li></ul><h3>4. Interoperability Needs:</h3><ul><li>In scenarios where interoperability with third-party systems or integration with legacy systems is crucial, SOLA provides a standardized approach to communication between services.</li></ul><h3>5. Agile Development:</h3><ul><li>For teams practicing agile development methodologies, SOLA aligns well with iterative and incremental development. It facilitates the quick and independent deployment of services.</li></ul><h3>6. Evolving Business Requirements:</h3><ul><li>As businesses evolve, so do their requirements. SOLA accommodates changing business needs by allowing the addition, removal, or modification of services without disrupting the entire application.</li></ul><h3>7. Service Reusability:</h3><ul><li>Organizations aiming to maximize the reuse of code and functionality across different parts of the application or across multiple applications can leverage SOLA.</li></ul><h3>Conclusion:</h3><p>Service-Oriented Layer Architecture stands as a powerful paradigm for designing and building robust, scalable, and maintainable software systems. Its emphasis on modularity, loose coupling, and scalability aligns with the needs of modern applications. When implemented thoughtfully, SOLA provides a framework that adapts to the evolving landscape of business requirements, making it a valuable choice for architects and developers looking to build resilient and future-proof systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4debe314c1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Roles Based Access Control ( RBAC ) using PostgreSQL, Node Js and Express]]></title>
            <link>https://aliahmadjan009.medium.com/roles-based-access-control-rbac-using-postgresql-node-js-and-express-08fbde4f4428?source=rss-e6cad85bc719------2</link>
            <guid isPermaLink="false">https://medium.com/p/08fbde4f4428</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[rbac]]></category>
            <category><![CDATA[sequelize]]></category>
            <dc:creator><![CDATA[Ali Ahmad Jan]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 06:20:05 GMT</pubDate>
            <atom:updated>2023-10-25T06:20:05.243Z</atom:updated>
            <content:encoded><![CDATA[<p>Access control is a critical aspect of application development. In many cases, you need to define and enforce user permissions and roles to ensure that your application’s data and resources are secure and accessible only to authorized users. Roles-Based Access Control (RBAC) is a popular approach to managing user access to different parts of an application. In this blog, we’ll explore how to implement RBAC using PostgreSQL, Node.js, and Express.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NoMUl4V7QjL4p3y7P4JafQ.png" /></figure><h3>Understanding Roles-Based Access Control (RBAC)</h3><p>RBAC is a model for managing user permissions within an application. It involves defining roles, assigning permissions to those roles, and then assigning users to specific roles. With RBAC, you can easily control who has access to what parts of your application, making it a robust and scalable solution for access control.</p><h3>Setting up the Environment</h3><p>Before implementing RBAC, you’ll need to set up your development environment. Here’s what you’ll need:</p><ol><li><strong>Node.js and Express</strong>: Node.js is a JavaScript runtime, and Express is a popular web application framework for Node.js.</li><li><strong>PostgreSQL</strong>: A powerful open-source relational database system that will store information about roles, permissions, and users.</li><li><strong>Object-Relational Mapping (ORM)</strong>: I have used ORM:sequelizefor database interactions</li></ol><h3><strong>Connecting Your Application With PostgreSQL</strong></h3><p>Create a file db.config.js and set your details like this</p><pre>module.exports = {<br>  HOST: &quot;localhost&quot;,<br>  USER: &quot;postgres&quot;,<br>  PASSWORD: &quot;12345&quot;,<br>  DB: &quot;Testing01&quot;,<br>  dialect: &quot;postgres&quot;,<br>  port: 5000<br>};</pre><p>Make sure to adjust the details according to your postgres using PgAdmin</p><p>Now, you have to configure these details to connect with PostgreSQL using sequelize</p><pre>const dbConfig = require(&quot;../DB/db.config&quot;);<br><br>const Sequelize = require(&quot;sequelize&quot;);<br>const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {<br>  host: dbConfig.HOST,<br>  dialect: dbConfig.dialect,<br>  port: dbConfig.port,<br>  logging: false<br>});<br>sequelize<br>  .authenticate()<br>  .then(() =&gt; {<br>    console.log(&quot;Connection to the database has been established successfully.&quot;);<br>  })<br>  .catch((err) =&gt; {<br>    console.error(&quot;Unable to connect to the database:&quot;, err);<br>  });<br>const db = {};<br><br>db.Sequelize = Sequelize;<br>db.sequelize = sequelize;<br><br>db.roles = require(&quot;./roles.model.js&quot;)(sequelize, Sequelize);<br>db.users = require(&quot;./users.model.js&quot;)(sequelize, Sequelize);<br>db.permissions = require(&quot;./permissions.model&quot;)(sequelize,Sequelize);<br>db.user_roles = require(&quot;./users_roles.model&quot;)(sequelize, Sequelize);<br>db.roles_permissions = require(&quot;./roles_permissions&quot;)(sequelize, Sequelize);<br>sequelize.sync();<br><br>module.exports = db;</pre><h3><strong>Creating Database</strong></h3><p>After establishing the connection with PostgreSQL, start by creating a PostgreSQL database that will store information about roles, permissions, and users. I have used sequelize as a ORM for PostgreSQL, so i have created my schemas using sequelize</p><p>Create roles.model.js for storing roles</p><pre>module.exports = (sequelize, Sequelize) =&gt; {<br>    const Roles = sequelize.define(&quot;roles&quot;, {<br>      id: {<br>        type: Sequelize.INTEGER,<br>        primaryKey: true,<br>        autoIncrement: true,<br>      },<br>      name: {<br>        type: Sequelize.STRING,<br>        allowNull:false<br><br>      },<br>      description: {<br>        type: Sequelize.STRING,<br>        allowNull:true<br>      },<br>      createdAt: Sequelize.DATE, <br>      updatedAt: Sequelize.DATE,<br>    });<br>  <br>    return Roles;<br>  };</pre><p>Create permissions.model.js for storing permissons</p><pre>module.exports = (sequelize, Sequelize) =&gt; {<br>    const Permissions = sequelize.define(&quot;permissions&quot;, {<br>      id: {<br>        type: Sequelize.INTEGER,<br>        primaryKey: true,<br>        autoIncrement: true,<br>      },<br>      <br>      name: {<br>        type: Sequelize.STRING, // Define an array of strings<br>        allowNull: false<br>      },<br>      createdAt: Sequelize.DATE, <br>      updatedAt: Sequelize.DATE,<br>    });<br>  <br>    return Permissions;<br>  };</pre><p>Create roles_permissions.model.js for storing the ids of roles and permissions</p><pre>module.exports = (sequelize, Sequelize) =&gt; {<br>    const RolesPermissions = sequelize.define(&quot;roles_permissions&quot;, {<br>  <br>        role_id: {<br>            type: Sequelize.INTEGER,<br>            allowNull: true,<br>            references: {<br>              model: &#39;roles&#39;, // This should match the name of the &quot;users&quot; table<br>              key: &#39;id&#39;<br>            }<br>          },<br>          permission_id: {<br>            type: Sequelize.INTEGER,<br>            allowNull: true,<br>            references: {<br>              model: &#39;permissions&#39;, // This should match the name of the &quot;roles&quot; table<br>              key: &#39;id&#39;<br>            }<br>          },<br>          createdAt: Sequelize.DATE, <br>          updatedAt: Sequelize.DATE,<br>        });<br>  <br>    return RolesPermissions;<br>  };</pre><p>Create users.model.js for storing the users</p><pre>module.exports = (sequelize, Sequelize) =&gt; {<br>    const Users = sequelize.define(&quot;users&quot;, {<br>      id: {<br>        type: Sequelize.INTEGER,<br>        primaryKey: true,<br>        autoIncrement: true,<br>      },<br>      name: {<br>        type: Sequelize.STRING,<br>        allowNull:false<br><br>      },<br>      email: {<br>        type: Sequelize.STRING,<br>        allowNull:false<br>      },<br>      password: {<br>        type: Sequelize.STRING,<br>        allowNull:false<br>      },<br>      createdAt: Sequelize.DATE, <br>      updatedAt: Sequelize.DATE,<br>    });<br>  <br>    return Users;<br>  };</pre><p>Create users_roles.modej.js for storing the ids of users and roles</p><pre>module.exports = (sequelize, Sequelize) =&gt; {<br>    const RolesUsers = sequelize.define(&quot;users_roles&quot;, {<br>        user_id: {<br>            type: Sequelize.INTEGER,<br>            allowNull: true,<br>            references: {<br>              model: &#39;users&#39;, // This should match the name of the &quot;users&quot; table<br>              key: &#39;id&#39;<br>            }<br>          },<br>          role_id: {<br>            type: Sequelize.INTEGER,<br>            allowNull: true,<br>            references: {<br>              model: &#39;roles&#39;, // This should match the name of the &quot;roles&quot; table<br>              key: &#39;id&#39;<br>            }<br>          },<br>          createdAt: Sequelize.DATE, <br>          updatedAt: Sequelize.DATE,<br>        });<br>  <br>    return RolesUsers;<br>  };</pre><p>After establishing the connection and creating the schemas, you now just have to write code for managing roles with permissions and users with roles, the code will vary according to your requirements, however I will give an example of managing roles with permissions</p><pre>const db = require(&quot;../Models&quot;);<br>const Roles = db.roles;<br>const Permissions = db.permissions;<br>const RolesPermissions = db.roles_permissions;<br><br>exports.editRole = (req, res) =&gt; {<br>  // Validate request<br>  if (!req.body.role_id || !req.body.permission_id) {<br>      res.status(400).send({<br>          message: &quot;Please provide role_id, and permission_id&quot;<br>      });<br>      return;<br>  }<br><br>  // Before assigning, let&#39;s ensure that the provided IDs actually exist in their respective tables.<br>  Promise.all([<br>      Roles.findByPk(req.body.role_id),<br>      Permissions.findByPk(req.body.permission_id)<br>  ])<br>  .then(([role, permission]) =&gt; {<br>    <br>      if (!role) {<br>          res.status(400).send({<br>              message: &quot;Role not found!&quot;<br>          });<br>          return;<br>      }<br><br>      if (!permission) {<br>          res.status(400).send({<br>              message: &quot;Permission not found!&quot;<br>          });<br>          return;<br>      }<br><br>      // All entities exist, let&#39;s link them<br>      let linkData = {<br>         <br>          role_id: role.id,<br>          permission_id: permission.id,<br>      };<br><br>      RolesPermissions.create(linkData)<br>          .then(() =&gt; {<br>              res.send({ message: &quot;Permissions assigned successfully!&quot; });<br>          })<br>          .catch(err =&gt; {<br>              res.status(500).send({<br>                  message: err.message || &quot;Some error occurred while linking the entities.&quot;<br>              });<br>          });<br>  })<br>  .catch(err =&gt; {<br>      res.status(500).send({<br>          message: err.message || &quot;Some error occurred while checking the entities.&quot;<br>      });<br>  });<br>};</pre><p>This is a PUTrequest in my case, so I tested with Postman</p><pre>http://localhost:8080/api/roles/edit<br><br>and giving ids in the body of the request<br><br>{<br>    &quot;role_id&quot;: 2,<br>    &quot;permission_id&quot; :1   <br>}<br><br>{<br>    &quot;message&quot;: &quot;Permissions assigned successfully!&quot;<br>}</pre><p>Similarly I managed/accessed users with roles.</p><h3>Conclusion</h3><p>Roles-Based Access Control (RBAC) is a powerful approach for managing user access in your application. By combining PostgreSQL, Node.js, and Express, you can create a robust RBAC system that ensures data security and controlled access to your resources. Properly implemented RBAC not only enhances security but also simplifies the management of user permissions as your application grows.</p><p>Remember that RBAC is just one piece of the puzzle in building a secure application. It’s crucial to keep your application and libraries up-to-date, implement other security measures, and regularly audit your RBAC system to maintain a robust and secure environment for your users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08fbde4f4428" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Express API Gateway with Node.js: The Modern Microservices Approach]]></title>
            <link>https://aliahmadjan009.medium.com/integrating-express-api-gateway-with-node-js-the-modern-microservices-approach-d8711237b021?source=rss-e6cad85bc719------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8711237b021</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[gateway]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Ali Ahmad Jan]]></dc:creator>
            <pubDate>Fri, 20 Oct 2023 04:22:12 GMT</pubDate>
            <atom:updated>2023-10-20T04:23:50.667Z</atom:updated>
            <content:encoded><![CDATA[<p>Microservices have rapidly become a popular architectural style, enabling organizations to develop modular and scalable applications. Each microservice takes care of one specific functionality and can be developed, deployed, and scaled independently. With all these moving parts, there arises a need to efficiently manage and route incoming requests to appropriate services. Enter the API Gateway.</p><h3>Advantages of an API Gateway:</h3><ol><li><strong>Centralized Management</strong>: Allows central management of all services without needing to touch each service individually.</li><li><strong>Security</strong>: Implement authentication and authorization at a single point instead of every microservice.</li><li><strong>Rate Limiting</strong>: Control the number of requests a user or service can make within a defined time limit.</li><li><strong>Caching</strong>: Improve response times and reduce unnecessary processing by caching responses.</li><li><strong>Load Balancing</strong>: Distribute incoming requests across multiple service instances to ensure optimal resource utilization.</li><li><strong>Monitoring</strong>: Centralized logging and monitoring capabilities to keep an eye on all incoming and outgoing requests.</li></ol><h3>Why Express API Gateway?</h3><p>There are numerous API gateway solutions available, but Express API Gateway stands out for a few key reasons:</p><ul><li><strong>Simplicity</strong>: Built on top of Express.js, one of the most popular and minimal web application frameworks for Node.js.</li><li><strong>Flexibility</strong>: Being open-source, it’s customizable to fit unique requirements.</li><li><strong>Configuration over Code</strong>: YML or JSON configurations allow quick setup without delving into the code.</li><li><strong>Built-in Policies</strong>: It comes with a plethora of built-in policies like logging, caching, rate-limiting, etc.</li><li><strong>Developer Friendly</strong>: It can simplify the development process by handling cross-cutting concerns like authentication and authorization, allowing individual microservices to focus on their specific functionality<strong>.</strong></li><li><strong>Compatibility</strong>: It is easily compatible with Node.js making it easy to work with Node Applications</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fHXs02wTw9OIjyRqK5h79A.png" /></figure><h3>Setting Up Express API Gateway:</h3><p>Firstly, install the Express Gateway:</p><pre>$ npm install -g express-gateway</pre><p>Initialize a new gateway:</p><pre>$ eg gateway create</pre><pre> ? What is the name of your Express Gateway? my-gateway<br> ? Where would you like to install your Express Gateway? my-gateway<br> ? What type of Express Gateway do you want to create? (Use arrow keys)<br> ❯ Getting Started with Express Gateway<br>   Basic (default pipeline with proxy)</pre><p>Follow the prompts, and you’ll have a basic gateway set up in no time!</p><h3>Configuration with YML:</h3><p>The real power of Express API Gateway lies in its configuration. With a simple YML file, you can define all your routes, endpoints, and policies.</p><p>Here’s a basic gateway.config.yml configuration:</p><pre>http:<br>  port: 5000<br>admin:<br>  port: 9876<br>  host: localhost<br>apiEndpoints:<br>  api:<br>    host: &#39;localhost&#39;<br>    paths: &#39;/endpoint/*&#39;<br>serviceEndpoints:<br>  service:<br>    url: &#39;http://localhost:3000&#39;<br>policies:<br>  - proxy<br>pipelines:<br>  default:<br>    apiEndpoints:<br>      - api<br>    policies:<br>      - proxy:<br>          - action:<br>              serviceEndpoint: service<br>              changeOrigin: true</pre><p>In this configuration:</p><ul><li>Requests coming to http://localhost:5000/endpoint/* are routed to <a href="http://localhost:3000/*.">http://localhost:3000/*.</a></li><li>We’re using the proxy policy, which will pass along the request to our defined service endpoint.</li></ul><h3>Integration with Node.js:</h3><p>Now, how does this work with a Node.js application?</p><p>Imagine you have a simple Express.js app running on localhost:3000.</p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br>app.get(&#39;/endpoint/hello&#39;, (req, res) =&gt; {<br>  res.json({ message: &quot;Hello from the microservice!&quot; });<br>});<br>app.listen(3000, () =&gt; {<br>  console.log(&#39;Service running on port 3000&#39;);<br>});</pre><p>With the gateway in place and the above configuration, any request to http://localhost:5000/endpoint/hello will be seamlessly routed to our service, providing a centralized entry point without the client ever knowing about the underlying service or its actual location.</p><h3>Interacting With Multiple Node Js Applications</h3><p>Similarly with Express API Gateway, you can interact with multiple Node.js applications, each application running on different Port. And for this make work we have to change gateway.config.yml to handle both applications simultaneously</p><p>Here is an Example of how to do it:</p><pre>http:<br>  port: 5000<br>admin:<br>  port: 9876<br>  host: localhost<br><br>apiEndpoints:<br>  user-api:<br>    host: &#39;localhost&#39;<br>    paths: &#39;/user/*&#39;<br>  camunda-api:<br>    host: &#39;localhost&#39;<br>    paths: &#39;/engine-rest/*&#39;<br><br>serviceEndpoints:<br>  camunda-service:<br>    url: &#39;http://localhost:3000&#39;<br>  user-service:<br>    url: &#39;http://localhost:3001&#39;<br><br>policies:<br>  - basic-auth<br>  - cors<br>  - expression<br>  - key-auth<br>  - log<br>  - oauth2<br>  - proxy<br>  - rate-limit<br><br>pipelines:<br>  user-pipeline:<br>    apiEndpoints:<br>      - camunda-api<br>    policies:<br>      - proxy:<br>          - action:<br>              serviceEndpoint: camunda-service<br>              changeOrigin: true<br>  task-pipeline:<br>    apiEndpoints:<br>      - user-api<br>    policies:<br>      - proxy:<br>          - action:<br>              serviceEndpoint: user-service<br>              changeOrigin: true</pre><p>To run API Gateway you have to type this command in terminal or run the URL in Postman:</p><pre>curl http://localhost:5000/user/create</pre><p>I would prefer to run the URL in Postman for better experience</p><p>Express API Gateway is easy to use, and as i said earlier its developer friendly so working with it makes things more simpler, you just have to create a gateway and change the configuration file according to your requirements and magic will happen on its own</p><h3>Conclusion:</h3><p>As applications grow and evolve, so do their complexities. Microservices offer a modular approach, but they also introduce challenges. Express API Gateway, combined with the power of Node.js, offers a scalable, maintainable, and efficient way to manage, monitor, and route requests in a microservice-based architecture. Embrace the gateway, and let your microservices shine!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8711237b021" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My DevOps Journey: From GitHub to Docker to Kubernetes to Service Mesh and GitOps]]></title>
            <link>https://aliahmadjan009.medium.com/my-devops-journey-from-github-to-docker-to-kubernetes-to-service-mesh-and-gitops-74b24ed57c18?source=rss-e6cad85bc719------2</link>
            <guid isPermaLink="false">https://medium.com/p/74b24ed57c18</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Ali Ahmad Jan]]></dc:creator>
            <pubDate>Tue, 06 Jun 2023 09:08:22 GMT</pubDate>
            <atom:updated>2023-06-06T09:08:22.562Z</atom:updated>
            <content:encoded><![CDATA[<p>The world of DevOps has revolutionized software development and deployment practices, enabling teams to deliver applications faster and more efficiently. In this blog, I will take you on my journey through the key milestones of the DevOps evolution, starting from GitHub to Docker, Kubernetes, service mesh, and GitOps. We will explore the tools, concepts, and learnings that have helped shape the modern DevOps landscape.</p><p><strong>Highlights of Course Content:</strong></p><ol><li>GitHub: Collaboration and Version Control — GitHub played a pivotal role in fostering collaboration and enabling version control in the DevOps journey. It provided developers with a centralized platform for managing source code, facilitating seamless collaboration, and ensuring version control. GitHub’s pull request mechanism revolutionized the way developers contribute and review code, promoting code quality and team collaboration.</li><li>Docker: Containerization and Portability — Docker introduced containerization, a game-changing technology in the DevOps ecosystem. Containers allowed developers to package applications and their dependencies into portable and lightweight units. This enabled consistent environments across different stages of the software development lifecycle and simplified application deployment, making it easier to replicate and scale environments.</li><li>Kubernetes: Orchestrating Containerized Applications — Kubernetes emerged as the de facto orchestration platform for managing containerized applications at scale. It provided a robust and scalable infrastructure for automating deployment, scaling, and management of containerized workloads. Kubernetes introduced concepts like pods, services, and deployments, empowering DevOps teams to efficiently manage and scale their applications with ease.</li><li>Service Mesh: Enhancing Microservices Communication — As microservices architectures gained popularity, the need for effective communication and management between services became crucial. Service mesh, exemplified by tools like Istio , emerged to provide features like traffic management, observability, and security for microservices. Service mesh solutions enhanced resilience, observability, and control over microservices interactions, making it easier to manage complex distributed systems.</li><li>GitOps: Infrastructure as Code and Continuous Delivery — GitOps introduced the concept of managing infrastructure and application deployments using version-controlled code repositories, primarily Git. With GitOps, infrastructure changes and application deployments are triggered by Git commits, ensuring version control, auditability, and reproducibility. GitOps promotes the principles of infrastructure as code and enables continuous delivery practices, providing a unified and automated approach to managing infrastructure and deployments.</li></ol><p><strong>Highlights of Course:</strong></p><p>A standout experience in the course was the highly anticipated Kubernetes Community Day hosted by our instructor, Mr. Saim Safdar at FAST NUCES, Islamabad. The event brought together a diverse range of workshops, with over ten sessions covering various aspects of Kubernetes. What made this day truly exceptional was the inclusion of renowned international speakers, who shared their invaluable expertise and anecdotes. The event not only provided unparalleled learning opportunities but also fostered valuable connections among like-minded individuals in the industry.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F3OQgB70EghM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D3OQgB70EghM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F3OQgB70EghM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/909adbdb279fd3ed1c9730fad138019d/href">https://medium.com/media/909adbdb279fd3ed1c9730fad138019d/href</a></iframe><p>Throughout the course, I actively contributed to the tech community by sharing my knowledge through Medium blogs. I focused on topics like Redux, PlayKube, and the comparison between Service Mesh and API Gateway, providing unique insights and perspectives.</p><p>One of my notable achievements during the course was obtaining the Istio Service Mesh certification. Istio, an open-source service mesh, provides a powerful framework to effectively manage the communication and interaction between different components within an application. This certification further solidified my expertise in deploying and leveraging Istio for seamless and secure microservices communication.</p><p><strong>Conclusion</strong></p><p>The DevOps journey has witnessed remarkable advancements from GitHub to Docker, Kubernetes, service mesh, and GitOps. I have learned the immense value these technologies bring to the world of DevOps. These technologies have empowered DevOps teams with greater collaboration, scalability, portability, and automation. The lessons learned include the value of collaboration, code portability, automation, and infrastructure as code. Adapting to the evolving DevOps landscape is crucial for continuous improvement and innovation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74b24ed57c18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Service Mesh vs API Gateway]]></title>
            <link>https://aliahmadjan009.medium.com/service-mesh-vs-api-gateway-d6ac40b5b4e6?source=rss-e6cad85bc719------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6ac40b5b4e6</guid>
            <category><![CDATA[service-mesh]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[api-gateway]]></category>
            <dc:creator><![CDATA[Ali Ahmad Jan]]></dc:creator>
            <pubDate>Wed, 10 May 2023 17:23:32 GMT</pubDate>
            <atom:updated>2023-05-10T17:24:49.888Z</atom:updated>
            <content:encoded><![CDATA[<p>As organizations continue to adopt microservices architecture, managing the communication between these services becomes a challenge. This is where Service Mesh and API gateway come into play. Both serve as essential tools in managing microservices communication, but they differ in their approach and functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*wO9UnnHdtIfu7_vfHDL9IA.jpeg" /></figure><p><strong>So, what is a Service Mesh?</strong></p><p>A Service Mesh is a dedicated infrastructure layer designed to manage and monitor service-to-service communication within a microservices architecture. It provides a way to manage, control and secure service-to-service communication using a set of lightweight proxies deployed alongside the services themselves.</p><p><strong>Deploying a Service Mesh:</strong></p><ol><li>Install Istio on Kubernetes</li></ol><pre>istioctl install</pre><p>Documentation: <a href="https://istio.io/latest/docs/setup/install/kubernetes/">https://istio.io/latest/docs/setup/install/kubernetes/</a></p><p>2. Create a new namespace and label it for automatic sidecar injection:</p><pre>kubectl create namespace my-namespace<br>kubectl label namespace my-namespace istio-injection=enabled</pre><p>Documentation: <a href="https://istio.io/latest/docs/setup/additional-setup/sidecar-injection/#automatic-sidecar-injection">https://istio.io/latest/docs/setup/additional-setup/sidecar-injection/#automatic-sidecar-injection</a></p><p>3. Deploy a sample application and service:</p><pre>kubectl apply -f &lt;sample_app.yaml&gt;<br>kubectl apply -f &lt;sample_service.yaml&gt;</pre><p><strong>Managing a Service Mesh:</strong></p><ol><li>View the status of the mesh components:</li></ol><pre>istioctl version<br>istioctl analyze</pre><p>Documentation: <a href="https://istio.io/latest/docs/ops/diagnostic-tools/istioctl/">https://istio.io/latest/docs/ops/diagnostic-tools/istioctl/</a></p><p>2. View the traffic flow and metrics:</p><pre>istioctl dashboard</pre><p>On the other hand, an <strong>API gateway</strong> is an essential part of an organization’s API infrastructure. It is responsible for managing and controlling access to APIs by external clients or applications. It provides a centralized point of entry for API requests, handles authentication, and enforces API policies.</p><p><strong>Deploying an API Gateway:</strong></p><ol><li>Install Kong Ingress Controller on Kubernetes:</li></ol><pre>helm repo add kong https://charts.konghq.com<br>helm install kong/kong --generate-name</pre><p>Documentation: <a href="https://docs.konghq.com/kubernetes-ingress-controller/2.3.x/deployment/installation/">https://docs.konghq.com/kubernetes-ingress-controller/2.3.x/deployment/installation/</a></p><p>2. Create a KongPlugin for authentication:</p><pre>kubectl apply -f &lt;kong_auth_plugin.yaml&gt;</pre><p>Documentation: <a href="https://docs.konghq.com/kubernetes-ingress-controller/2.3.x/guides/plugins/custom-plugins/">https://docs.konghq.com/kubernetes-ingress-controller/2.3.x/guides/plugins/custom-plugins/</a></p><p>3. Deploy an Ingress resource to expose the service:</p><pre>kubectl apply -f &lt;ingress.yaml&gt;</pre><p>Documentation: <a href="https://kubernetes.io/docs/concepts/services-networking/ingress/">https://kubernetes.io/docs/concepts/services-networking/ingress/</a></p><p><strong>Managing an API Gateway:</strong></p><ol><li>View the KongAdmin dashboard:</li></ol><pre>kubectl port-forward service/&lt;kong-admin-service-name&gt; &lt;local-port&gt;:&lt;remote-port&gt;</pre><p>Documentation: <a href="https://docs.konghq.com/kubernetes-ingress-controller/2.3.x/guides/expose-admin-api/">https://docs.konghq.com/kubernetes-ingress-controller/2.3.x/guides/expose-admin-api/</a></p><p>2. View the KongProxy metrics:</p><pre>kubectl port-forward service/&lt;kong-proxy-service-name&gt; &lt;local-port&gt;:&lt;remote-port&gt;</pre><p>Documentation: <a href="https://docs.konghq.com/kubernetes-ingress-controller/2.3.x/guides/expose-metrics/">https://docs.konghq.com/kubernetes-ingress-controller/2.3.x/guides/expose-metrics/</a></p><p>While both service mesh and API gateway share some similarities, there are key differences between them.</p><ol><li><strong>Communication</strong></li></ol><p>A service mesh manages communication between services within a microservices architecture, while an API gateway is responsible for managing communication between external clients and the APIs. Service mesh is focused on east-west traffic (between services), while API gateway focuses on north-south traffic (between external clients and APIs).</p><p>2. <strong>Functionality</strong></p><p>Service mesh is more focused on service-to-service communication, providing features such as service discovery, load balancing, traffic routing, and service-level security. In contrast, API gateway is more focused on managing external access to APIs, providing features such as API authentication, rate limiting, and API transformation.</p><p><strong>3. Deployment</strong></p><p>Service mesh proxies are deployed alongside the services themselves, providing a dedicated infrastructure layer for managing service-to-service communication. API gateways, on the other hand, are typically deployed as a separate layer in the infrastructure, providing a centralized point of entry for API requests.</p><p>So, which is better?</p><p>The answer to this question depends on the specific needs of your organization. If you are focused on managing service-to-service communication within a microservices architecture, then service mesh is the better choice. Service mesh provides a dedicated infrastructure layer for managing and securing communication between services, providing features such as service discovery, load balancing, and traffic routing.</p><p>If your organization is more focused on managing external access to APIs, then API gateway is the better choice. API gateway provides a centralized point of entry for API requests, handling authentication, rate limiting, and API transformation.</p><p>In conclusion, both service mesh and API gateway play important roles in managing microservices communication. Service mesh is focused on east-west traffic within a microservices architecture, while API gateway is focused on north-south traffic between external clients and APIs. Choosing the right tool depends on your organization’s specific needs and priorities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6ac40b5b4e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerizing a MERN Stack Application using Docker Compose: A Step-by-Step Guide]]></title>
            <link>https://aliahmadjan009.medium.com/dockerizing-a-mern-stack-application-using-docker-compose-a-step-by-step-guide-396250713b20?source=rss-e6cad85bc719------2</link>
            <guid isPermaLink="false">https://medium.com/p/396250713b20</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[mern-stack]]></category>
            <dc:creator><![CDATA[Ali Ahmad Jan]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 07:45:51 GMT</pubDate>
            <atom:updated>2023-03-31T08:15:54.438Z</atom:updated>
            <content:encoded><![CDATA[<p>Docker is a popular containerization technology that allows developers to package and deploy their applications with ease. Docker Compose is an additional tool that simplifies the process of defining and running multi-container Docker applications. In this blog post, we will walk through how to Dockerize a MERN stack application using Docker Compose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WXzIKHDVwdSokeMrq3PIOQ.jpeg" /></figure><h3>MERN Stack Overview</h3><p>Before we dive into Dockerizing our MERN stack application, let’s first understand what MERN stack is. MERN is an acronym for MongoDB, Express, React, and Node.js, which are four open-source technologies used to build web applications. MongoDB is a NoSQL database used to store data, Express is a web application framework for Node.js, React is a front-end library used to create user interfaces, and Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine.</p><h3>Dockerizing a MERN Stack Application</h3><p>Dockerizing a MERN stack application involves creating a Docker image for each component of the stack and defining how these components will communicate with each other using Docker Compose.</p><h4><strong>Backend/Server</strong></h4><ol><li>Create Dockerfile for the Node.js Server. We will start by creating a Dockerfile for the Node.js server. The Node.js server is the backend of our application that runs on the server and communicates with the database. The directory should look like this.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*o3Rgrk6atNHZ-HUsLXaU8w.png" /></figure><p>2. We will use the <strong>node:alpine</strong> image as our base image and copy the server files into the container.</p><pre># Base image<br>FROM node:alpine<br><br># Set working directory<br>WORKDIR /app<br><br># Copy package.json and package-lock.json files<br>COPY package*.json ./<br><br># Install dependencies<br>RUN npm install <br><br># Copy the rest of the application files<br>COPY . .<br><br># Port on which the backend server runs<br>EXPOSE 5000 <br><br># Serve the application<br>CMD [&quot;npm&quot;, &quot;start&quot;]</pre><p><strong>Note: </strong>If you have nodemon installed then running the server command is “<em>npm start</em>”. And if you haven’t installed nodemon, then running the server command is “<em>node index/server.js</em>”</p><p>3. This Dockerfile installs node:alpine , sets the working directory to /app, copies the package.json and package-lock.json files, runs npm install, copies the entire application code, exposes port 5000, and finally runs the npm start command.</p><h4>Frontend/Client</h4><p>1. Create Dockerfile for the React Client Next, we will create a Dockerfile for the React client. The React client is the front-end of our application that runs in the user’s browser. The directory should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*8pDc3AHQUnah8MR4ZWnvGQ.png" /></figure><p>2. We will again use the <strong>node:alpine</strong> image as our base image and copy the client files into the container.</p><pre># Base image<br>FROM node:alpine<br><br># Set working directory<br>WORKDIR /app<br><br># Copy package.json and package-lock.json files<br>COPY package*.json ./<br><br># Install dependencies<br>RUN npm install --force<br><br># Copy the rest of the application files<br>COPY . .<br><br># Port on which the frontend server runs<br>EXPOSE 3000  <br><br># Serve the application<br>CMD [&quot;npm&quot;, &quot;start&quot;]</pre><p><strong>Note: </strong>In my case it was “<em>npm install — force</em>”. Usually it is only “<em>npm install</em>”</p><p>3. This Dockerfile installs node:alpine , sets the working directory to /app, copies the package.json and package-lock.json files, runs npm install, copies the entire application code, exposes port 3000, and finally runs the npm start command.</p><h4>Docker Compose</h4><p>Make sure you have Docker Desktop installed and the version of docker compose is <strong>v2. </strong>After that, follow these steps</p><ol><li>Define Docker Compose Configuration in the main working directory.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*FmtBsECXOZ7cvulpzJ_QGg.png" /></figure><p>We will now define the Docker Compose configuration file that will bring together our <strong>Backend</strong> and <strong>Frontend</strong> containers. We will name the configuration file docker-compose.yaml. Add the following code to this file:</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  mongodb:<br>    image: &quot;mongo&quot;<br>    volumes: <br>      - data:/data/db<br>  backend:<br>    build: ./backend<br>    ports: <br>      - &quot;5000:5000&quot;<br>    volumes:<br>      - logs:/app/logs<br>      - ./backend:/app<br>      - /app/node_modules<br>    depends_on:<br>      - mongodb<br>  <br>  frontend:<br>    build: ./frontend<br>    ports:<br>      - &quot;3000:3000&quot;<br>    volumes:<br>      - ./frontend/src:/app/src<br>    stdin_open: true<br>    tty: true<br>    depends_on:<br>      - backend<br><br>volumes:<br>  data:<br>  logs:</pre><p>This configuration file defines two services: <strong>backend</strong> and <strong>frontend</strong>. The <strong>backend</strong> service uses the Dockerfile in the ./backend directory to build the Node.js server image and maps port 5000 in the container to port 5000 on the host. The <strong>frontend </strong>service uses the Dockerfile in the ./frontend directory to build the React client image and maps port 3000 in the container to port 3000 on the host.</p><h4>Commands for Docker Compose</h4><p>Follow these steps in order to fully Dockerize the multi container applications.</p><ol><li>Build the multi container application using: docker-compose build</li></ol><p>2. Run the multi container application using: docker-compose up</p><p><strong>Congratulations! You have fully Dockerized your MERN Stack Application!</strong></p><p>You can run your application on <strong>localhost:3000</strong> to view. Backend server is running on port 5000.</p><h3>Conclusion</h3><p>In conclusion, Docker Compose is a powerful tool for managing MERN stack applications, providing developers with a unified and efficient way to deploy and run their code across multiple environments. By using Docker Compose, developers can easily manage the dependencies of their application and many other things. With its ease of use and flexibility, Docker Compose has become a go-to solution for many developers looking to streamline their workflow and optimize their application deployment process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=396250713b20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PlayKube Podman: Building containers without Docker]]></title>
            <link>https://aliahmadjan009.medium.com/playkube-podman-building-containers-without-docker-3f71eece1bcf?source=rss-e6cad85bc719------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f71eece1bcf</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[podman]]></category>
            <dc:creator><![CDATA[Ali Ahmad Jan]]></dc:creator>
            <pubDate>Thu, 23 Mar 2023 07:19:30 GMT</pubDate>
            <atom:updated>2023-03-23T07:19:30.189Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>As software development becomes more complex, containerization has become a crucial component of the development process. They provide a lightweight and portable way to package software dependencies and run applications in any environment. Docker has emerged as a popular containerization platform, but its popularity has led to some issues. Many developers are now looking for alternatives that can help them to build containers without relying on Docker.</p><p><strong>The problem with Docker</strong></p><p>Docker has been the most popular container engine for many years. However, it has been facing several issues, such as security concerns, performance issues, and complexity. One of the main concerns with Docker is its security. Docker runs as a privileged user, which can pose a security risk. In addition, Docker requires root access to run containers, which can lead to privilege escalation attacks.</p><p>Another issue with Docker is its performance. Docker uses a monolithic architecture, which can cause performance issues in certain situations. For example, when multiple containers are running on the same host, Docker can experience resource contention, leading to performance degradation.</p><p>Finally, Docker can be complex to use. It requires developers to learn new commands and workflows, which can be time-consuming and error-prone.</p><p><strong>How PlayKube Podman can help</strong></p><p>PlayKube Podman is an open-source project that provides a container-based development and deployment platform for Kubernetes using the Podman container engine. Podman is a container engine that allows you to manage containers directly from the command line without needing a separate daemon process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*Z5fPx-cPpJq-w69WSyQMRw.jpeg" /></figure><p>Playkube and Podman can work together to help you deploy and manage containerized applications in a Kubernetes environment. Here are some ways in which PlayKube Podman can help:</p><ol><li><strong>Container management:</strong> Podman can be used to create, run, and manage containers, including building images from Dockerfiles, importing and exporting container images, and managing container networks.</li><li><strong>Resource isolation:</strong> Podman provides a level of resource isolation that allows you to run containers securely and efficiently, without needing a separate daemon process.</li><li><strong>Kubernetes integration:</strong> PlayKube integrates with Kubernetes, allowing you to deploy and manage your containerized applications in a Kubernetes environment. You can use Podman to create and manage the containers, while PlayKube handles the orchestration and management of the Kubernetes resources.</li><li><strong>Compatibility:</strong> Podman is compatible with Docker images and Dockerfiles, allowing you to easily migrate your Docker-based applications to a PlayKube Podman environment.</li></ol><p><strong>Building Containers With PlayKube Podman</strong></p><ol><li>First, create a Dockerfile that defines the contents of your container. For example, create a file called Dockerfile with the following contents:</li></ol><pre>FROM alpine:latest<br>RUN apk add --update nginx<br>COPY index.html /usr/share/nginx/html/index.html<br>EXPOSE 80<br>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><p>This Dockerfile uses the Alpine Linux base image, installs the Nginx web server, copies an index.html file to the Nginx document root, exposes port 80, and sets the Nginx process to run as the main container process.</p><ol><li>Create an index.html file in the same directory as the Dockerfile with some content that you would like to display on the webpage.</li><li>Open a terminal or command prompt and navigate to the directory where the Dockerfile and index.html file are located.</li><li>Run the following command to build a new container image:</li></ol><pre>podman build -t my-container-image .</pre><p>This command tells Podman to build a new container image using the Dockerfile and the current directory as the build context. The -t option specifies a name for the image, in this case my-container-image.</p><ol><li>Wait for Podman to finish building the container image. This may take a few minutes, depending on the size of the image and the complexity of the Dockerfile.</li><li>Once the build is complete, you can list the available container images using the following command:</li></ol><pre>podman images</pre><p>This will show you a list of available container images, including the one you just built.</p><p>That’s it! You have now built a container image using PlayKube Podman. You can now use this image to deploy a new container in a Kubernetes environment or run it directly on your local machine using the podman run command</p><p>While PlayKube Podman provides a lot of benefits and advantages for running containers, there are also some limitations to consider:</p><p><strong>Limitations:</strong></p><ol><li><strong>Limited support for Docker Compose</strong>: While Podman can run Docker Compose files, there may be some limitations or differences in behavior compared to running them with Docker. This could result in compatibility issues or unexpected behavior when running Docker Compose files with Podman.</li><li><strong>Limited container networking options:</strong> Podman currently only supports a limited set of container networking options, which may not be suitable for all use cases. For example, it does not support multi-host networking, which can be a limitation for certain distributed applications.</li><li><strong>Limited storage options:</strong> Podman currently does not support certain storage options, such as Docker’s overlay2 driver, which can be a limitation for certain applications that require specific storage configurations.</li><li><strong>Limited ecosystem and community support:</strong> While Podman has an active and growing community, it may not have the same level of ecosystem support or integration with other tools and platforms as Docker does.</li><li><strong>Limited Windows support:</strong> Podman is primarily designed to run on Linux and does not have the same level of support for running containers on Windows as Docker does.</li></ol><p>It’s important to evaluate these limitations and consider whether they will be a factor in your specific use case when deciding whether to use PlayKube Podman.</p><p><strong>Conclusion</strong></p><p>PlayKube Podman offers a viable alternative to Docker for containerization, providing developers with a lightweight and efficient way to manage and deploy containers in a Kubernetes environment. With Podman’s direct command-line interface and Playkube’s integration with Kubernetes, developers can easily create, run, and manage containers securely and efficiently. While there are some limitations to consider, such as limited support for Docker Compose and container networking options, PlayKube Podman offers an attractive option for those seeking an alternative to Docker.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f71eece1bcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced techniques for using Redux with React JS, such as using Redux DevTools or Redux Toolkit]]></title>
            <link>https://aliahmadjan009.medium.com/advanced-techniques-for-using-redux-with-react-js-such-as-using-redux-devtools-or-redux-toolkit-7cdf6d28a4b4?source=rss-e6cad85bc719------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cdf6d28a4b4</guid>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Ali Ahmad Jan]]></dc:creator>
            <pubDate>Sun, 19 Feb 2023 14:02:13 GMT</pubDate>
            <atom:updated>2023-02-19T14:02:13.828Z</atom:updated>
            <content:encoded><![CDATA[<p>Redux is a popular state management library used for managing the state of an application in a predictable way. It is widely used with React JS, but it can be used with any other JavaScript library or framework. In the first part of blog, we will explore some useful tips for working with Redux in React JS and then we will see some technical issues regarding Redux in React JS.</p><h3>1. Use Redux DevTools Extension</h3><p>Redux DevTools is a browser extension that provides a powerful debugging tool for Redux. It allows you to view the current state, track actions, and see how the state changes over time. You can also time travel through the state history to see how the application behaved at any point in time.</p><p>To use the Redux DevTools Extension, you need to install it in your browser and add the extension to your Redux store. Here’s an example of how to add the extension:</p><pre>import { createStore } from &#39;redux&#39;;<br>import rootReducer from &#39;./reducers&#39;;<br>const store = createStore(<br>  rootReducer,<br>  window.__REDUX_DEVTOOLS_EXTENSION__ &amp;&amp; window.__REDUX_DEVTOOLS_EXTENSION__()<br>);</pre><h3>2. Use Redux Toolkit</h3><p>Redux Toolkit is a set of utilities that simplifies the process of working with Redux. It provides a standardized way of writing Redux code and reduces boilerplate. With Redux Toolkit, you can create a store, create reducers, and dispatch actions without writing a lot of code.</p><p>To use Redux Toolkit, you need to install it in your project and create a slice. A slice is a collection of reducers, actions, and selectors that work together to manage a specific part of the state. Here’s an example of how to create a slice:</p><pre>import { createSlice } from &#39;@reduxjs/toolkit&#39;;<br>const counterSlice = createSlice({<br>  name: &#39;counter&#39;,<br>  initialState: { value: 0 },<br>  reducers: {<br>    increment: state =&gt; {<br>      state.value += 1;<br>    },<br>    decrement: state =&gt; {<br>      state.value -= 1;<br>    },<br>  },<br>});<br>export const { increment, decrement } = counterSlice.actions;<br>export default counterSlice.reducer;</pre><h3>3. Use Selectors to Access the State</h3><p>Selectors are functions that extract a specific part of the state from the Redux store. They provide an easy and efficient way to access the state in your components without having to worry about the structure of the state.</p><p>To use a selector, you need to define it in your Redux store and call it in your component. Here’s an example of how to define and use a selector:</p><pre>import {createSelector } from &#39;@reduxjs/toolkit&#39;;<br>const selectCounter = state =&gt; state.counter;<br>export const selectCounterValue = createSelector(<br>  selectCounter,<br>  counter =&gt; counter.value<br>);</pre><p>In your component, you can use the selector like this:</p><pre>import { useSelector } from &#39;react-redux&#39;;<br>import { selectCounterValue } from &#39;./selectors&#39;;<br>function MyComponent() {<br>  const counterValue = useSelector(selectCounterValue);<br>return &lt;div&gt;{counterValue}&lt;/div&gt;;<br>}</pre><h3>4. Use Redux Thunk for Asynchronous Actions</h3><p>Redux Thunk is a middleware that allows you to write asynchronous actions in Redux. It provides a way to dispatch actions that return functions instead of objects. This is useful for making API calls or other asynchronous operations.</p><p>To use Redux Thunk, you need to install it in your project and add it to your middleware. Here’s an example of how to use Redux Thunk:</p><pre>import { createAsyncThunk } from &#39;@reduxjs/toolkit&#39;;<br>import { fetchUser } from &#39;./api&#39;;<br>export const getUser = createAsyncThunk(&#39;user/getUser&#39;, async userId =&gt; {<br>  const response = await fetchUser(userId);<br>  return response.data;<br>});</pre><h3>5. Use Reselect to get optimization</h3><p>Reselect provides a memoization technique that optimizes selectors by caching their results. This means that if a selector is called with the same arguments, the cached result is returned instead of recomputing the value. This can significantly improve the performance of your application, especially when dealing with large or complex state trees and prevent unnecessary re-renders of components.</p><p>Here is an example of how to use Reselect with Redux in a simple counter application:</p><pre>import { createSelector } from &#39;reselect&#39;<br>// A simple input selector<br>const getItems = state =&gt; state.items<br>// A more complex selector that uses the input selector and computes a derived value<br>const getTotalPrice = createSelector(<br>  [getItems],<br>  items =&gt; items.reduce((acc, item) =&gt; acc + item.price, 0)<br>)<br>// The Redux store and initial state<br>const initialState = {<br>  items: [<br>    { id: 1, name: &#39;Apple&#39;, price: 1.5 },<br>    { id: 2, name: &#39;Banana&#39;, price: 2 },<br>    { id: 3, name: &#39;Orange&#39;, price: 1.8 },<br>  ],<br>}<br>const store = createStore(rootReducer, initialState)<br>// Using the selectors to get data from the Redux store<br>console.log(getItems(store.getState())) // outputs the array of items<br>console.log(getTotalPrice(store.getState())) // outputs the total price of all items</pre><h3>6. Use Redux Saga for more efficiency</h3><p>Redux Saga is a middleware library for Redux that allows you to handle side effects such as asynchronous API requests and impure operations in your Redux application in a more efficient and manageable way. It uses generator functions to write asynchronous logic, which makes the code easier to read and test.</p><pre>import { takeLatest, call, put } from &#39;redux-saga/effects&#39;;<br>import { fetchDataSuccess, fetchDataError } from &#39;../actions&#39;;<br>import { FETCH_DATA_REQUEST } from &#39;../constants&#39;;<br>import { api } from &#39;../api&#39;;<br>// worker saga<br>function* fetchDataSaga() {<br>  try {<br>    const data = yield call(api.fetchData);<br>    yield put(fetchDataSuccess(data));<br>  } catch (error) {<br>    yield put(fetchDataError(error));<br>  }<br>}<br>// watcher saga<br>function* watchFetchData() {<br>  yield takeLatest(FETCH_DATA_REQUEST, fetchDataSaga);<br>}<br>export default watchFetchData;</pre><p>While Redux is a popular state management library for React and other JavaScript applications, there are several technical issues that can arise when working with it. Here are some of the common technical issues in Redux:</p><h3>1. Overly complex state structure</h3><p>One of the most common issues in Redux is having an overly complex state structure. When the state tree is too complex, it can make it difficult to manage the state and write efficient selectors.</p><p>To address this issue, you can simplify your state structure by breaking it down into smaller, more manageable pieces. This can be done by using multiple reducers, using nested objects to represent different parts of the state, and using selectors to extract only the data that you need.</p><h3>2. Boilerplate code</h3><p>Redux can require a lot of boilerplate code, especially when defining actions and reducers. This can make it difficult to write and maintain Redux code.</p><p>To address this issue, you can use a library like Redux Toolkit. Redux Toolkit provides a set of tools that simplify the process of writing Redux code, including creating reducers and defining actions.</p><h3>3. Performance issues</h3><p>When working with large or complex state trees, Redux can sometimes cause performance issues. This is because every time the state changes, all connected components are re-rendered.</p><p>To address this issue, you can use memoization techniques to optimize your selectors and prevent unnecessary re-renders. You can also use tools like Reselect to create memoized selectors that only recompute when their inputs have changed.</p><h3>4. Asynchronous actions</h3><p>Redux is primarily designed for synchronous actions, but many applications require asynchronous actions like making API calls. Handling asynchronous actions in Redux can be complex and require additional middleware.</p><p>To address this issue, you can use middleware like Redux Thunk or Redux Saga to handle asynchronous actions in Redux. These middleware libraries provide additional functionality for handling asynchronous actions, including handling loading states and error handling.</p><h3>5. Testing</h3><p>Testing Redux code can be challenging, especially when dealing with complex state trees and asynchronous actions.</p><p>To address this issue, you can use testing frameworks like Jest and Enzyme to write unit tests for your Redux code. You can also use tools like Redux Mock Store to mock your Redux store and simulate actions and state changes. Additionally, you can use the Redux DevTools Extension to debug and test your Redux code in the browser.</p><h3>Conclusion</h3><p>In conclusion, Redux is a powerful state management library that can greatly simplify the process of managing and sharing state in your React applications. By keeping your state in a single, centralized store, Redux can make it easier to debug and test your application, and also enable features like time-travel debugging and hot-reloading.</p><p>While Redux can have a bit of a learning curve, it is definitely worth taking the time to understand its key concepts and how it can be used in conjunction with React. Additionally, there are a number of useful tools and libraries that can help make working with Redux even easier, such as the Redux DevTools and Redux Saga.</p><p>Overall, if you’re building complex applications with React, Redux is definitely worth considering as a way to manage your application state in a more organized and efficient way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cdf6d28a4b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create a Virtual Machine on DigitalOcean and Securely Access it using SSH Keys and RDP]]></title>
            <link>https://aliahmadjan009.medium.com/how-to-create-a-virtual-machine-on-digitalocean-and-securely-access-it-using-ssh-keys-and-rdp-3f0983065ba0?source=rss-e6cad85bc719------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f0983065ba0</guid>
            <category><![CDATA[virtual-machine]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[digital-ocean-droplet]]></category>
            <dc:creator><![CDATA[Ali Ahmad Jan]]></dc:creator>
            <pubDate>Sat, 18 Feb 2023 19:15:58 GMT</pubDate>
            <atom:updated>2023-02-19T07:56:41.280Z</atom:updated>
            <content:encoded><![CDATA[<p>DigitalOcean is a cloud hosting provider that offers an easy-to-use interface for creating and managing virtual machines (VMs) in the cloud. In this blog post, we will cover the steps for creating a VM instance, configuring SSH keys for secure access to the VM, accessing the VM using SSH, adding custom firewall rules, installing RDP on the VM, and hosting files using a simple HTTP server.</p><p>1.Register and Create a VM Instance First, register on the DigitalOcean website and log in to your account. From the dashboard, click on the “Create” button and select “Droplets.” Choose the operating system and plan you want for your VM instance, and select a data center region. Finally, click on the “Create” button to create your VM instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJ3vXSERhawXT13CzPwHAg.png" /></figure><p>2. Configure SSH Keys for Secure Access to the VM After the VM instance is created, click on its name to open its configuration page. Scroll down to the “Authentication” section and select “Add SSH Keys.” Copy and paste your SSH public key in the provided box or upload a file containing your public key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*YKfCiJTqXGdDv2R39sidKQ.png" /><figcaption>SSH Key</figcaption></figure><p>Click on “Add SSH Key” to add your key to the VM instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kwcmNeMic_2z-n5cTVhRxQ.png" /></figure><p>3. Access the VM Using SSH To access the VM using SSH, you can access using cloud platform or from your terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*2vH693m2ZPODRbmi89DFIQ.png" /><figcaption>Accessing from Droplet’s Console</figcaption></figure><p>Accessing from terminal: <br>ssh root@&lt;droplet’s public ip address&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*911h3-UfvrBM90JNkkk8aQ.png" /><figcaption>Accessing from Terminal</figcaption></figure><p>4. Add Custom Firewall Rules in the Subnet’s Security List To add custom firewall rules, click on the “Networking” tab and select the “Security” option. Click on the “Create a Firewall” button and set the firewall name and rules according to your needs. Once the firewall is created, click on the “Assign” button to assign it to your VM instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-fijNaHfBP7luLagSJGSA.png" /><figcaption>Inbound Rules for Custom Firewall</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ZSlxsYaj2s2LH-D6qsvMQ.png" /><figcaption>Outbound Rules for Custom Firewall</figcaption></figure><p>5. Install RDP on the VM and Access it Using RDP from Your PC To install RDP on the VM, run the following commands on the VM command line:</p><pre>adduser (username)<br>usermod -aG sudo (username) <br>sudo apt update<br>sudo apt install xubuntu-desktop<br>sudo apt install xrdp<br>sudo systemctl status xrdp<br>sudo adduser xrdp ssl-cert<br>sudo ufw allow 3389</pre><p>Once RDP is installed, you can access the VM desktop from your local computer using an RDP client. For Windows, you can use the built-in Remote Desktop Connection app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*QmCk-MbKWqQGUbWwZloE6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rFfH79u-cbdHWd1_Ca9SqA.png" /></figure><p>6. Host Files Using a Simple HTTP Server and Access Them Using the Public IP To host files using a simple HTTP server, install a web server such as Apache on the VM by running the following commands:</p><pre>sudo apt-get update<br>sudo apt-get install apache2</pre><p>After the web server is installed, change your directory to web server’s root directory and access the “index.html” file</p><pre>cd /var/www/html<br>nano index.html</pre><p>Once the files are hosted, you can access them using the VM’s public IP address from a web browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WHdmvaIlznISq27V9mPs-A.png" /><figcaption>Hosted File using Public IP as shown</figcaption></figure><p>Files are hosted which can be confirmed by RDP:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpRy4aEzrrXHEbTQRZyeqA.png" /></figure><p>Conclusion DigitalOcean provides an easy-to-use interface for creating and managing VM instances in the cloud. By following the steps outlined in this blog post, you can create a VM instance, configure SSH keys for secure access, access the VM using SSH, add custom firewall rules, install RDP, and host files using a simple HTTP server. These steps will help you get started with DigitalOcean and securely access your VM instances in the cloud.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f0983065ba0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>