<?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 Sam Thomas on Medium]]></title>
        <description><![CDATA[Stories by Sam Thomas on Medium]]></description>
        <link>https://medium.com/@sam-thomas?source=rss-f0d87e545507------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*F9PehblQQfowQHWxP7I_Xg.jpeg</url>
            <title>Stories by Sam Thomas on Medium</title>
            <link>https://medium.com/@sam-thomas?source=rss-f0d87e545507------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 09:18:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sam-thomas/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[How to setup static outbound IP in DigitalOcean Kubernetes (DOKS)?]]></title>
            <link>https://sam-thomas.medium.com/how-to-setup-static-outbound-ip-in-digitalocean-kubernetes-doks-5cfb65e69165?source=rss-f0d87e545507------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cfb65e69165</guid>
            <category><![CDATA[droplet]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[digitalocean]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[static-ip]]></category>
            <dc:creator><![CDATA[Sam Thomas]]></dc:creator>
            <pubDate>Sat, 02 Sep 2023 23:20:54 GMT</pubDate>
            <atom:updated>2023-09-02T23:20:54.356Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8su6B8LbBIFtm-1N6NZ5Qw.png" /></figure><h4>DigitalOcean VPC Gateway configuration for Droplets and Kubernetes Clusters.</h4><p>There are plenty of reasons to route all of your traffic through a single IP such as IP Whitelisting and security. This solution can be achieved in DigitalOcean droplet using something like VPC Gateway. But what about configuring static outbound IP in DigitalOcean managed Kubernetes AKA as DOKS ? Luckily it is very similar to DigitalOcean VPC Gateway configuration. Let’s take a look at how it works. Check out official documentation of configuring VPC Gateway <a href="https://www.notion.so/How-to-setup-static-outbound-ip-in-DigitalOcean-managed-Kubernetes-6af9083927d54cc9896c960daf221ddf?pvs=21">here</a>. I will be referring DigitalOcean VPC Gateway as VPC Gateway and DOKS as Kubernetes[ Cluster] from now onwards for simplicity.</p><h3>Prerequisites</h3><ol><li>DigitalOcean Droplet/Droplets</li><li>DigitalOcean Kubernetes Cluster</li><li>Access to both Droplets and Cluster via SSH and Kubectl</li></ol><h3>DigitalOcean VPC Gateway Configuration</h3><p>In a simple VPC config we have 3 components. First we have the <a href="https://en.wikipedia.org/wiki/Virtual_private_cloud">VPC</a> (Virtual Private Cloud) it self which belongs to a location provided by DO. Next we have two droplets belongs to the same <strong>VPC</strong> (Droplets inside the same VPC share a private network with associated private IPs). First we have our <strong>gateway droplet</strong> and then we have our <strong>backend droplet</strong> or multiple backend droplets according to your requirement. There is no configuration needed for VPC after creation. But configuration is involved in rest of the components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FoQW4XF1pqwMbJ92vsFjig.png" /><figcaption>VPC Gateway with backend droplets</figcaption></figure><h3>Gateway Droplet Configuration</h3><p>There are two steps in configuring the gateway droplet. First we need to enable IP forwarding using the command</p><pre>sysctl -w net.ipv4.ip_forward=1</pre><p>To persist this change after reboot we need to add net.ipv4.ip_forward=1 to /etc/systcl.conf</p><p>Next we need to configure <strong>Network address translation</strong> (NAT) to route traffic between our backend resources and public internet. Using the following <em>iptables</em> command we can configure the gateway droplet to translate traffic from our VPC network’s subnet to the public IP of the gateway droplet. Replace the &lt;vpc_network_prefix&gt; with our VPC Network private IP prefix. (Looks something like 10.118.0.0/20 right next to our VPC name)</p><pre>iptables -t nat -A POSTROUTING -s &lt;vpc_network_prefix&gt; -o eth0 -j MASQUERADE</pre><blockquote><em>The default name of the public network interface for DO droplet is </em><em>eth0. If you have changed this, use </em><em>ip -br a command to get the public interface and replace </em><em>eth0 with the new interface name.</em></blockquote><p>To persist these changes after rebooting we have install iptables-persistent</p><pre>sudo apt-get install iptables-persistent</pre><p>Select “<strong>Yes”</strong> when iptables-persistent asks if you want to save the current IPV4 rules.</p><h3>Backend Droplet Configuration</h3><p>Now for the backend droplets. Since we are going to redirect backend droplet internet traffic through the gateway droplet, we have to login to the backend droplet through gateway droplet to avoid disconnection when we update the IP routes.</p><pre>ssh -o ProxyCommand=&quot;ssh -W %h:%p root@&lt;public_IP_of_gateway_Droplet&gt;&quot; root@&lt;private_IP_of_backend_Droplet&gt;</pre><p>Here we have to add/update two routing table entries. First we need to find out the default gateway of our droplet and add an IP route to the network configuration to retain the droplet’s access to the metadata endpoint(169.254.169.254) provided by DigitalOcean.</p><pre>curl -s &lt;http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/gateway&gt;</pre><p>This command returns the current default gateway IP address of the droplet. Use the IP from the above command to replace &lt;default-gateway-ip&gt; when running following command.</p><pre>ip route add 169.254.169.254 via &lt;default-gateway-ip&gt; dev eth0 # returns nothing as output</pre><p>Next we can change the default gateway for the outward traffic to our gateway droplet by running the following command. (Private IP of the droplet will be available in the droplet DO dashboard)</p><pre>ip route change default via &lt;private_IP_of_gateway_Droplet&gt;</pre><p>Next we need to edit the /etc/netplan/50-cloud-init.yaml file to persist the changes after reboot. We have to remove the routes portion from the eth0 interface and add the new route to the eth1 interface.</p><pre>network:<br>    version: 2<br>    ethernets:<br>        eth0:<br>            addresses:<br>            - 137.184.174.21/20<br>            - 10.20.0.7/16<br>            match:<br>                macaddress: 86:bc:46:82:4d:95<br>            mtu: 1500<br>            nameservers:<br>                addresses:<br>                - 67.207.67.3<br>                - 67.207.67.2<br>                search: []<br>						# remove the following<br>            routes:<br>            -   to: 0.0.0.0/0<br>                via: &lt;original gateway address&gt;<br>						# till here<br>            set-name: eth0<br>        eth1:<br>            addresses:<br>            - 10.118.0.4/20<br>            match:<br>                macaddress: 5a:59:57:e0:f3:9d<br>            mtu: 1500<br>            nameservers:<br>                addresses:<br>                - 67.207.67.3<br>                - 67.207.67.2<br>                search: []<br>            routes:<br>            -   to: 0.0.0.0/0<br>                via: &lt;gateway droplet private ip address&gt;<br>            set-name: eth1</pre><p>After the changing the network file. Run netplan apply to apply the changes. Run curl -4 &lt;https://icanhazip.com/&gt; to verify if the traffic is being routed through the gateway. Please remember that you will have to use the proxy ssh to access the backend droplet from now onwards.</p><h3>DigitalOcean Kubernetes Egress Configuration.</h3><p>To configure egress inside DOKS we need to two things. First we need a VPC gateway droplet configured. Checkout the previous section to see how to do that and come back once it’s configured properly. Next we need to configure our K8s cluster to route network traffic through previously configured gateway. Under the hood the process is really similar to how we did things in the simple gateway config with backend droplets.As you can see in the below image you can configure both droplets and k8s cluster to route your traffic through a single VPC gateway. This is very helpful and DigitalOcean doesn’t provide any simple tool to achieve this like other cloud providers. But it’s achievable through some configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i05ecTwpF-w5Vvw_ix9V2A.png" /><figcaption>VPC Gateway with Kubernetes Cluster</figcaption></figure><h3>Static Routes Operator</h3><p>DigitalOcean has released <a href="https://github.com/digitalocean/k8s-staticroute-operator">Static Routes Operator</a> CRD for updating the linux routing table of each worker nodes inside our cluster. Once installed, it deploys the static route operator daemonset in each worker node to manage the linux routing table. As you can see this is very similar to the backend droplet configuration in the previous section.</p><p>Deploy Static Routes Operator by running the following command. Also check github release page to find the lates version of Static Routes Operator.</p><pre>kubectl apply -f &lt;https://raw.githubusercontent.com/digitalocean/k8s-staticroute-operator/main/releases/v1/k8s-staticroute-operator-v1.0.0.yaml&gt;</pre><p>After deploying check pods inside static-routes namespace to see if everything is up and running.</p><pre>kubectl get pods -n static-routes</pre><p>Output should look similar to:</p><pre>NAME                             READY   STATUS    RESTARTS   AGE<br>k8s-staticroute-operator-77h4g   1/1     Running   0          28d<br>k8s-staticroute-operator-cxdfn   1/1     Running   0          28d<br>k8s-staticroute-operator-f558l   1/1     Running   0          28d<br>k8s-staticroute-operator-hdfv4   1/1     Running   0          28d</pre><p>Now <strong>Static Routes Operator</strong> is deployed and ready to use. Next we can create a static route to our gateway. Use the following <a href="https://github.com/digitalocean/container-blueprints/blob/main/DOKS-Egress-Gateway/assets/manifests/static-routes/public-egress-example.yaml"><em>StaticRoute</em></a> config file provided by DigitalOcean and replace the gateway with our gateway private IP address. We are using public <a href="https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing">CIDRs</a> to redirect our egress traffic through the gateway, but there’s caveat with this approach. Like in the backend droplet metadata API there are internal services inside k8s cluster that need access to the DigitalOcean APIs. (I assume that those APIs are using the IP of the droplet to identify the source and provide response accordingly and routing traffic through the gateway could break this functionality. This is purely my assumption.) So the solution is to avoid the CIDRs that overlap with DO Public API endpoints. These are already commented out in the default configuration provided by DO.</p><pre>apiVersion: networking.digitalocean.com/v1<br>kind: StaticRoute<br>metadata:<br>  name: public-egress<br>spec:<br>  destinations:<br>    - &quot;0.0.0.0/5&quot;<br>    - &quot;8.0.0.0/7&quot;<br>    - &quot;11.0.0.0/8&quot;<br>    - &quot;12.0.0.0/6&quot;<br>    - &quot;16.0.0.0/4&quot;<br>    - &quot;32.0.0.0/3&quot;<br>    # - 64.0.0.0/2    NOT TO BE USED! Overlaps with DO API endpoints.<br>    # - 128.0.0.0/3   NOT TO BE USED! Overlaps with DOKS API endpoints.<br>    - &quot;160.0.0.0/5&quot;<br>    - &quot;168.0.0.0/6&quot;<br>    - &quot;172.0.0.0/12&quot;<br>    - &quot;172.32.0.0/11&quot;<br>    - &quot;172.64.0.0/10&quot;<br>    - &quot;172.128.0.0/9&quot;<br>    - &quot;173.0.0.0/8&quot;<br>    - &quot;174.0.0.0/7&quot;<br>    - &quot;176.0.0.0/4&quot;<br>    - &quot;192.0.0.0/9&quot;<br>    - &quot;192.128.0.0/11&quot;<br>    - &quot;192.160.0.0/13&quot;<br>    - &quot;192.169.0.0/16&quot;<br>    - &quot;192.170.0.0/15&quot;<br>    - &quot;192.172.0.0/14&quot;<br>    - &quot;192.176.0.0/12&quot;<br>    - &quot;192.192.0.0/10&quot;<br>    - &quot;193.0.0.0/8&quot;<br>    - &quot;194.0.0.0/7&quot;<br>    - &quot;196.0.0.0/6&quot;<br>    - &quot;200.0.0.0/5&quot;<br>    - &quot;208.0.0.0/4&quot;<br>  gateway: &quot;&lt;YOUR_EGRESS_GW_DROPLET_PRIVATE_IP_HERE&gt;&quot;</pre><p>Save the default config as public-egress-example.yaml and run kubectl apply -f public-egress-example.yaml to deploy the static route. verify the deployment by running kubectl get staticroutes. Now you can ssh into any of the pods and run curl -4 &lt;https://icanhazip.com/&gt; to verify if the traffic is being routed through the gateway. Please note that if your traffic is not being routed to the gateway for a specific IP. That IP could be missing from the list of destination. You could add the CIDR or the IP to the list and it will be routed as expected. You can see all the IP ranges used by DigitalOcean <a href="https://ipinfo.io/AS14061">here</a> and <a href="https://github.com/SecOps-Institute/Digitalocean-ASN-and-IPs-List">here</a>. Restrain from using these IP ranges in your configuration.</p><h3>Conclusion</h3><p>Static IP is a requirement when it comes to normal server instances as kubernetes is widely used these days, the same is required in kubernetes. Although there is no simple built in solution for that in DigitalOcean, it is possible with some configuration. It can be little more hands-on than other cloud providers but I prefer to do it this way for more control. If you are only looking to do this setup with your K8s cluster there is a simpler method where infrastructure orchestration tool like <a href="https://www.crossplane.io/">crossplane</a> is deployed inside your cluster and used to interact with DigitalOcean to create gateway droplet as a k8s resource, where you can manage the droplet through k8s and kubectl. I prefer the non-crossplane way to avoid deploying crossplane in my cluster. You can find the DO documentation for crossplane setup <a href="https://github.com/digitalocean/container-blueprints/tree/main/DOKS-Egress-Gateway">here</a>. Also there’s another extra layer you could add to make sure that static IP will never change. You can configure the gateway droplet to send outbound traffic through the reserved IP (formerly known as floating IP). Check out <a href="https://docs.digitalocean.com/products/networking/reserved-ips/how-to/outbound-traffic/">this</a> documentation from DigtialOcean to do that. Please note that static IP does not support certain type of traffic such as SMTP. Please raise a ticket if you are having trouble with outbound traffic after configuring static IP.</p><h3>References</h3><ul><li><a href="https://github.com/digitalocean/container-blueprints/tree/main/DOKS-Egress-Gateway">container-blueprints/DOKS-Egress-Gateway at main · digitalocean/container-blueprints</a></li><li><a href="https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing">Classless Inter-Domain Routing - Wikipedia</a></li><li><a href="https://docs.digitalocean.com/products/networking/vpc/how-to/create/">How to Create a VPC | DigitalOcean Documentation</a></li><li><a href="https://docs.digitalocean.com/products/networking/vpc/how-to/configure-droplet-as-gateway/">How to Configure a Droplet as a VPC Gateway | DigitalOcean Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cfb65e69165" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes IngressClass | error=”ingress does not contain a valid IngressClass"]]></title>
            <link>https://sam-thomas.medium.com/kubernetes-ingressclass-error-ingress-does-not-contain-a-valid-ingressclass-78aab72c15a6?source=rss-f0d87e545507------2</link>
            <guid isPermaLink="false">https://medium.com/p/78aab72c15a6</guid>
            <category><![CDATA[nginx-ingress]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Sam Thomas]]></dc:creator>
            <pubDate>Mon, 11 Jul 2022 10:40:04 GMT</pubDate>
            <atom:updated>2022-07-11T10:40:43.076Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kubernetes IngressClass | error=&quot;ingress does not contain a valid IngressClass&quot;</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8Y9BJjYKHojrLBZOsQgbw.png" /></figure><p>If you have come across this error after updating Kubernetes to the latest version, this solution should work.</p><p>IngressClass is ingress resource that was added in Kubernetes 1.18 helps to target a specific Ingress controller while running multiple ingress controller in a single cluster.</p><p>Earlier <a href="http://kubernetes.io/ingress.class">kubernetes.io/ingress.class</a> annotation was used to specify the ingress controller which is deprecated by 1.18. Here we are directly mentioning the name of the controller rather than creating a the resource.</p><h3>Solution</h3><h3>Step 1 — Create IngressClass resource</h3><p>First we have to create IngressClass ingress resource. (Check if there is any kubectl get ingressclass -A -o yaml )</p><pre>apiVersion: networking.k8s.io/v1<br>kind: IngressClass<br>metadata:<br>  name: nginx<br>spec:<br>	# use your controller name.<br>  controller: k8s.io/ingress-nginx</pre><h3>Step 2 — Create/Update Ingress</h3><p>Update ingress resource spec.ingressClassName with ingress class name nginx. This should resolve the problem.</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: minimal-ingress<br>  annotations:<br>    nginx.ingress.kubernetes.io/rewrite-target: /<br>spec:<br>  ingressClassName: nginx<br>  rules:<br>  - http:<br>      paths:<br>      - path: /testpath<br>        pathType: Prefix<br>        backend:<br>          service:<br>            name: test<br>            port:<br>              number: 80</pre><h3>Set Default IngressClass</h3><p>Instead of assigning ingressClassName inside ingress resource, we can set a specific ingress controller as default by adding annotation [ingressclass.kubernetes.io/is-default-class](&lt;http://ingressclass.kubernetes.io/is-default-class&gt;) to &quot;true&quot;.</p><pre>apiVersion: networking.k8s.io/v1<br>kind: IngressClass<br>metadata:<br>  name: nginx<br>	annotations:<br>	ingressclass.kubernetes.io/is-default-class: &quot;true&quot;<br>spec:<br>	# use your controller name.<br>  controller: k8s.io/ingress-nginx</pre><p>One of the above solution should fix the invalid ingress class error. Please note that both Kubernetes and Ingress controller should be updated to the latest version to make sure this works.</p><p><a href="https://kubernetes.io/docs/concepts/services-networking/ingress/">https://kubernetes.io/docs/concepts/services-networking/ingress/</a></p><p><a href="https://kubernetes.io/docs/concepts/services-networking/ingress/#default-ingress-class">https://kubernetes.io/docs/concepts/services-networking/ingress/#default-ingress-class</a></p><p><a href="https://github.com/haproxytech/kubernetes-ingress/blob/master/documentation/ingressclass.md">https://github.com/haproxytech/kubernetes-ingress/blob/master/documentation/ingressclass.md</a></p><p><a href="https://stackoverflow.com/a/64912413/3473281">https://stackoverflow.com/a/64912413/3473281</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78aab72c15a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Redis is the new best database ?]]></title>
            <link>https://sam-thomas.medium.com/why-redis-is-the-new-best-database-4863aed99a43?source=rss-f0d87e545507------2</link>
            <guid isPermaLink="false">https://medium.com/p/4863aed99a43</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Sam Thomas]]></dc:creator>
            <pubDate>Fri, 01 Jul 2022 04:44:13 GMT</pubDate>
            <atom:updated>2022-07-01T04:44:13.907Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*XPtmZDvqK41JrE1reRahcA.png" /></figure><h3>Why Redis is the new best database ?</h3><p>Redis is a simple in-memory key value database mainly used for caching. Redis used to be a simple in-memory database. Now Redis is much more than that. Thanks to Redis modules, apart from the simple data structures such as strings, sets, maps, streams, etc. Redis can now support more complicated operations and data structures like full text search, json, graph and many more. In this article we will look into two components of <a href="https://redis.io/docs/stack/">Redis Stack</a>. RediSearch and RedisJSON are two powerful plugins built top on Redis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*rTUk6EGg8dFFg15kaOlCWw.png" /></figure><blockquote><em>If you want to use RedisJSON/RediSearch and try along, check out </em><a href="https://redis.io/docs/stack/get-started/install/docker/"><em>docker installation</em></a><em> or use </em><a href="https://redis.com/try-free/"><em>Redis cloud</em></a><em> free account. Redis cloud gives out $200 credit for free for new accounts.</em></blockquote><h3>RedisJSON</h3><p>Json is the default language of web. Json is so powerful that we all started using json databases like MongoDB and DynamoDB everywhere in our applications. Now Redis supports json natively, Thanks to RedisJSON. Before RedisJSON the only way to store json inside Redis was by serialising and deserialising into Json and string back and forth. Or we can use Hash to store Json, but Hash only supports single level, to store multi level Json we have to include keys inside Hashes. All of this adds up as overhead to our application.</p><p>But with RedisJSON we have all the control to store and manipulate json natively. RedisJSON provides all the control but with best latency ever possible.</p><p>Once you have a Redis database ready we can start interacting with it. <a href="https://redis.com/redis-enterprise/redis-insight/">RedisInsight</a> is the best GUI available to interact with Redis and Redis modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-sCLaw5e7F9H_80riVx5EA.png" /></figure><p>As you can see above after installation use the “ADD REDIS DATABASE” option to add your database and connect to the database. Explaining everything inside RedisInsight is far from the scope of this article. But for now we can use the <strong>Workbench</strong> and <strong>Command Helper</strong> to check out the RedisJSON and RediSearch.</p><p>Let’s look at the Redis module command structure.</p><pre>&lt;MODULE&gt;.&lt;OPERATION&gt; KEY VALUE/PATH .</pre><p>This is the usual structure of a Redis module command. Let’s look at couple of RedisJSON command we are going to use for our very interesting project we are going to do. Let’s store a simple json data to Redis.</p><pre>JSON.SET milkyway $ &#39;{&quot;age&quot;: &quot;13B&quot;, &quot;members&quot;: [&quot;Mercury&quot;, &quot;Venus&quot;, &quot;Earth&quot;, &quot;Mars&quot;, &quot;Jupitor&quot;, &quot;Saturn&quot;, &quot;Uranus&quot;, &quot;Neptune&quot;, &quot;Pluto&quot;]}&#39;</pre><p>Here milkyway is the key of the document and $ denotes that it is the root of the document. Run this command inside the workbench and you will get &quot;OK&quot; as response. Congratulation you have successfully stored a json document inside Redis.</p><p>Now let’s retrieve the Json document stored using the key.</p><pre>JSON.GET milkyway $</pre><p>The above command returns then entire document stored. What if you only want to access the array inside the document ? Use the following command.</p><pre>JSON.GET milkyway $</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YEiKrPXHDc0eHg5PZUpCVw.png" /></figure><p>You can see all the outputs of the commands we tried in the above screenshot. Now let’s kick it up a notch by trying more complicated commands. First of all we have to remove Pluto from list of planets, Thanks to Neil deGrasse Tyson. We can pop our little dwarf planet out by <strong>JSON.ARRPOP</strong> command. This will remove the last element of the array.</p><pre>JSON.ARRPOP milkyway $..members</pre><p>Next up we can update the age our galaxy from 13 Billion to 13.6 Billion, Turns out 600 Million years is a very long time. We can use the same command used to create the document to update the document.</p><pre>JSON.SET milkyway $.age &#39;&quot;13.6B&quot;&#39;</pre><p>These are the basic commands inside the <strong>JSON</strong> Module. Check out the entire list of commands <a href="https://redis.io/commands/?group=json">here</a>.</p><h3>RediSearch</h3><blockquote><strong><em>full-text search</em></strong><em> refers to techniques for searching a single computer-stored document or a collection in a full-text database.</em></blockquote><p>RediSearch is a <strong>full-text search</strong> and <strong>indexing</strong> module built on top of Redis. RediSearch provides a simple and fast way to index and query data using any field, and do search and aggregation on an indexed dataset. RediSearch gives super powers to your Redis cache or database.</p><p>We can store data inside hash and create indexes on top of those records. This makes RediSearch very powerful and dynamic. Previously we had to query the entire data and iterate through it to search or modify. Now we can do complex aggregations like grouping and ordering on the data through queries. Since it’s built on top of Redis it is really fast.</p><p>The real magic is when you combine both RedisJSON and RediSearch. Apart from native data structures Redis supports indexing of json data too. This is the super power I mentioned.</p><p>Let’s look into the basic commands of RediSearch inside the demo.</p><h3>Demo</h3><p>Apart from coding, I am a passionate reader and I love fantasy books. So I combined both of my interest to come up with this demo idea. I want to store basic details of my favourite books inside Redis and build an api endpoint to retrieve information of the book. It’s nothing fancy but enough to dabble with most of the concept of RedisJSON and RediSearch.</p><p>First of all we need to insert json data(book data) into Redis for us to create indexes. I am using a simple javascript to upload all the book details to Redis</p><pre>async function insertJSON() {<br>  try {<br>    if (process.argv.length &lt; 3) {<br>        console.error(&quot;json filepath to be provided.&quot;)<br>        process.exit(1);<br>    }</pre><pre>    // read json file<br>    let buf = fs.readFileSync(path.join(__dirname, process.argv[2]));<br>    let JSONStr = buf.toString();<br>    let books = JSON.parse(JSONStr);</pre><pre>    const client = createClient();<br>    await client.connect();</pre><pre>    for (let i = 0; i &lt; books.length; i++) {<br>        const book = books[i];<br>        const key = &quot;book:&quot; + book.name.toLowerCase().replaceAll(&quot; &quot;, &quot;_&quot;);<br>        let r = await client.json.set(key, &#39;.&#39;, book);<br>        console.log(key, &quot; - &quot;, r);<br>    }</pre><pre>    await client.quit();<br>  } catch (e) {<br>    console.error(e);<br>  }<br>}</pre><p>Here I am not focusing too much on the key structure since my requirement is less complex and it is not relevant, But good key structure is always important for better access. All code examples and book json file are available in this <a href="https://github.com/samthom/my-library">repo</a>. Check out Github repo to follow along.</p><p>Now we have all the json documents stored inside Redis, which can be easily accessed, updated and manipulated natively.</p><blockquote><em>Note that inserting json data is not necessary to create new indexes. Indexes can be created independent whether documents exist or not, pre existing json documents will get indexed once the index is created.</em></blockquote><h3>Create json indexes</h3><p>Full-text search module commands follows the same format of json module commands. All commands starts with <strong>FT</strong> — Full text search.</p><pre>FT.CREATE {index_name} ON JSON PREFIX {count} {prefix} SCHEMA {identifier} AS {attribute} {attribute_type}...</pre><ol><li>index_name - This is the custom name that can be given to the index created. Usually idx:&lt;key&gt; is used as a conventions</li><li>ON JSON/HASH - Index can only be created on these both datatypes. (Default value is HASH)</li><li>PREFIX {count} {prefix} - Prefix keyword mentions the structure of the keys to be indexed. Count is the number of prefixes to be indexed and we can provide multiple key prefixes. Default value is *, which is all the keys. Consider our document key structure as book:the_book, to index all our document use PREFIX 1 book:.</li><li>SCHEMA {identifier} AS {attribute} {type}... - This is the schema definition part of the command. <em>identifier</em> is the name of the field to be indexed. For Hashes it the name of the field. For json it is the path to the json value. <em>attribute</em> is the alternate name to be given to easily identify the field and index. Attribute type follows the attribute type - type of index to be created for this field (NUMERIC, TEXT and TAG)</li></ol><p>Let’s look at a single entry of our document.</p><pre>{ <br>  &quot;name&quot;: &quot;The Book&quot;, // text<br>  &quot;author&quot;: &quot;Sam&quot;, <br>  &quot;year&quot;: &quot;2020&quot;, // text<br>  &quot;rating&quot;: 5, // numeric sortable<br>  &quot;cover&quot;: &quot;image.png&quot;,<br>  &quot;description&quot;: &quot;...&quot; // text <br>}</pre><p>From the above document let’s create the index for our library dataset. name, year and description fields are indexed as text. rating is indexed as number and sortable, so we can do sorting on rating.</p><p>Following command creates all the indexes we need with name idx:books.</p><pre>FT.CREATE idx:books ON JSON PREFIX 1 book: SCHEMA $.name AS name TEXT $.author AS author TEXT $.rating AS rating NUMERIC SORTABLE $.description AS description TEXT</pre><h3>Queries</h3><p>Now we can start querying using SEARCH Operation.</p><p>Simple Search on the book index. This returns all the json records with the word ‘Kaz’ indexed in any of the ‘TEXT’ attribute.</p><pre>FT.SEARCH idx:books Kaz</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k9s7XZtSbjJRZvA9LlLGcg.png" /></figure><p>To search a word only in a single attribute use @{attribute-name}:{word}.</p><pre>FT.SEARCH idx:books &#39;@description:Kaz&#39;</pre><p>To select fields to be returned use RETURN {count} {fields...}</p><pre>FT.SEARCH idx:books Kaz RETURN 2 name author</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uSA1SFCHUdK3gswzFdeXXw.png" /></figure><p><strong>Sorting</strong></p><p>To sort the output according to the rating we can use SORTBY and ASC/ DESC to sort in ascending order or descending order.</p><pre>FT.SEARCH idx:books * SORTBY rating DESC RETURN 2 name rating</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gUbLv1LswmniAZO2s9QrbA.png" /></figure><p>There is more cool stuff you can do with SEARCH. Check out more commands <a href="https://redis.io/commands/ft.search/">here</a>.</p><h3>Aggregation</h3><p>AGGREGATE extends the capability of full text search module. <strong>Aggregations</strong> can be done on the data instead of simply fetching the data using SEARCH.</p><p>Explaining the entire aggregation would be so long and out of scope of this article. But to understand the flexibility let’s look at some of requirement for out library application and solve it.</p><p>I want to find the top 5 authors I read most. Following AGGREGATE query will fetch the top authors I read most.</p><pre>FT.AGGREGATE idx:books * GROUPBY 1 @author REDUCE COUNT 0 AS no_of_books SORTBY 2 @no_of_books DESC LIMIT 0 5</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iAXDHjCUlypwjdiWFTNn6Q.png" /></figure><p>Looks like I am fan of Leigh Bardugo (Which is absolutely correct).</p><ol><li>AGGREGATE - Aggregation query</li><li>GROUPBY - Group by operator to group all the docs with same author</li><li>REDUCE - As the name suggest <em>REDUCE</em> is used on top of Grouped docs to reduce the docs in to a singe doc.</li><li>COUNT - Function to be executed on Grouped docs to reduce in to a single. <em>count</em> returns the number of records in a group. <em>AS</em> can be used to give a name for the value.</li><li>SORTBY - To sort the record on a sortable attribute. In this case it is the calculated value <em>no_of_books.</em> The format of <em>SORTBY</em> is little different from the SEARCH query, here we have to mention the <em>nargs</em> (number of arguments following <em>SORTBY</em>)</li><li>LIMIT - Limits the number of documents returned. We can paginate the result by providing the <em>offset</em> value after <em>LIMIT</em> and number of documents to be returned after <em>offset</em>.</li></ol><p>Check out this <a href="https://github.com/samthom/my-library">repo</a> for nodejs implementation of Redis full text search queries in this article.</p><h3>Conclusion</h3><p>Redis is a full fledged no-sql database with reliability and flexibility. Redis modules makes Redis more powerful and usable. Since it’s an in-memory database your queries can achieve crazy response times.</p><p>Try <a href="https://redis.com/try-free/">Redis Cloud</a> for free</p><p><a href="https://www.youtube.com/watch?v=vyxdC1qK4NE">Redis Enterprise</a></p><p><a href="https://developer.redis.com/">Redis Developer Hub</a></p><p><a href="https://redis.io/docs/stack/insight/">Redis Insight</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4863aed99a43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Networks]]></title>
            <link>https://sam-thomas.medium.com/docker-networks-af93e7d718db?source=rss-f0d87e545507------2</link>
            <guid isPermaLink="false">https://medium.com/p/af93e7d718db</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Sam Thomas]]></dc:creator>
            <pubDate>Sun, 27 Feb 2022 05:29:09 GMT</pubDate>
            <atom:updated>2022-05-13T06:23:30.814Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker 101: Docker Networks</h3><p>Hello friends! In previous post in this series I described what is <strong>Docker</strong> ? How it used ? and How you can get started with <strong>Docker</strong> ? In this post I will explain Networking concepts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XP1DTXGYzjjWfxCK" /><figcaption>Photo by <a href="https://unsplash.com/@hharritt?utm_source=medium&amp;utm_medium=referral">Hunter Harritt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Docker Networking</h3><p>Docker is very flexible and versatile when it comes configurations. Docker networking is used to enable and configure communication between other docker containers or outside services. Could be a database or REST API in other network. Docker supports different kind of networking configurations. Docker also has internal DNS service that adds new entry to the resolv.conf whenever a new container is created. Will explain in detail.</p><p>First of all will describe the underlying networking modes(Drivers). They are Host, Bridge, Overlay and Macvlan. Besides these there is none mode which basically disables networking of a container. This mainly used when there is some custom network driver is used.</p><h4>Bridge</h4><p>In Docker, <a href="https://docs.docker.com/network/bridge/">Bridge</a> is a software bridge that help all the containers to connect to the same bridge. So they can communicate and provide isolation to other containers that are not connected. This is the default network mode used if another mode is not defined. Bridge is applied only for containers in the same docker daemon. For communicating with other containers in another Docker daemon hosts we will have to use OS level routing or overlay mode.</p><h4>Host</h4><p><a href="https://docs.docker.com/network/host/">Host</a> network mode removes all the isolation between conatiner’s network and docker host network. The container will be sharing the host’s network. To make more sense, if your container is using port 8000 inside container then there is no need to publish that port using -p, You will be able to access your app at port 8000 of host&#39;s localhost/ip address. -p option is ignored when you are using host network mode.<br>host network mode is useful to reduce latency or expose large number of ports.</p><h4>Overlay</h4><p><a href="https://docs.docker.com/network/overlay/">Overlay</a> network enables networking between multiple Docker daemons. This can be used to connect swarm service together without any OS level routing configurations.</p><h4>Macvlan</h4><p><a href="https://docs.docker.com/network/macvlan/">Macvlan</a> let’s you to assign a MAC address to your container. This makes your container look like a physical device in your network. This is useful to monitor network traffic, making it look like a physical device. There is lot of configuration that can be done in macvlan mode.</p><p>Besides all these network drivers there are third-party network plugins available to integrate with different types of networks.</p><h3>Container Networking</h3><h4>Ports, IP Addresses and DNS</h4><p>Every container has a network interface with an IP address, gateway, routing table, DNS service and other networking details. When you are creating a container none of the container’s ports are published to the external world (If you are using host mode then no need). To publish a port to outside network or to a container which are not connected to the same network, we can use --publish or -p flag. This creates an firewall rule to map the container port to the port of the Docker host.<br>Whenever a container is connected to a network, an IP address is assigned from the pool of IP allocated to the network. This is useful for the Docker daemon to connect and act as DHCP server for the each container.<br>Whenever a container starts it can only be connected to a single network. But we can connect a running container to multiple networks using docker network connect command. In this case you can use --ip and --ip6 flags to specify the container&#39;s IP address on the additional network.<br>Like IP whenever a container is created the it is assigned with a hostname. Container&#39;s ID is used as default hostname. To provide custom hostname use --hostname flag. And same as IP address whenever we connecting our container to a existing container we can use --alias flag to provide an alias for the container in that network.<br>If this confuses and goes above your head. Just keep in mind that docker containers are just like your host system and contains all kind configurations for networking.</p><p>Demo — <a href="https://github.com/samthom/todo-app/tree/networking">https://github.com/samthom/todo-app/tree/networking</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af93e7d718db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What the hell is this Docker ?]]></title>
            <link>https://sam-thomas.medium.com/what-the-hell-is-this-docker-72401a414f08?source=rss-f0d87e545507------2</link>
            <guid isPermaLink="false">https://medium.com/p/72401a414f08</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Sam Thomas]]></dc:creator>
            <pubDate>Fri, 14 Jan 2022 16:10:29 GMT</pubDate>
            <atom:updated>2022-01-14T16:10:29.505Z</atom:updated>
            <content:encoded><![CDATA[<h3>What the hell is this Docker ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*B1YjAy4YHgNrDWfT" /></figure><p>If you are a developer or a computer science student or a software enthusiast you might have heard a term called “Docker”. You might know one or two things about docker also. This is not an article for an expert docker user. I am going to explain you — what is docker? what is containers and images? and how docker works?</p><h3>Introduction</h3><p>Docker is virtualization platform that helps developers to build light weight and portable applications. Important idea to keep in mind is that Docker is a tool. virtualization and containerization are the concept behind it. There is couple of alternatives for docker, but docker is widely accepted and supported in the community.<br>To understand why docker is relevant we have to go back to when applications are deployed without docker or any kind of containerization. Back then we used VMs(Short for virtual machines) to run our applications. It was okay till lot of configuration was involved.<br><strong>“It is working in my system”</strong><br>All of us might have said this statement at least once in our life time.<br>It was common for the deployments to go down due to misconfigurations or dependency inconsistency(Doesn’t mean deployments are not going down these days). So transporting the application with all the dependencies and configuration was really hard. That is when the idea of containerization was born. Containerization is the idea of bundling all the dependencies, configuration and the application into a single entity that can be transported and deployed easily. It provides portability, consistency and reliability.</p><h3>Example</h3><p>Let’s see how to convert an app into a docker image. Then I’ll explain the architecture of the docker and docker components that helped to create the image.<br>Consider we have a very simple nodejs application.</p><pre>// index.js<br>const express = require(&quot;express&quot;);<br>const port = process.env.PORT || 8000;</pre><pre>// Create express app instance<br>const app = express();</pre><pre>// Simple index route<br>app.get(&quot;/&quot;, (req, res) =&gt; res.send(&quot;Hello world&quot;));</pre><pre>// Start server<br>app.listen(port, () =&gt; console.log(`Server started at port ${port}`))</pre><p>We have a very simple nodejs application that starts simple server using express at port 8000 or the given port in the environment.<br>we can use a file named as <em>Dockerfile</em> to specify the instructions for the image build.</p><pre># Base &quot;image&quot;<br># This is the read only part. We are importing all the readonly layers which are predefined and adding our own steps into it.<br>FROM node:16-alpine</pre><pre># New steps/layers<br># Setting a working directory using `WORKDIR` command<br># Command sets the specified directory as the default dir for all the following commands. Such as RUN, CMD, ADD<br>WORKDIR /usr/src/app</pre><pre># Copy current directory to the image. Copies the entire project folder to the image for running.<br># Important whenever you copy/connect between host and guest in docker. Left is always host and right is guest. H<br># Here the first . denotes the host system dir and the second . denotes the remote dir inside guest(Image)<br>COPY . .</pre><pre># Install all the dependencies for the app to run<br>RUN npm install --production</pre><pre># Defining env variables. Most common way is to use a env file with `--env-file` flag or `-e` flag with env values directly specified in the command.<br>ENV PORT 8888</pre><pre># Exposing port<br>EXPOSE ${PORT}</pre><pre># Starting command specified. We can use `ENTRYPOINT` for the same purpose. This starts our application<br>CMD [ &quot;npm&quot;, &quot;run&quot;, &quot;start&quot; ]</pre><p>Above you can see the simplest <em>Dockerfile</em>. We will explain the <em>Dockerfile</em> in great detail later. Now we can use Docker build command to build an image of this app.<br>docker build -t &lt;image name&gt; .<br>Run this command to build the image. Last . denotes the path to the Dockerfile. Now we have an image of the application and we can test it using docker run -p 8000:8888 &lt;image name&gt; now we have an application running inside docker at port 8000. check browser to see if it&#39;s working</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*LrhGMLwFFB5EvOkvMIjRjg.png" /><figcaption>Hello world node application</figcaption></figure><p>So now we have working image and a container running in our local system.</p><h3>How it works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/0*HS4xA63Eo__3kBIS" /><figcaption>Docker Components</figcaption></figure><p>These are the components of Docker. Docker Client, Docker Host and Docker Registry.<br>Docker client is the most used way to interact with Docker. <strong>Docker CLI</strong> is a docker client. Whenever we use commands such as <strong>docker run</strong> or <strong>docker build</strong> client sends all this to the docker daemon.<br><strong>DockerHost</strong> is the combination of different components that helps to manage docker environment. It includes Docker Daemon, Images, Containers, Networking and Storage.</p><h3>Docker Daemon</h3><p>Docker daemon is the heart of docker. It keeps running in the background listening for the client requests, managing running containers, stored images and others. Whenever a request is received, it communicates with the underlying host operating system and start your container. Docker daemon is responsible for processing all the request received from CLI or REST API then pulling or building different images.</p><p>Check out <a href="https://dockerlabs.collabnix.com/beginners/components/daemon/">this</a> to learn more about Docker Daemon.</p><h3>Image vs Container</h3><p>Though we use terms image and container in same context. Both of them are not the same. Images are read only template that contains instruction to build the container. These instructions are files or commands required for running the container. This includes dependencies, source code and other libraries. Images are stored inside <strong>Docker Registry</strong> such as docker hub or AWS ECR.<br>A Docker container is the actual running instance of an image. Containers are the ultimate utility of docker, which provide a portable and light weight environment for deploying applications.</p><h3>Docker registry</h3><p>We can store all the images inside a docker registry. <a href="https://hub.docker.com/?ref=login#!">DockerHub</a> is an example for docker registry. Create an account in docker hub to push your image to the remote registry. We can store image as public or private. After creating a docker hub account use docker login command in your local system login. If you want to login to a private registry then you can use docker login &lt;registry&gt; to login.</p><p>To push your image to your registry use command docker push new-repo:tagname. Now you can go to docker hub and see your image updated in the registry. Now others can download and run it if want.</p><p>Next up we will look in to <strong>Docker Compose</strong> to run multiple containers at the same time. And how docker network and storage works.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72401a414f08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is gRPC ?]]></title>
            <link>https://sam-thomas.medium.com/what-is-grpc-cdd00c1322c6?source=rss-f0d87e545507------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdd00c1322c6</guid>
            <category><![CDATA[grpc-web]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[grpc]]></category>
            <dc:creator><![CDATA[Sam Thomas]]></dc:creator>
            <pubDate>Mon, 06 Sep 2021 05:17:10 GMT</pubDate>
            <atom:updated>2021-09-06T05:36:54.578Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yEJI9szaJ6myX8lC8y1sbQ.png" /></figure><h3>Why gRPC might not be right for you ?</h3><ol><li>What is gRPC ?</li><li>gRPC vs Http</li><li>gRPC Web</li><li>Why gRPC is not a replacement for REST API ?</li><li>Conclusion</li></ol><h3>What is gRPC ?</h3><p>In simple terms <a href="https://samthomas.tech/grpc.io">gRPC</a> is a RPC(Remote procedure call) framework developed by google. No, “g” in gRPC is not google. But google open sourced the project. Since then gRPC is trending. It uses <strong>protobuf</strong> (Protocol buffers) to define the functionality of a service. It acts as documentation for your service and using the same protobuf other services can call functions in your service. It is fast, reliable and trending. It supports streaming and it supports multiple languages. Then why it might not be right for you ? I have seen blog posts promoting gRPC as a alternative for REST. But from my experience gRPC Never meant to replace RESTful APIs. Why? Let’s see.</p><h3>gRPC vs REST</h3><p>First of all lets see what are the major difference between both gRPC and REST, but from a pure development experience perspective then functional perspective. REST service can be developed with most of the programming languages, and it’s same for gRPC. Eventhough gRPC libraries are not available for every programming languages. There are libraries available for mostly used development stacks. There is no in built documentations available for REST API, but we can use external tools like <a href="https://swagger.io/">swagger</a> which support <a href="https://spec.openapis.org/oas/v3.1.0">OpenAPI Specification</a>to build API Documentation. In gRPC <em>proto</em> files has to be created in advance to generate the platform specific library files. All of these proto files can be used as a documentation of a service. Though writing and handling proto files is tedious job, it pays off when it can be used as a valid contract between services. There is <a href="https://github.com/grpc/grpc/blob/master/doc/server-reflection.md">server reflection package</a> to expose available methods and payloads inside a grpc server. It comes in handy during debugging and development process.</p><p>REST is basically collection of requests with different http methods but it always follow request and response paradigm. It is simple to understand and conventional.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U7wvKLHqM7ex_TVh.png" /></figure><p>On the other side gRPC lets you to create 4 types of methods:</p><ul><li>Unary RPC It is more like a traditional request and response structure.</li><li>Server streaming Here client can send a request and recieve a stream of message from the server.</li><li>Client streaming Client can send a stream of data into the server and server returns a message back when stream ends.</li><li>Bi directional streaming Read-write stream. Two different streams therefore client and server can read and write in any order. Order of messages in stream is preserved.</li></ul><p>I am not explaining it in much detail. You can go to <a href="https://grpc.io/docs/what-is-grpc/core-concepts/">link</a> and check out yourself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*oToGAk3r72KlNJoWgDFHkQ.png" /></figure><p>Image shows the basic working of gRPC and how protos is exchanged between services.</p><p>Maintaining proto files is a tedious task because in microservice architecture we use multiple programmming languages for servers and clients. So we have to genereate server-side and client-side code from the protobuf file using protocol buffer compiler. It get’s difficult to handle manually when you have couple of services with different languages. Packaging of client-side/server-side code is mandatory using some kind of automation. So whenever a new version of proto file is updated in repository, client-side code can be generated using the plugin for multiple languages and others can easily update to it. This requires bit more resource and planning compared to REST.</p><h3>gRPC Web</h3><p>Yes. It is possible to directly access a gRPC server from web. But it comes with some of caveats. Right now gRPC does not support direct connection to any gRPC implementation. We have to use proxy like <em>Envoy</em> to connect to our service. Native support for <a href="https://github.com/grpc/grpc-web">gRPC web</a> is on the development road map. But till then if we want to connect our web app to a gRPC service we don’t have much options. And with different moving parts the complexity and possible points of failure goes up. This is without considering the resources and skill required to configure a envoy proxy and maintaining the same. Most of the small to medium projects might not require this level of complexity. Also all projects need not to be implemented in microservices architecture and building and maintaining a gRPC service for simple web app is bit of an over kill.</p><h3>Why gRPC is not a replacement for REST API ?</h3><p>I personally don’t think gRPC is supposed to replace REST API. It does not support web right out of the box. There is no point using it while you are working on a single service application. It is useful if you have any scenario in the system to stream any data in between like logs and events. But again that does not make gRPC and alternate solution for REST. gRPC will be very efficient if you want to build a cli or a package with communication to the server, gRPC is really apt for it. One example would be how google’s firebase package use RPC for their implementation. One another best scenario would be log/event/stream processing. Above all of it, resources needed to implement gRPC is higher than REST. So the application of REST and gRPC seems different to me. Even though it can be used interchangeably.</p><h3>Conclusion</h3><p>Don’t get me wrong gRPC is a great framework. It’s fun to play around with. But unless you are not utilizing features like Bi directional streaming and other streaming methods, the overhead has to be justified. Also the use case is really important when it comes to the adoption of gRPC. Using something like gRPC to just build a simple request-response microservice would be pointless.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdd00c1322c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using private docker registry inside kubernetes]]></title>
            <link>https://sam-thomas.medium.com/using-private-docker-registry-inside-kubernetes-46a3cede7cb1?source=rss-f0d87e545507------2</link>
            <guid isPermaLink="false">https://medium.com/p/46a3cede7cb1</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[digitalocean]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Sam Thomas]]></dc:creator>
            <pubDate>Wed, 04 Aug 2021 07:38:01 GMT</pubDate>
            <atom:updated>2021-08-04T07:38:01.429Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/797/0*GV77LE0_knYzhILO.png" /></figure><h3>Requirements</h3><ul><li>Kubernetes cluster (Access to the cluster via <em>kubectl</em>)</li><li>Private docker registry (I use Digital Ocean for demo)</li><li>Docker image</li></ul><p>Accessing public images in a public docker registry like <strong>Dockerhub</strong> is the default behaviour of a kubernetes cluster, unless you want to integrate your own private registry to access private docker images for obvious security reasons. Cloud service providers like AWS, Digital Ocean provides easy integration between own docker registry to managed kubernetes.<br>But configuring a <strong>baremetal</strong> kubernetes cluster to access your private registry comes with couple of steps including updating the deployment/pod yaml. I am using digital ocean docker registry for the reference. But steps are same for most of the providers.</p><blockquote><em>If you don’t have a cluster for demo. Check out </em><a href="https://kind.sigs.k8s.io/">Kind</a><em>. Kind helps you to run a kubernetes cluster locally in minutes. Or else you can use Katacoda or </em><a href="https://labs.play-with-k8s.com/">Play with kubernetes</a>.</blockquote><h3>Step 1</h3><h3>Dockerconfig.json</h3><p>First we have to get the cluster configured to authenticate to the private registry. A Kubernetes cluster uses the Secret of kubernetes.io/dockerconfigjson type to authenticate with a container registry to pull a private image. We can do it in two methods. First method is to use the <em>config.json</em> file and the second method requires your username, password and email.<br>In digital ocean container registry you can download a read-only config file at container registry home <em>Actions</em> button. The same file can be found in ~/.docker/config.json when you login in to docker registry in your local machine.</p><h4>Using config.json</h4><pre>kubectl create secret generic registry-credential \<br>    --from-file=.dockerconfigjson=&lt;path/to/.docker/config.json&gt; \<br>    --type=kubernetes.io/dockerconfigjson</pre><p>or</p><h4>Using docker credentials</h4><pre>kubectl create secret docker-registry registry-credential --docker-server=&lt;your-registry-server&gt; --docker-username=&lt;your-name&gt; --docker-password=&lt;your-password&gt; --docker-email=&lt;your-email&gt;</pre><p>Inspect created secret</p><pre>kubectl get secret registry-credential --output=yaml</pre><p>The output is similar to this:</p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  ...<br>  name: registry-credential<br>  ...<br>data:<br>  .dockerconfigjson: eyJodHRwczovL2luZGV4...<br>type: kubernetes.io/dockerconfigjson</pre><p>The value of the .dockerconfigjson field is a base64 representation of your Docker credentials. To convert the data into readable format use the following command.</p><pre>kubectl get secret registry-credential --output=&quot;jsonpath={.data.\.dockerconfigjson}&quot; | base64 --decode</pre><h3>Step 2</h3><h3>Editing the pod</h3><p>Once the secret is created we can update our pod config to use the created secret to pull images. Update the spec session of your pod as follows.</p><pre>spec:<br>  containers:<br>  - name: private-reg-container<br>    image: &lt;your-private-image&gt;<br>  imagePullSecrets:<br>  - name: registry-credential</pre><p>To pull the image from the private registry, Kubernetes needs credentials. The imagePullSecrets field in the configuration file specifies that Kubernetes should get the credentials from a Secret named registry-credential.<br>Create a Pod that uses your Secret, and verify that the Pod is running</p><pre>kubectl apply -f pod.yaml<br>kubectl get pod &lt;pod-name&gt;</pre><p>If you don’t want to add imagePullSecrets to your pod config or need to set different registries per namespace as default then go to <strong>step 3</strong>.</p><h3>Step 3</h3><h3>Adding image pull secretes to service account</h3><p>If you want to get a preview about service accounts checkout this <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/#use-the-default-service-account-to-access-the-api-server"><em>doc</em></a><br>To add our new secret to the namespace we have to modify the service account and push our new secret name to the <em>imagePullSecret</em> array inside the service account.<br>We can download the service account manifest by</p><pre>kubectl get serviceaccounts default -o yaml &gt; ./service-account.yaml</pre><p>then update it as follows:</p><pre>apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  creationTimestamp: 2015-08-07T22:02:39Z<br>  name: default<br>  namespace: default<br>  uid: 052fb0f4-3d50-11e5-b066-42010af0d7b6<br>secrets:<br>- name: default-token-uudge<br>imagePullSecrets:<br>- name: registry-credential</pre><p>Finally replace the service account with updated manifest file</p><pre>kubectl replace serviceaccount default -f ./service-account.yaml</pre><p>Now, you can remove imagePullsecrets part from the pod definition and when a new Pod is created in the current namespace and using the default ServiceAccount, the new Pod has its spec.imagePullSecrets field set automatically.</p><pre>kubectl get pod &lt;pod name&gt; -o=jsonpath=&#39;{.spec.imagePullSecrets[0].name}{&quot;\n&quot;}&#39;</pre><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>References:<br><a href="https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/"><em>Pull an Image from a Private Registry</em></a><br><a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/#add-image-pull-secret-to-service-account"><em>Add image pull secret to service account</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46a3cede7cb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple double stage Golang docker image]]></title>
            <link>https://sam-thomas.medium.com/simple-double-stage-golang-docker-image-4aa66f732d19?source=rss-f0d87e545507------2</link>
            <guid isPermaLink="false">https://medium.com/p/4aa66f732d19</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Sam Thomas]]></dc:creator>
            <pubDate>Sat, 15 May 2021 11:03:11 GMT</pubDate>
            <atom:updated>2021-05-15T11:03:11.868Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nD-_qWrxSDWKmDyw.png" /></figure><p>The efficient way to run <em>golang</em> app inside docker is to convert it to the binary and run. It is one of the advantage of compiled programming languages against interpreted programming languages. <br>Compared to all the files needed to run a nodejs application, Golang binaries are much more manageable.</p><h3>Docker</h3><p>It is important to make the docker image small as possible to save storage and make the process faster. The solution is <strong>Multi Stage Builds</strong>. Using multi stage building we can build the app to get the binary and in the second stage copy the binaries and any other dependency in to the base image. We are using the <a href="https://hub.docker.com/_/scratch/"><strong>scratch</strong></a> image from docker, Which used to create the base images.</p><p><strong>Scratch</strong> image does not contain any of the executables normally found inside a container. Remember to add the executables or files needed. As you can see I’ve added CA Certificates.It is also possible to avoid using the <strong>scratch</strong> image and run it in a base alpine image, And still able create comparatively small image</p><pre># First stage<br>FROM golang:1.14-alpine AS build<br>RUN apk --update add ca-certificates</pre><pre># Selecting work directory<br>WORKDIR /src/<br># Copy the project directory to the image<br>COPY . .<br># Actual build<br>RUN CGO_ENABLED=0 go build -o /bin/app ./path/to main</pre><pre># Second stage<br>FROM scratch<br># Copying build <br>COPY --from=build /bin/app /bin/app<br>COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt</pre><pre>ENTRYPOINT [&quot;/bin/app&quot;]<br>EXPOSE 8080</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4aa66f732d19" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>