<?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[Beyond Code - Medium]]></title>
        <description><![CDATA[Covering code related technologies, and buisness analysis on promising tech compnies - Medium]]></description>
        <link>https://medium.com/beyond-coding?source=rss----3190dbc755f4---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Beyond Code - Medium</title>
            <link>https://medium.com/beyond-coding?source=rss----3190dbc755f4---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 09:39:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/beyond-coding" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Take Advantage of Node.js Cluster and child processes with PM2, RabbitMQ, Redis and Nginx]]></title>
            <link>https://medium.com/beyond-coding/take-advantage-of-node-js-cluster-and-child-processes-with-pm2-rabbitmq-redis-and-nginx-c83eccfb8af8?source=rss----3190dbc755f4---4</link>
            <guid isPermaLink="false">https://medium.com/p/c83eccfb8af8</guid>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[pm2]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Matan Yemini]]></dc:creator>
            <pubDate>Thu, 09 Jul 2020 17:24:08 GMT</pubDate>
            <atom:updated>2020-07-10T10:34:24.681Z</atom:updated>
            <content:encoded><![CDATA[<h3>Take Advantage of Node.js Cluster and Child Processes with PM2, RabbitMQ, Redis and Nginx</h3><p>In this article I will try to show you how to take advantage of Node.js built-in libraries of Cluster and Child Processes to create an application that can distribute the load of incoming connections with no downtime and much more. We will use the RabbitMQ message broker and Redis pub/sub pattern. In addition, Nginx web server will be used as our reverse proxy and load balancer. Enjoy.</p><h3>Gentle Intro to Node Operations</h3><p>As developers you (mostly likely) have created both blocking and non-blocking operations. Blocking operations take many more cycles to complete when compared with non-blocking operations.</p><ul><li><strong>Non-blocking operations</strong>: will be performed in your L1, L2 and L3 cache or at your RAM. For example, math calculations, or any other processing logic</li><li><strong>Blocking operations:</strong> disk, file i/o, network operations and etc.</li></ul><p>As you probably already know, JavaScript engine is a single threaded engine — so we have exactly one execution stack.</p><p>In node js we have the <strong>event loop</strong>. Whenever we send a request to the application it will be queued by the <strong>event queue</strong> (described below). The event loop will constantly monitor the event queue and pick up each request and put in the execution stack. If the operation is a non-blocking operation, the response will be returned to the caller. But if it is a blocking operation the event loop will hand over the operation to a <strong>worker thread</strong> and when the operation is completed the response will be queued back and finally will get back to the caller. (Brief explanation — I won’t cover irrelevant details…)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJ_Zury2U7YDjTAgpuc7NQ.png" /><figcaption>This is actually what libuv enables — I ignored the V8 section, not relevant</figcaption></figure><h3>So, Why use a Cluster?</h3><p>Node.js is a single threaded (as said above) which means that even if we have machine with multiple cores: each core can handle a process, every process can handle multiple threads , or one Node.js instance (it will use only one core! For example, my machine has 12 cores..).</p><p><em>What is the big deal?</em></p><p>Take for example a function with a heavy calculation that we want to run in a simple Express application using Node — calculate Fibonacci according to a given large number (e.g. 100, your session will freeze) or even organizing a complex structured input. So, since it is a non-blocking operation the <strong>event loop will get stuck</strong> as opposed to the blocking operations that will executed by the worker threads (so they won’t freeze the loop). Think about how <strong>bad</strong> it is! While your server is calculating the heavy calculation, any other request that is coming to the service, will<strong> get stuck</strong>! Even if you have configured orchestration like Kubernetes you cannot create another replica because of one heavy logic calculation.</p><p>As a result, resource waste can be reduced tremendously by using the full capacity of your microprocessor — all available cores can be utilized for application execution, and even the requests will be handled more efficiently. Every core will handle a Node.js process serving the same port of our application and distributing the load between them. (Think about the traditional threads..)</p><blockquote>You can also solve these kind of problems by using Worker Threads (look at this — <a href="https://nodejs.org/api/worker_threads.html">https://nodejs.org/api/worker_threads.html</a>) but here I will focus the clustering option :) I will introduce them later.</blockquote><h3>Node.js Cluster Module</h3><p>As mentioned, Cluster Mode allows us to take advantage of a multi-core processor’s parallel capabilities by creating child processes each of which run a single instance of Node (in one thread) and share the same server port.</p><ul><li>Worker processes are spawned by using the fork() method.</li><li>These processes can communicate with the parent (child to parent and parent to child) via IPC (Inter Process Communication channel).</li></ul><p>The Cluster Module supports two methods for distributing incoming connections:</p><ol><li><strong>Round Robin:</strong> The master process listens on a port, accepts new connection and distribute them across the workers in a round-robin fashion.</li><li><strong>Second method</strong> (Sorry, don’t have a name for that..): The master process creates the listen socket and sends it to interested workers, the workers then accept incoming connections directly.</li></ol><p>The worker and cluster classes are sharing almost the same properties, methods and definition — besides that workers have different methods that can be used (such as ‘IsDead’ or ‘IsConnected’).</p><p>In addition, you must pay attention to the number of cores your machine has in order to maximize the clustering benefits <em>(os.cpus().length) — spawning large number of node js processes is not recommended! Because of additional resource allocation.</em></p><p>Each process has its own memory with their own V8 Engine.</p><p>Try to look at this example with an express app. <strong>The Fibonacci </strong>is just a recursive implementation of the algorithm with given number. Try running it first without the if-else and the cluster, send first request with number of 100 as parameter (?number=100) then open another session and try with the number of 2. It will stuck. Then do the same with the cluster — works amazingly!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/130d22c4c73cf14eeac7f745afa70e0d/href">https://medium.com/media/130d22c4c73cf14eeac7f745afa70e0d/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/350a3ab44877e6d9f1c141aa838dc1a8/href">https://medium.com/media/350a3ab44877e6d9f1c141aa838dc1a8/href</a></iframe><p><strong>Pay attention</strong> — This is not a best practice! we will not need to create the clustering operations (cluster.fork(), etc) since we will use PM2 :)</p><p>You can also check the difference at runtime between a Server with clustering and with by using loadtest (an npm package for load tests):</p><pre>npm install -g loadtest</pre><p>And run (-n = the number of requests, -c = concurrently,-- rps = requests per second):</p><pre>loadtest -n 1000 -c 100 --rps 200 &lt;host&gt;:&lt;port&gt;?number=&lt;param_fib&gt;</pre><p>Then you will see a report of the longest request completion time, total time, mean latency, number of errors and other important indicators of your service’s health.</p><p>Pay attention that the &lt;param_fib&gt; should be bigger in order to ‘feel’ the true benefits from clustering. Otherwise, it will just be overhead :)</p><p>Or use Artillery (an amazing load testing tool: <a href="https://artillery.io/faq.html">https://artillery.io/faq.html</a>)</p><h3>Running our application with PM2</h3><p>When we deploy our application, some child processes might get killed due to different reasons. Since scaling a single threaded process can be hard to get right; let’s use PM2 — over 60 million downloads and 25k GitHub stars (and rising!). PM2 has a built in load balancer. With a configuration file (process.json/js), you specify what processes you want to run and how many you’d like to scale to. When starting PM2, you specify the process.json/js file and PM2 takes care of the rest. Monitoring, stopping, deleting, restarting processes are EASY.</p><p>As mentioned earlier, it is important to define the process file to:</p><ol><li>Fine-tune PM2’s behavior.</li><li>Define environment variables</li><li>Define where to store log files for each application (and furthermore, each child process which forms such an application)</li></ol><p>Install:</p><pre>npm install -g pm2</pre><p>Run PM2 process config:</p><pre>pm2 [start|restart|stop|delete] &lt;config_name&gt;.config.js/json</pre><p>Here is a super simple example (can be auto produced by typing: ‘ pm2 ecosystem’ for a config (as js file — if auto generated it will be ecosystem.config.js):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbded784b56cee1c56ca373baabbc62c/href">https://medium.com/media/dbded784b56cee1c56ca373baabbc62c/href</a></iframe><p>For all the options to run PM2, take a look at this <a href="https://devhints.io/pm2">cheatsheet</a>.</p><p>Now you can return to your code without any cluster implementation. PM2 will manage the cluster for you.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/130d22c4c73cf14eeac7f745afa70e0d/href">https://medium.com/media/130d22c4c73cf14eeac7f745afa70e0d/href</a></iframe><pre>pm2 start ecosystem.config.js</pre><p>Then you will see a list of processes and monitoring metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*OZNc1NF9T17UDWdi8vywqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*pxJs2yJvIeTGO9dLrYnU4Q.png" /><figcaption>Typing: pm2 monit for details about health and log (from above)</figcaption></figure><p>Then, you can <strong>run the load tests again</strong> and see how your application performs with PM2. In order to have super cool monitoring try entering: app.pm2.io (in browser), sign up and follow the instructions (you will get a public and private key for your machine). You can use it for <strong>monitoring your event loop </strong>which is amazing! You will be able to see all of the details crystal clear. This is how it should look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*boeI9RO_WpV_raGSIGJZxQ.png" /><figcaption>Super simple</figcaption></figure><h3>The child_process Module:</h3><p>Differences between the child_process module and the cluster module:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XjARU57S6Fzcz2Ae04oz3w.png" /></figure><p><strong>A cluster</strong> is when you have two or more node instances running with one master process routing incoming requests (or whatever tasks you want) to one of the worker instances. I find that this is generally better achieved using a real router or more complex node.js solutions, like <a href="https://www.npmjs.com/package/pm2">pm2</a>, for example. This is what I tend to use on production servers. Throughput is phenomenal and the server instances are extremely stable.</p><p><strong>A child process </strong>is much the same as it is in other languages. It simply spawns a new script or executable on the system. It can be anything you have the ability run, not necessarily JavaScript. The result of executing the spawn function (the child object above) is a ChildProcess instance, which implements the <a href="https://medium.freecodecamp.com/understanding-node-js-event-driven-architecture-223292fcbc2d">EventEmitter API</a>. This means we can register handlers for events on this child object directly. For example, we can do something when the child process exits by registering a handler for the exit event.</p><p><strong>Pay Attention:</strong></p><p>cluser.fork is implemented on top of child_process.fork. The extra stuff that cluster.fork brings is that, it will enable you to listen on a shared port. If you don&#39;t want it, just use child_process.fork. So, use cluster for web servers and child_process for workers.</p><h4><strong>A Few Differences for example:</strong></h4><p><strong>Clustering:</strong></p><ul><li>Built on top of Child_process, but with TCP distribution between clusters</li><li>Best for distributing/balancing incoming http requests, while bad for cpu intensive tasks</li><li>Works by taking advantage of available cores in cpu, by cloning node.js webserver instances on other cores</li><li>Solution for cases you don’t want a downtime</li></ul><p><strong>Child_process (</strong><a href="https://nodejs.org/api/child_process.html"><strong>official docs</strong></a><strong>):</strong></p><ul><li>Make use also of different cores available, but its bad since it costs huge amount of resources to fork a child process since it creates virtual memory</li><li>Forked processes could communicate with the master thread through events and vice versa, but there is no communication between forked processes</li><li>We can run .exe or .bat files with them! check <a href="https://nodejs.org/api/child_process.html">node.js docs</a></li></ul><h4>Differences between spawn() and fork() when talking about child_processes:</h4><p><strong>Spawn</strong> is a command designed to run system commands. When you run spawn, you send it a system command that will be run on its own process, but does not execute any further code within your node process. You can add listeners for the process you have spawned, to allow your code interact with the spawned process, but no new V8 instance is created(unless of course your command is another Node command, but in this case you should use fork!) and only one copy of your node module is active on the processor.</p><p><strong>Fork</strong> is a special instance of spawn, that runs a fresh instance of the V8 engine. Meaning, you can essentially create multiple workers, running on the exact same Node code base, or perhaps a different module for a specific task. This is most useful for creating a worker pool. While node’s async event model allows a single core of a machine to be used fairly efficiently, it doesn’t allow a node process to make use of multi core machines. The easiest way to accomplish this is to run multiple copies of the same program, on a single processor.</p><p>A good rule of thumb is one to two node processes per core, perhaps more for machines with a good ram clock/cpu clock ratio, or for node processes heavy on I/O and light on CPU work, to minimize the down time the event loop is waiting for new events. However, the latter suggestion is a micro-optimization, and would need careful benchmarking to ensure your situation suits the need for many processes/core. You can actually decrease performance by spawning too many workers for your machine/scenario.</p><p>For more info about child_processes you can enter <a href="https://www.freecodecamp.org/news/node-js-child-processes-everything-you-need-to-know-e69498fe970a/"><strong>this great article</strong></a><strong>.</strong></p><h4>Master and Child Process Communication Using PM2 and RabbitMQ</h4><p>When using PM2 we can’t use some of the modules (like the cluster module — in the example before), so we need to find another way to communicate between them, and distribute the load.</p><p>For this we have the open-source message broker — <strong>RabbitMQ</strong></p><p><strong><em>A little introduction to RabbitMQ (it is not RabbitMQ guide!)…</em></strong></p><p>We have to important roles:</p><p>Messaging enables software applications to connect and scale. Applications can connect to each other, as components of a larger application, or to user devices and data. Messaging is asynchronous, decoupling applications by separating sending and receiving data.</p><p>You may be thinking of data delivery, non-blocking operations or push notifications. Or you want to use publish / subscribe, asynchronous processing, or work queues. All these are patterns, and they form part of messaging.</p><p>RabbitMQ is a messaging broker — an intermediary for messaging. It gives your applications a common platform to send and receive messages, and your messages a safe place to live until received.</p><ol><li><strong>Producer:</strong> An application that publish the messages. These messages will go to the RabbitMQ Broker that will define message queues for each service that wants subscribed to the broker for specific message.</li><li><strong>Consumer:</strong> The consumer can be also an application that has subscribed to Broker and wants to consume messages from the relevant message queue.</li></ol><ul><li>These queues can be <a href="https://www.rabbitmq.com/ha.html">mirrored</a> across several machines in a cluster, ensuring that even in the event of hardware failure your messages are safe.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*wLFkh6E-VPpkOpNu3_J1Ww.png" /></figure><p>We will use RabbitMQ for distribute messages to multiple consumers and even load balance between the workers.</p><p><a href="https://www.rabbitmq.com/download.html">Install RabbitMQ</a> and add this package:</p><pre>npm install --save amqplib</pre><p>In order to see the queue in a nice web interface, open the browser and type this URL: <a href="http://localhost:15672/">http://localhost:15672</a> (userid = guest, password = guest):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MCFN3Aj85lil-wDIMHCaMA.png" /><figcaption>Simple and Easy!</figcaption></figure><p>Now, in the next example we are going to take PM2 advantages and manage our application. PM2 will be responsible to create and manage the processes. It will create two processes that will act like producers, that will finally get the request and pass it to the RabbitMQ broker. In addition, PM2 will create two more consumers that will be our consumers — they will subscribe to the broker and consume messages from its message queues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZyRe255EKH4gaGRuGfdbEw.png" /><figcaption>Our simple app architecture</figcaption></figure><p>When implementing this architecture and using RabbitMQ all the queue logic will be over the <strong>channel</strong>; A virtual connection inside a connection. When publishing or consuming messages from a queue — it’s all done over a channel after establishing <strong>connection</strong>; a TCP connection between your application and the RabbitMQ broker.</p><p>A super simple <strong>example for a queue</strong> that we can use for each of our workers — every worker is going to consume different queue (the function is called from where the workers and queues are created):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7e57f0f6fa7f23e4784f102e22a7150/href">https://medium.com/media/f7e57f0f6fa7f23e4784f102e22a7150/href</a></iframe><p>Now, here is an example of a <strong>worker </strong>code that <strong>consumes </strong>from this queue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb7a545c6c7d6f2490c5d68a06f12345/href">https://medium.com/media/fb7a545c6c7d6f2490c5d68a06f12345/href</a></iframe><p>You will now have to create a small file that will call the workers. For the example we will have two workers and two express app instances (as described in the architecture earlier). Now we should change our config for PM2 to support this architecture (I have removed the deploy, not relevant):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b4903d675f4c3a1ef0752151dbcf70c/href">https://medium.com/media/5b4903d675f4c3a1ef0752151dbcf70c/href</a></iframe><p>Now, follow the commands for the example:</p><pre>pm2 start ecosystem.config.js</pre><p>Then, you should see the pm2 list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*24V1z_3xwO4BwTeNSXCgAw.png" /></figure><p>Then, we want to check the load tests:</p><pre>loadtest -n 1000 -c 100 --rps 100 <a href="http://localhost:3000/?number=20">http://localhost:3000?number=20</a></pre><p>This is should be your output from the load tests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0YyV-NZ9FGQ2S45BVNVX2g.png" /></figure><p>Now, see at the web interface of pm2 what is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oid8duCF6kls9J_JIMLq3A.png" /></figure><p>You can see that we have X2 on the express app and two workers (one from each kind — first and second). When we started the load tests the cpu and memory were in use as can be seen in the activity measurement. In addition, you can reach out for the logs of each worker or express app by typing in the command line:</p><pre>pm2 logs &lt;id_at_pm2_list&gt;</pre><p>If you want to check your RabbitMQ queues or any other data regarding it, you should go to where you RabbitMQ server is and then go to ‘sbin’ folder. For example:</p><pre>/c/Program Files/RabbitMQ Server/rabbitmq_server-3.8.3/sbin</pre><p>And now run the command for watch the queues’ details:</p><pre>rabbitmqctl list_queues</pre><h3>Redis &amp; REST API with Express.js and PM2</h3><p><strong>Introduction:</strong></p><ul><li>Redis is a NoSQL database — which is kind of amazing!</li><li>It stores data in a ‘Key-Value’ pair (for comparison, mongoDB stores data as documents)</li><li>It is in-memory database = fast!</li><li>It supports multiple data structures</li><li>It is open-source!</li><li>Great for caching, cookie storage, expiring data, pub/sub, etc</li></ul><p><a href="https://redis.io/download">Install Redis</a> . For more information about Redis read <a href="https://codeburst.io/redis-what-and-why-d52b6829813">this article</a></p><p>For our example we are going to use a dummy API: <a href="https://jsonplaceholder.typicode.com/">JsonPlaceHolder</a>. We are going to create requests to the API for data about users, posts and comments. We are going to have an entry js file that will create our express app and call our route handler: ‘app.use(‘/jph’, jphRoutes)</p><p>Then we will create our super simple route handler (If it was not for only an example, I would have done it differently..):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9b7c170739514d3b35ec94f8d547e11/href">https://medium.com/media/b9b7c170739514d3b35ec94f8d547e11/href</a></iframe><p>the keys just holds the port (redis default: 6379 and host: localhost)</p><p>And the route file is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77de2fbb632a53bd2006f1b27dc4740f/href">https://medium.com/media/77de2fbb632a53bd2006f1b27dc4740f/href</a></iframe><p>Then, run PM2 start with your config (should be as the first config I have showed here with ‘MAX’ instances) and the loadtest (same as before with URL of http://localhost:3000/jph/&lt;posts / comments / users&gt;). Now you can see by using ‘pm2 monit’ the logs that represent our data that was retrieved from Redis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c-0BTFUKavJZIzDvVJJsTg.png" /></figure><p><em>The flow was:</em></p><ol><li>Defining the router to handle requests from a URL</li><li>Fetching the data from the JsonPlaceHolder API</li><li>Activating a middleware of Redis for saving the fetched data</li><li>Load the saved data from Redis</li><li>Send the data back with an indication that Redis was used.</li></ol><p>Now, we want will want to enable a <strong>Publisher/Subscriber with Redis. </strong>We are going to create demo that has almost the same architecture as the RabbitMQ implementation. Instead of using the message broker we are going to create a pub/sub module that is naturally integrated on Redis. The architecture will look like (simplified it as much as possible)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zc8RRegLJh4MVV88MwJyGA.png" /></figure><p>We have two processes that will act like publisher. They will publish the request data to the Redis server by creating a channel. In addition, the two subscribes will receive the data from the channel. As soon as a publisher publish a message to the channel the subscriber can get the message and process it.</p><p><strong>Implement message store with Redis using the publisher/subscriber pattern:</strong></p><p>First, we will create our publisher. As can be seen at the code below (simplified it as much as possible), the Redis client is going to be our publisher. The client is going to publish the number to a channel according to the given number. Each channel will be consumed by a subscriber as mentioned in the architecture above. This publisher will be duplicated according to our config in PM2, here it will be 2 publishers and 2 subscribers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/778e00c09533bede6db2c42e6d56f8c8/href">https://medium.com/media/778e00c09533bede6db2c42e6d56f8c8/href</a></iframe><p>We will create a listener according to our Redis keys, then the subscriber subscribe to a channel. After that, the subscriber waits to an event, here is message, and then processes the event. The basic subscriber code will look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8b14a07a3f37eedef38f6dd467a1cb3/href">https://medium.com/media/a8b14a07a3f37eedef38f6dd467a1cb3/href</a></iframe><p>Pay attention to your configuration file for PM2 — remember, 2 subscribers and 2 publishers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9cce5c344c3def53e2d402396952deb4/href">https://medium.com/media/9cce5c344c3def53e2d402396952deb4/href</a></iframe><p><strong>This is just an example config in order to simplify some things, your subscribers’ names and scripts should be defined in a more ‘clean’ way..</strong></p><h3>How to configure Nginx web server as reverse proxy and load balancer</h3><p><strong>Introduction to Nginx</strong></p><p>nginx has one master process and several worker processes. The main purpose of the master process is to read and evaluate configuration, and maintain worker processes. Worker processes do actual processing of requests. nginx employs event-based model and OS-dependent mechanisms to efficiently distribute requests among worker processes. The number of worker processes is defined in the configuration file and may be fixed for a given configuration or automatically adjusted to the number of available CPU cores.</p><p>NGINX is a powerful web server and uses a non-threaded, event-driven architecture that enables it to outperform Apache if configured correctly. It can also do other important things, such as load balancing, HTTP caching, or be used as a reverse proxy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*KC-OWGp3z614JxWnzWFuYg.png" /></figure><p>Various things in this file can be tweaked based on your needs, but NGINX is so simple to use that you can go along even with the default settings. Some of the most important pieces of the NGINX config file are:</p><ul><li><strong>worker_processes:</strong> This setting defines the number of worker processes that NGINX will use. Because NGINX is single threaded, this number should usually be equal to the number of CPU cores.</li><li><strong>worker_connections:</strong> This is the maximum number of simultaneous connections for each worker process and tells our worker processes how many people can simultaneously be served by NGINX. The bigger it is, the more simultaneous users the NGINX will be able to serve.</li><li><strong>access_log &amp; error_log:</strong> These are the files that NGINX will use to log any erros and access attempts. These logs are generally reviewed for debugging and troubleshooting.</li></ul><p><strong>The common use </strong>for Nginx load balancing HTTP requests . Load balancing involves the proxy server being configured to route incoming HTTP requests to a set of identical servers. By spreading incoming requests across these servers, the reverse proxies are able to balance out the load, therefore sharing it among them equally.</p><p>For more information and installation — read <a href="https://www.freecodecamp.org/news/an-introduction-to-nginx-for-developers-62179b6a458f/">this great article</a>.</p><p>We will use Nginx as a reverse proxy. But, <strong>What is reverse proxy?</strong></p><p>A reverse proxy is an intermediary proxy service which takes a client request, passes it on to one or more servers, and subsequently delivers the server’s response to the client. <strong>What are the benefits from reverse proxy?</strong></p><ol><li><strong>Load balancing</strong> — A reverse proxy can perform load balancing which helps distribute client requests evenly across backend servers. This process greatly helps in avoiding the scenario where a particular server becomes overloaded due to a sudden spike in requests. Load balancing also improves redundancy as if one server goes down, the reverse proxy will simply reroute requests to a different server. For more information about the load balancing processes <a href="https://www.keycdn.com/support/load-balancing">read this</a>.</li><li><strong>Increased security</strong> — A reverse proxy also acts as a line of defense for your backend servers. Configuring a reverse proxy ensures that the identity of your backend servers remains unknown. This can greatly help in protecting your servers from attacks such as <a href="https://www.keycdn.com/support/ddos-attack">DDoS</a> for example.</li><li><strong>Easy logging and auditing</strong> — Since there is only one single point of access when a reverse proxy is implemented, this makes logging and auditing much simpler. Using this method, you can easily monitor what goes in and out through the reverse proxy</li><li><strong>URL Rewriting</strong> before they go on to the backend servers</li><li><strong>Caching Server</strong></li></ol><p><strong>Few Command of Nginx:</strong></p><ul><li>Stop — fast shutdown:</li></ul><pre>nginx -s stop</pre><ul><li>Quit — graceful shutdown:</li></ul><pre>nginx -s quit</pre><ul><li>Reload — reloading the configuration file</li></ul><pre>nginx -s reload</pre><ul><li>Reopen — reporting the log files</li></ul><pre>nginx -s reopen</pre><p>This is how it should be in our example program:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*H_yrLGXrxFbNHxUYhHT1hg.png" /></figure><p><strong>Modify the Nginx configuration file:</strong></p><p>Download and extract the files from <a href="http://nginx.org/en/download.html">this installation</a>. Now, press the Nginx.exe to start your Nginx server.</p><p>Configuration file includes rules for Nginx as load balancer and reverse proxy:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b190f9e6859c311126cf82cf5b2c3a45/href">https://medium.com/media/b190f9e6859c311126cf82cf5b2c3a45/href</a></iframe><p>The upstream is the definition for the cluster web servers and to what port they are serving. The server section means to which port Nginx will serve and pass the requests from the defined port (here 80), and the location to send requests to is the location section.</p><p>Now, we need to add it to the main Nginx configuration file. Go to where you have extract the files and open the nginx.conf file and add to the http section the configuration that I have mentioned earlier (pay attention that I have put them in the same folder, this should be your path to the file):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*kwPlsus8jXxHdwQ0FIsEvw.png" /></figure><p>This is how your PM2 config should look like for the example (as defined in architecture)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00b1d13981e6c254c3540e76e218099c/href">https://medium.com/media/00b1d13981e6c254c3540e76e218099c/href</a></iframe><p>Pay attention that we have added the args option here since when distributing the request we will want to know who is going to recieve the request. Now, you can react your process.argv[0] and get inside your router.</p><p>Now, try enter: localhost/users and see the magic in PM2 and at your browser!</p><h3>Comparison (with a teaser to worker threads):</h3><p>Remember Node.js is not actually single threaded! Not only that it utilized the OS for blocking operations in its core libraries - operations that not taking care by the event loop and only when they are ready they are coming as callbacks to the loop.</p><p>In addition to Cluster module and child_processes there is another way to create another thread that can actually share data easily — <strong>Worker Threads</strong></p><p><strong>I will discuss worker threads at the next article!</strong></p><p><strong>Cluster:</strong></p><ol><li>Great for spawning many HTTP servers that share the same port b/c the master process will multiplex the requests to the child processes.</li><li>One <em>process</em> is launched on each CPU and can communicate via <a href="https://en.wikipedia.org/wiki/Inter-process_communication">IPC</a>.</li><li>Each process has it’s own memory with it’s own Node (v8) instance. Creating tons of them may create memory issues.</li><li>Remember — cluster module creates processes (not threads!), so that on each process will be a Node.js instance</li></ol><p><strong>Child Process:</strong></p><ol><li>It simply spawns a new script or executable on the system. It can be anything you have the ability run, not necessarily JavaScript.</li><li>Forked processes could communicate with the master thread through events and vice versa, but there is no communication between forked processes.</li></ol><p><strong>Worker Threads (as a teaser…):</strong></p><ol><li>One process total</li><li>Creates multiple threads with each thread having one Node instance (one event loop, one JS engine). Most Node API’s are available to each thread except a few. So essentially Node is embedding itself and creating a new thread.</li><li>Shares memory with other threads (e.g. SharedArrayBuffer)</li><li>Great for CPU intensive tasks like processing data or accessing the file system. Because Node.js is single threaded, synchronous tasks can be made more efficient with workers</li></ol><h3>Thank you!</h3><p>I hope you have enjoyed reading it and found something that will be useful for your application. In addition, if you have more points for comparison, please write! Thank you for surviving :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*QeI0yWGyih75wrEP10_7bA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c83eccfb8af8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beyond-coding/take-advantage-of-node-js-cluster-and-child-processes-with-pm2-rabbitmq-redis-and-nginx-c83eccfb8af8">Take Advantage of Node.js Cluster and child processes with PM2, RabbitMQ, Redis and Nginx</a> was originally published in <a href="https://medium.com/beyond-coding">Beyond Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NATS Streaming Server  in the Node.js World with Kubernetes How-To Guide]]></title>
            <link>https://medium.com/beyond-coding/nats-streaming-server-in-the-node-js-world-with-kubernetes-how-to-guide-2595dd598acc?source=rss----3190dbc755f4---4</link>
            <guid isPermaLink="false">https://medium.com/p/2595dd598acc</guid>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[eventbus]]></category>
            <category><![CDATA[nats-streaming]]></category>
            <dc:creator><![CDATA[Matan Yemini]]></dc:creator>
            <pubDate>Sat, 23 May 2020 09:07:27 GMT</pubDate>
            <atom:updated>2020-05-24T11:40:33.816Z</atom:updated>
            <content:encoded><![CDATA[<h3>NATS Streaming in the Node.js World with Kubernetes How-To Guide</h3><p>We will cover introduction to NATS Streaming, how to implement the NATS Streaming Server and its clients (w/ Node.js) in a microservices environment, and how to deploy it on k8s.</p><h3>What is NATS Streaming?</h3><p>First, you have to understand that NATS and NATS Streaming are <strong>two different things</strong>!</p><p>While <strong>NATS </strong>is<strong> </strong>Lightweight publish-subscribe &amp; distributed queueing messaging system. Unlike traditional enterprise messaging systems, NATS has an always-on dial tone that does whatever it takes to remain available. This forms a great base for building modern, reliable, and scalable cloud and distributed systems.</p><p><strong>NATS Streaming</strong> is a lightweight, streaming platform built on top of <a href="https://nats.io/">NATS</a> that provides an API for persistent logs. NATS Streaming is written in Go. It can be employed to add event streaming, delivery guarantees, and historical data replay to NATS. The high-level features of NATS Streaming is similar like the capabilities of Apache Kafka, but the former wins when you consider simplicity over complexity. Because NATS Streaming is relatively a new technology, it needs to improve in some areas especially on providing a better solution for load balancing scenarios, as compared to Apache Kafka. NATS streaming uses the concept of a channel to represent an ordered collection of messages. Clients send to and receive from channels instead of subjects.</p><h3><strong>Why NATS Streaming?</strong></h3><ul><li>Amazing messaging protocol → NATS Streaming’s client and server exchange binary messages using <a href="https://developers.google.com/protocol-buffers/">Google Protocol Buffers</a> (take a look)</li><li>Message persistence in-memory, files or database and allowing new subscribers to reply historical messages</li><li><strong>It guards your sequence order!</strong> NATS Streaming uses the concept of <em>channel</em> to represent an ordered collection of messages. We can think of a channel as a First In First Out (FIFO) queue where client can publish to and consume from</li><li>Support to replay messages in a stream</li><li>At-Least-Once Delivery model, giving reliable message delivery</li><li>Strong tool for creating a high available events streaming server especially when performance is your major goal</li><li>Rate matched on a per subscription basis</li></ul><h3><strong>How it Works?</strong></h3><p>I have personally used NATS Streaming server as <strong>my ‘event bus’</strong> in my microservices architecture.<strong> Every kind of event has its own ‘channel’. </strong>For example, if we will have a ticket buying app we will have event kinds such as ‘ticket:created’ and ‘ticket:updated’ that will be our <strong>channels</strong>, while the events will be specified to the requests. As a result, we will have a channel of ‘ticket:created’ with an event inside (a request that came is) that will look like: ticket:created <em>| created | userId: ‘abc’ | price: 50 | version: 1</em> . The versioning is super important so we will preserve the sequence of the actions (will be discussed). In addition, our NATS Streaming server will include Queue Groups that will manage the reading from our channels. Our server will preserve its listeners and publishers and will define subscription options for them. The <strong>stan </strong>client is actually our NATS Streaming client that we are going to discuss on. The server will check for heartbeats from the clients and define their availability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*cgOiZnGg4RL-e03c6hHJGA.png" /><figcaption>Not our final result (mid-example)</figcaption></figure><p>Before we are going to dive in through the implementation, lets start from our deployment.</p><h4>NATS Streaming Server Deployment and Configuration (Kubernetes)</h4><p>When using NATS Streaming we will have 3 main option to how connecting it to our Kubernetes cluster:</p><ol><li>using Ingress-Nginx as our gateway to the NATS Streaming cluster service:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*aco5D9DJXEFWH9PzKsRoBQ.png" /></figure><p>2. Instead of the Ingress expose the service via NodePort</p><p>3. The easy way that I want to focus on, via port-forwarding(didn’t to dive into k8s manual)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*sdKxY5xf1EaaW5QWibn5tg.png" /><figcaption>Port 4222 as an example</figcaption></figure><p>Now, we are going to build our k8s specification using the <a href="https://hub.docker.com/_/nats-streaming">NATS-Streaming image from docker hub</a>. Take a look for a yaml file configuration example:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nats-depl<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: nats<br>  template:<br>    metadata:<br>      labels:<br>        app: nats<br>    spec:<br>      containers:<br>        - name: nats<br>          image: nats-streaming:0.17.0<br>          args:<br>            [<br>              &#39;-p&#39;,<br>              &#39;4222&#39;,<br>              &#39;-m&#39;,<br>              &#39;8222&#39;,<br>              &#39;-hbi&#39;,<br>              &#39;5s&#39;,<br>              &#39;-hbt&#39;,<br>              &#39;5s&#39;,<br>              &#39;-hbf&#39;,<br>              &#39;2&#39;,<br>              &#39;-SD&#39;,<br>              &#39;-cid&#39;,<br>              &#39;ticketing&#39;,<br>            ]<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: nats-srv<br>spec:<br>  selector:<br>    app: nats<br>  ports:<br>    - name: client<br>      protocol: TCP<br>      port: 4222<br>      targetPort: 4222<br>    - name: monitoring<br>      protocol: TCP<br>      port: 8222<br>      targetPort: 8222</pre><p>Lets simplify it: In the first section of the example (before the 3 dashes in the middle) we are defining our <strong>NATS Streaming Deployment</strong> as ‘nats-depl’. Our base docker image will be NATS Streaming server from version 0.17.0. <strong>“-p”</strong> is port and then its number ‘4222’ and <strong>“-m”</strong> refers to our http monitoring (will be shown) <strong>“-hbi”</strong> refers to the time the server send heartbeat to check the , and <strong>“-hbt” </strong>refers to the client response. <strong>“-SD”</strong> enables debugging our cluster and <strong>“-cid” </strong>defines our cluster id which in this case will be ‘ticketing’.</p><p>After the dashes we define our NATS Streaming service. In this example, the server will listen on port ‘4222’ and enable http monitoring on ‘8222’.</p><p>To connect this deployment to our service we will make sure that we have at least these configurations: (from the view of my tickets service deployment, a service for doing CRUD actions on tickets): pay attention it is <strong>not </strong>the full yaml file.</p><pre>...<br>spec:<br>      containers:<br>        - name: tickets<br>          image: matanyemini/tickets<br>          env:<br>            - name: NATS_CLIENT_ID<br>              valueFrom:<br>                fieldRef:<br>                  fieldPath: metadata.name<br>            - name: NATS_URL<br>              value: &#39;<a href="http://nats-srv:4222&#39;">http://nats-srv:4222&#39;</a><br>            - name: NATS_CLUSTER_ID<br>              value: ticketing<br>...</pre><p>Now we can refer to this server according to our environment settings.</p><h3><strong>Defining our goal and architecture</strong></h3><p>Lets describe a common generic use case: we have a ticketing app that is going to include (actually you will need more, I want to put my focus on these three):</p><ol><li>Ticket service: for CRUD actions on our tickets.</li><li>Authentication service: for CRUD action on users and authentication (not our focus this is why I am simplifying it)</li><li>Orders service: for handling orders of users that are buying tickets</li></ol><ul><li>Some functional requirements: a ticket is reserved for 30 min when ordering (until purchase).</li></ul><p>Now, lets think about some common problems that we can encounter:</p><ol><li><strong>What happens if we want to horizontal scale one of our services? </strong>When you scale horizontally a service you increase its number of instances (adding more pods). So, how we can make sure that only one service will handle the event, and two or more? Think how bad it can be if 2 services will handle the same action. Our answer will be the usage of queue groups, so every service will handle a different event in the queue of the channel. =&gt; <strong>another problem!</strong></li><li><strong>What will happen if one action was failed from any reason and then we need to execute the next one? </strong>Think about a scenario when an action of ‘ticket:deleted’ was failed in one of our tickets service pods and then we will have a different event of ‘ticket:updated’ with the same ticket id? our program will crash. So, in order to handle these we will create a “processed sequence” in which the events are numbered. =&gt; <strong>another problem!</strong></li><li><strong>When the sequence is numbered, we will have a problem of sequential processing of our events. </strong>For this, our numbering will be dedicated to a specific functional object (user for example). So, we will have {ticket:created | id: ‘123’ | created | #1} and then {ticket:created | id: ‘123’ | updated | #2 | updateData} -&gt; <strong>a new problem!</strong> we will have to create channel for each object!</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*iW1uoMvSz02MClrhmr6o2g.png" /><figcaption>channel to every object!!</figcaption></figure><p>To solve all these problems, you will have to design your application in a different way, maybe not the obvious one for less experienced developers. Our concept:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*CN36z5Z7m19BV8etu99JjQ.png" /><figcaption>Simple option</figcaption></figure><p>After reading the explanations in the PNG that is mentioned above. We might have <strong>another problem: What if one of our services is down? </strong>how we can make sure that all the events will be executed? For this we have <strong>‘Durable Subscriptions’</strong> all our subscriptions from the NATS Streaming clients will be from this kind. This will make that when a service has successfully processed an event, he will send ACK that the action finished, and then the event is marked as ‘PROCESSED’ in the queue of the channel. Don’t forget the <strong>Queue Group</strong> feature that guarantees our subscribers list, even if they are temporarily unavailable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*uaDRY4XzWVtYxCufpKLO5Q.png" /></figure><p>When combining our conclusion with the example: (higher level look)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*g3wcgdVapfk2EN6nyQkV4Q.png" /><figcaption>I tried to simplify it as much as I can — some things that have been mentioned above are not included. And probably for a real ticketing app it is not enough.</figcaption></figure><h3>Base Listener and Publisher Implementation — using Node.js and TypeScript</h3><p>For using NATS Streaming, we will need to install the package <strong>‘node-nats-streaming’</strong></p><pre>import { Message, Stan } from &#39;node-nats-streaming&#39;;<br>import { Subjects } from &#39;./subjects&#39;;</pre><pre>interface Event {<br>  subject: Subjects;<br>  data: any;<br>}</pre><pre>export abstract class Listener&lt;T extends Event&gt; {<br>  abstract subject: T[&#39;subject&#39;];<br>  abstract queueGroupName: string;<br>  abstract onMessage(data: T[&#39;data&#39;], msg: Message): void;<br>  private client: Stan;<br>  protected ackWait = 5 * 1000;</pre><pre>constructor(client: Stan) {<br>    this.client = client;<br>  }</pre><pre>subscriptionOptions() { // How our client is going to behave<br>    return this.client<br>      .subscriptionOptions()<br>      .setDeliverAllAvailable() // send the event to those who can<br>      .setManualAckMode(true) // sending ack when the event processed - mentioned earlier in this story<br>      .setAckWait(this.ackWait) // how long to wait for ack<br>      .setDurableName(this.queueGroupName); // what queue group this listener is, and define him as durable! as mentioned earlier<br>  }</pre><pre>listen() {<br>    const subscription = this.client.subscribe(<br>      this.subject,<br>      this.queueGroupName,<br>      this.subscriptionOptions()<br>    );</pre><pre>subscription.on(&#39;message&#39;, (msg: Message) =&gt; {<br>      console.log(`Message received: ${this.subject} / ${this.queueGroupName}`);<br>      const parsedData = this.parseMessage(msg);<br>      this.onMessage(parsedData, msg);<br>    });<br>  }</pre><pre>parseMessage(msg: Message) {<br>    const data = msg.getData();<br>    return typeof data === &#39;string&#39;<br>      ? JSON.parse(data)<br>      : JSON.parse(data.toString(&#39;utf8&#39;));<br>  }<br>}</pre><p>The subjects are event types, for our example:</p><pre>export enum Subjects {<br>  TicketCreated = &#39;ticket:created&#39;,<br>  OrderUpdated = &#39;order:updated&#39;,<br>}</pre><p>And a <strong>Base Publisher</strong> will look like:</p><pre>import { Stan } from &#39;node-nats-streaming&#39;;<br>import { Subjects } from &#39;./subjects&#39;;</pre><pre>interface Event {<br>  subject: Subjects;<br>  data: any;<br>}</pre><pre>export abstract class Publisher&lt;T extends Event&gt; {<br>  abstract subject: T[&#39;subject&#39;];<br>  private client: Stan;</pre><pre>constructor(client: Stan) {<br>    this.client = client;<br>  }</pre><pre>publish(data: T[&#39;data&#39;]): Promise&lt;void&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>      this.client.publish(this.subject, JSON.stringify(data), (err) =&gt; {<br>        if (err) {<br>          return reject(err);<br>        }<br>        console.log(&#39;Event published&#39;);<br>        resolve();<br>      });<br>    }); <br>  }<br>}</pre><p>You can take those base classes and generate our of them you relevant listener and publisher. Listener will consume the events in the channels while publisher will emit the events to our NATS Streaming server.</p><p>Now lets define our events, for example we will create our ‘ticket:created’ event:</p><pre>import { Subjects } from &#39;./subjects&#39;;</pre><pre>export interface TicketCreatedEvent {<br>  subject: Subjects.TicketCreated;<br>  data: {<br>    id: string;<br>    title: string;<br>    price: number;<br>  };<br>}</pre><p>After setting the relevant possible events, and building robust base classes for both listener and publisher. We will need to create the derived listener that will include specification for the each event. For the example we will look at a <strong>‘ticket:created’ event listener</strong></p><pre>import { Message } from &#39;node-nats-streaming&#39;;<br>import { TicketCreatedEvent } from &#39;./ticket-created-event&#39;;<br>import { Subjects } from &#39;./subjects&#39;;<br>import { Listener } from &#39;./base-listener&#39;;</pre><pre>export class TicketCreatedListener extends Listener&lt;TicketCreatedEvent&gt; {<br>  subject: Subjects.TicketCreated = Subjects.TicketCreated;<br>  queueGroupName = &#39;tickets-service&#39;;</pre><pre>onMessage(data: TicketCreatedEvent[&#39;data&#39;], msg: Message) {<br>    console.log(&#39;Event data!&#39;, data);</pre><pre>msg.ack();<br>  }<br>}</pre><p>And a publisher will look like (‘ticket:created’ event publisher) — will be at orders service:</p><pre>import { Subjects } from &#39;./subjects&#39;;<br>import { TicketCreatedEvent } from &#39;./ticket-created-event&#39;;<br>import { Publisher } from &#39;./base-publisher&#39;;</pre><pre>export class TicketCreatedPublisher extends Publisher&lt;TicketCreatedEvent&gt; {<br>  subject: Subjects.TicketCreated = Subjects.TicketCreated;<br>}</pre><h3>Set our service to be a listener / publisher:</h3><p>Before connecting the clients (publisher/listener) we will need to wrap the implementation: (nats-wrapper)</p><pre>import nats, { Stan } from &#39;node-nats-streaming&#39;;</pre><pre>class NatsWrapper {<br>  private _client?: Stan;</pre><pre>get client() {<br>    if (!this._client) {<br>      throw new Error(&#39;Cannot access NATS client before connecting&#39;);<br>    }<br>    return this._client;<br>  }</pre><pre><strong>// the connect function is explained later</strong></pre><pre>connect(clusterId: string, clientId: string, url: string) {<br>    this._client = nats.connect(clusterId, clientId, { url }); </pre><pre>this._client.on(&#39;close&#39;, () =&gt; {<br>      console.log(&#39;NATS listener closed&#39;);<br>      process.exit();<br>    });</pre><pre>process.on(&#39;SIGINT&#39;, () =&gt; this.client.close());<br>    process.on(&#39;SIGTERM&#39;, () =&gt; this.client.close());</pre><pre>return new Promise((resolve, reject) =&gt; {<br>      this._client!.on(&#39;connect&#39;, () =&gt; {<br>        console.log(&#39;Connected to NATS!&#39;);<br>        resolve();<br>      });<br>      this._client!.on(&#39;error&#39;, (err) =&gt; {<br>        reject(err);<br>      });<br>    });<br>  }<br>}</pre><pre>export const natsWrapper = new NatsWrapper();</pre><p>The <strong>connect function </strong>receives its values from your startup file (index.ts for example). In there we should define the cluster id, the url, get having a client id, so the streaming server will know whom he is connected to.</p><pre>await natsWrapper.connect(<br>      process.env.NATS_CLUSTER_ID!,<br>      process.env.NATS_CLIENT_ID!,<br>      process.env.NATS_URL!<br>    );</pre><p>remember to check that those arguments are received!! those arguments are received from our deployment <strong>settings as environment variables — look above to where we created the yaml configuration file for one of our client’s deployment. </strong>The URL, the Cluster ID and the Client ID (from the service metadata name) are specified there.</p><p>Now we only have left the final action itself → we will look on our tickets service and particularly on the publish ‘ticket:created’ event.</p><pre>import { Publisher, TicketCreatedEvent } from &#39;@yemini/common&#39;;<br>import { Subjects } from &#39;@yemini/common&#39;;</pre><pre>export class TicketCreatedPublisher extends Publisher&lt;TicketCreatedEvent&gt; {<br>  subject: Subjects.TicketCreated = Subjects.TicketCreated;<br>}</pre><blockquote>(@yemini/common) is a common package that includes the things we have mentioned earlier — you can find it at NPM : <a href="https://www.npmjs.com/package/@yemini/common">https://www.npmjs.com/package/@yemini/common</a> → (this package include also error handler middleware and authentication via JWT) this meant to be for private usage, so there is no docs for now :) but you can take the things we have talked about..</blockquote><p>Then we can actually publish the event with the relevant data:</p><pre>...<br>      new TicketCreatedPublisher(natsWrapper.client).publish({<br>        id: ticket.id,<br>        title: ticket.title,<br>        price: ticket.price,<br>        userId: ticket.userId,<br>      });<br>...</pre><p>Remember we said that we expose our NATS Streaming service via port forwarding we should define it!</p><p>I am using minikube as my Kubernetes cluster, but the idea is the same</p><pre>$ kubectl get pods</pre><p>Check your nats-depl (as we named it before)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*qvQeW422YPwXUxQgrTVtdw.png" /></figure><p>and then:</p><pre>$ kubectl port-forward nats-depl-5458db5b74-24rc4 4222:4222</pre><p>Now, remember that our NATS Streaming service has also port 8222 exposed — for monitoring. You can go to your browser and enter localhost:8222 and see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*QoN_WLUvVY6N5e6emLNS5A.png" /></figure><p>There you can find info about the data is being transferred in each channel and etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*ZzYBzhIY65t1Kb67yh8PFA.png" /><figcaption>An example for pressing ‘server’ and viewing the connected clients</figcaption></figure><p>There you can also see the passed events and their data.</p><h3>Using NATS Streaming in a Microservices Architecture</h3><p>When building distributed systems, Microservices pattern is a great choice. In a Microservices architecture, you build applications by composing a suite of independently deployable, small, modular services. In order to solve practical challenges of Microservices with regards to managing distributed actions (like transactions) and data consistency, an event-driven and in particularly Event-Sourcing architecture is a highly recommended approach. Event Sourcing deals with an event store of immutable log of events, in which each log (a state change made to a domain object) represents an application state. Every log describes a state in the application. So, in NATS Streaming each log is actually an event that is appended to the relevant channel from where they can be published → Then, other services can subscribe those channels (contains messages) and consume them.</p><h3>In Conclusion</h3><p>When you build distributed systems, you can use <strong>NATS Streaming as the nervous system for your applications</strong> for publishing events to data streams and exchanging messages between different systems in asynchronous manner. When the performance is your event-driven application base, NATS Streaming can be the right tool for you! I <strong>will not</strong> recommend NATS Streaming for building enterprise queueing, but for smaller applications, this light-weight platform is amazing. In addition, I personally recommend you to use Golang when dealing with NATS Streaming, but the fun with Node.js beats my common logic :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*yEpxu9ihpvKvrRWEfSomKg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2595dd598acc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beyond-coding/nats-streaming-server-in-the-node-js-world-with-kubernetes-how-to-guide-2595dd598acc">NATS Streaming Server  in the Node.js World with Kubernetes How-To Guide</a> was originally published in <a href="https://medium.com/beyond-coding">Beyond Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker & Kubernetes Installation and Troubleshooting on WIN 10 Home]]></title>
            <link>https://medium.com/beyond-coding/docker-kubernetes-installation-and-troubleshooting-on-win-10-home-742b4f153efd?source=rss----3190dbc755f4---4</link>
            <guid isPermaLink="false">https://medium.com/p/742b4f153efd</guid>
            <category><![CDATA[windows-10]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[minikube]]></category>
            <dc:creator><![CDATA[Matan Yemini]]></dc:creator>
            <pubDate>Fri, 22 May 2020 16:19:31 GMT</pubDate>
            <atom:updated>2020-05-02T09:17:05.947Z</atom:updated>
            <content:encoded><![CDATA[<h3>Prepare for the unknown…</h3><p>You have to acknowledge the fact that using<strong> Windows 10 home edition is not optimal for running docker and kubernetes</strong>. You will probably get some <strong>non-deterministic errors</strong> in your usage. In the last section of the article we will go through some <strong>common errors and how to fix them</strong>.</p><h3>What is going to be covered?</h3><p><strong>This is not a guide for docker and k8s!</strong> I do not want to spend time explaining about what Kubernetes is and its building blocks like Pods, Replication Controllers, Services, Deployments ,or what is Docker all about. There are multiple articles on those stuff. <strong>Installation, common commands, and troubleshooting ‘cheat sheet’ only.</strong></p><h3>Installing Docker Toolbox</h3><p>Check this URL: <a href="https://docs.docker.com/toolbox/toolbox_install_windows/">Docker Toolbox</a></p><p>Follow this installation guide. When this page refers you to the “Toolbox releases” choose the latest version. <strong>You should not tackle any problem!</strong> Pay attention that when accessing docker from now, it will be via the VirtualBox IP address (default: 192.168.99.100). If something went wrong, check the troubleshooting section.</p><h3>What is minikube (in short)?</h3><p>If you want to run kubernetes on your machine locally, this is the best option for you. Pay attention, minikube is capable to run only a single node cluster in a VM at your local machine. After installation, you will be able to work with kubernetes clusters from your workstation.</p><p><strong>Installation (minikube &amp; kubectl):</strong></p><ul><li>Use <a href="https://chocolatey.org/install">Chocolatey</a> , it is convenient! (will automatically update your Path in the environment variables)</li></ul><pre>choco install minikube</pre><ul><li>Install kubernetes CLI (kubectl):</li></ul><pre>choco install kubernetes-cli</pre><ul><li>Now, we want to start our Minikube, you can use the<strong> ‘Docker Quickstart Terminal’ </strong>(check quick menu, it should have been installed from the ‘Docker Toolbox’).</li><li>We will define our Minikube to use VirtualBox and start it. It will take some time until Minikube will download the ISO images.</li></ul><pre>$ minikube start --vm-driver=virtualbox</pre><ul><li>Check by typing :</li></ul><pre> $ minikube status</pre><ul><li>The output should be:</li></ul><pre>host: Running<br>kubelet: Running<br>apiserver: Running<br>kubeconfig: Configured</pre><ul><li>Kubernetes cluster requires Master Node endpoint and credentials. If something went wrong and the output is not similar to what is written above, check the config by typing:</li></ul><pre>$ kubectl config view</pre><p>The output should be like this:</p><pre>apiVersion: v1<br>clusters:<br>- cluster:<br> certificate-authority: C:\Users\&lt;user&gt;\.minikube\ca.crt<br> server: <a href="https://192.168.99.102:8443/">https://&lt;minikube_ip&gt;:8443</a><br> name: minikube<br>contexts:<br>- context:<br> cluster: minikube<br> user: minikube<br> name: minikube<br>current-context: minikube<br>kind: Config<br>preferences: {}<br>users:<br>- name: minikube<br> user:<br> client-certificate: C:\Users\&lt;user&gt;\.minikube\profiles\minikube\client.crt<br> client-key: C:\Users\&lt;user&gt;\.minikube\profiles\minikube\client.key</pre><ul><li>If you have encoutered a different config / something went wrong -&gt; check the troubleshooting section or check the <a href="https://kubernetes.io/docs/setup/learning-environment/minikube/">docs</a>.</li></ul><p><strong>Installation </strong>(ingress-nginx):</p><ul><li>Adding load balancer + ingress controller: I personally prefer using <strong>ingress-nginx. </strong>In order to run it in your cluster, <strong>you should not run </strong>the mandatory command because you are using minikube. You should run:</li></ul><pre>$ minikube addons enable ingress</pre><p>Now, check that the controller is running (for further information go to the <a href="https://kubernetes.io/docs/tasks/access-application-cluster/ingress-minikube/">official documentation</a> :</p><pre>$ kubectl get pods -n kube-system</pre><blockquote>Output should include: nginx-ingress-controller-5984b97644-rnkrg 1/1 Running 0 1m Can take a while for running.</blockquote><p><strong>Short Intro and Installation</strong>(Skaffold):</p><ul><li>Skaffold is all about automating tasks in a kubernetes dev environment. It makes it super easy to update code in a running pod and create/delete all objects that are tied to a project at once. <strong>Installation via Chocolatey using</strong> PowerShell:</li></ul><pre>choco install skaffold</pre><p><em>Why Skaffold?</em></p><ul><li><strong>Without Skaffold</strong>, in order to update an image from code to the actual pod you will have to:</li></ul><pre>$ docker build -t &lt;docker_id&gt;/&lt;image&gt;:&lt;optional tag&gt; .<br>$ docker push<br>$ kubectl rollout restart deployment [depl_name]</pre><ul><li>An example of Skaffold configuration (react-app). This is the most simple example I could think about:</li></ul><pre>apiVersion: skaffold/v2alpha3<br>kind: Config<br>deploy:<br>  kubectl:<br>    manifests: # Where your k8s configuration files are placed<br>      - ./infra/k8s/*<br>build:<br>  local:<br>    push: false<br>  artifacts: # starting an array of your images <br>    - image: matanyemini/client # &lt;docker_id&gt;/&lt;image&gt;<br>      context: client # &lt;your folder name&gt; where the src is<br>      docker:<br>        dockerfile: Dockerfile<br>      sync:<br>        manual:<br>          - src: &#39;src/**/*.js&#39; # where your code is at<br>            dest: .</pre><ul><li>But with Skaffold, <strong>life are easier </strong>(think about changing a number of services) — at your root folder where scaffold is set, <strong>just insert</strong>:</li></ul><pre>skaffold dev</pre><p><em>sometimes it will throw errors, just give the command again</em></p><p>Now, whenever there is a change in one of your artifacts specifications (as mentioned in the example above) it should update everything automatically. Make sure you have ‘<em>nodemon’ </em>for starting the service again immediately.</p><blockquote><em>I think it is enough installation for this article. I have tried to simplify it as mush as possible. I assume that the users at WIN 10 Home are those who only want to try working with docker &amp; kubernetes and understand their basics.</em></blockquote><h3>Fixing common errors:</h3><ol><li><strong>My VirtualBox is not working</strong></li></ol><ul><li>Make sure virtualization is enabled at your machine (at task manager and BIOS):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*SDJ_rpw-2BCfOj4X--h8JA.png" /><figcaption>Task Manager</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*5xMx3yxrnbYP3x--g-sv0A.jpeg" /><figcaption>In the BIOS menu</figcaption></figure><ul><li>make sure Hyper-V is disabled at your ‘Windows Features’</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*27SktMp-7ahDA_AsJkMZsQ.png" /></figure><p><strong>2. Cannot get an answer from service when sending a request</strong></p><ul><li>first, get your minikube IP:</li></ul><pre>$ minikube ip</pre><ul><li>It is important to know the IP in order to test our deployment. For example, when using ‘Postman’ for checking our API we will insert ‘http://localhost:&lt;port&gt;/&lt;value&gt;’ but, when running minikube on windows you will have to change the ‘localhost’ to your minikube IP. So, it will be:<strong> ‘http://&lt;minikube_ip&gt;:&lt;Node Port&gt;/&lt;value&gt;</strong> (I won’t get into details with what Node Port is..). This is a solution for testing <strong>before you defined your paths in your nginx.</strong></li></ul><blockquote><strong>Pay attention</strong> that between the pods communication will be via their ClusterIP service respectively.</blockquote><ul><li>For example, you should define your axios request as follows:</li></ul><pre>await axios.get(&#39;http://&lt;Service&gt;:&lt;port&gt;/events&#39;);</pre><ul><li>Then you should check your paths at the ingress configuration file that every path has its matching<em> ‘serviceName’</em> and <em>‘servicePort’</em>:</li></ul><pre>...<br>- path: /posts/create<br>            backend:<br>              serviceName: &lt;Service&gt;<br>              servicePort: &lt;port&gt;</pre><p><strong>3. Cannot find host using Nginx</strong></p><ul><li>First, open the host file from the location: C:\Windows\System32\Drivers\etc\hosts</li><li>Open with code editor and check if you added the host as in the yaml configuration file with the minikube IP (not with local host) and then the host specification. For Example: &lt;minikube_ip&gt; &lt;host&gt;</li></ul><pre>192.168.99.102 posts.com</pre><p>In the ingress service yaml this specification should look like: (my service name is posts, serving port 4000)</p><pre>...<br>        paths:<br>          - path: /posts<br>            backend:<br>              serviceName: posts-clusterip-srv<br>              servicePort: 4000</pre><ul><li>Now, try insert the relevant path, it should work. If not, please comment with error message and relevant log.</li></ul><p>4. <strong>Cannot pass parameters through the URL when using ingress-nginx</strong></p><ul><li>In the ingress service configuration file you can not use parameters inside the URL in the ‘path attribute’. You will have to change it to <strong>regular expression </strong>. For example:</li></ul><pre><strong>old</strong>: /posts/:id/comments <strong>=&gt; new:</strong> /posts/?(.*)/comments</pre><ul><li>You will also need to enable the regex usage by adding an <strong>annotation </strong>(in the annotations specifications):</li></ul><pre>nginx.ingress.kubernetes.io/use-regex: ‘true’</pre><p>5. <strong>Some paths are not being served after running ingress-nginx</strong></p><p><strong>Important Note:</strong> the paths definitions in the ingress configuration file should be ordered from <strong>greatest importance down to latest importance</strong>. Look at this<strong> simple example </strong>(Tried to simplify as much as possible this section) of my spec section:</p><pre>spec:<br>  rules:<br>    - host: posts.com<br>      http:<br>        paths:<br>          - path: /posts/create<br>            backend:<br>              serviceName: posts-srv # could be any &lt;Service&gt;<br>              servicePort: 4000<br>          - path: /posts<br>            backend:<br>              serviceName: query-srv<br>              servicePort: 4002<br>          - path: /posts/?(.*)/comments<br>            backend:<br>              serviceName: comments-srv<br>              servicePort: 4001<br>          - path: /?(.*)/<br>            backend:<br>              serviceName: client-srv<br>              servicePort: 3000</pre><p>6.<strong> Failed running react app in a docker container</strong></p><ul><li>If the app was created by using ‘create-react-app’, you might have encountered this: common <a href="https://github.com/facebook/create-react-app/issues/8688">bug</a> (hopefully it will be closed..)</li><li>To solve it you have to update your Dockerfile (this is also an example of node based app Dockerfile). I assumed you have already <strong>updated your requests URLs</strong> according the host.</li></ul><pre># basic setup image<br>FROM node:alpine</pre><pre><strong>ENV CI=true</strong></pre><pre># our working directory<br>WORKDIR /app<br>COPY package.json ./</pre><pre># what to run if something from the above was changed<br>RUN npm install</pre><pre># copying relevant code<br>COPY ./ ./</pre><pre># running command as defined in “scripts”<br>CMD [ “npm”, “start” ]</pre><p>7. <strong>My docker build has not succeeded</strong></p><ul><li>First, check your code and dependencies. Second, restart the docker machine. Be aware that it can happen from time to time, without having any mistakes:</li></ul><pre>$ docker-machine restart</pre><p>8. <strong>My minikube cluster went wrong</strong></p><ul><li>Sometimes (for me it happens when I left my PC on for long time) minikube behavior is not as expected, try resetting it:</li></ul><pre>$ minikube delete <br>$ minikube start </pre><p>9. <strong>Unable to connect to the server: dial tcp 192.168.99.100:8443: i/o timeout</strong></p><ul><li>First, try re-run minikube with the configuration:</li></ul><pre>$ minikube delete<br>$ minikube start --vm-driver=virtualbox</pre><ul><li>If it still shows up, try disabling your VPN and reinstall minikube and kubectl. Check <a href="https://github.com/kubernetes/minikube/issues/2554">this issue</a> on GitHub</li></ul><p>10. <strong>Getting CrashLoopBackOff Error for &lt;number&gt; pods due to Error syncing pod</strong></p><ul><li>First, check that the app is running fine, and has all of its dependencies. Then, After the deployment, check the node capacities with kubectl describe nodes for example, Allocatable CPU: 1800m Already used by pods in kube-system namespace: 100m + 260m + +100m + 200m + 20m = 680m. Which means 1800m — 680m = 1120m is left for you to use. So, if your pod or pods request for more than 1120m CPU, they will not fit on this node.</li><li>In case, there is enough cpu for your pods to use and still you are getting insufficient CPU error, check if you are setting the cpu request and limit params correctly. See <a href="https://kubernetes.io/docs/tasks/configure-pod-container/assign-cpu-resource/#specify-a-cpu-request-and-a-cpu-limit">this</a> from the official documentation.</li><li>If it still not working, see the full and ongoing <a href="https://github.com/kubernetes/kubernetes/issues/33777#issuecomment-426487268">issue at GitHub</a></li></ul><h3>Conclusion</h3><p>I hope you have found this post helpful for setting up your basic environment for using Kubernetes and Docker at your local Windows (Home) machine. If you have any improvement suggestions please comment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*xIzbfE1PPI6Xj6Y7wakaRw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=742b4f153efd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beyond-coding/docker-kubernetes-installation-and-troubleshooting-on-win-10-home-742b4f153efd">Docker &amp; Kubernetes Installation and Troubleshooting on WIN 10 Home</a> was originally published in <a href="https://medium.com/beyond-coding">Beyond Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>