<?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 Ossama Shokry on Medium]]></title>
        <description><![CDATA[Stories by Ossama Shokry on Medium]]></description>
        <link>https://medium.com/@oshokry1?source=rss-e061736faabe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rAi4Jp0PyNats_UOvn-B6Q.jpeg</url>
            <title>Stories by Ossama Shokry on Medium</title>
            <link>https://medium.com/@oshokry1?source=rss-e061736faabe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:26:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oshokry1/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[Build A Two-Tier Kubernetes Application with a PHP Front End and a Flask REST API Backend]]></title>
            <link>https://medium.com/@oshokry1/build-a-two-tier-kubernetes-application-with-a-php-front-end-and-a-flask-rest-api-backend-b7effaeb7e22?source=rss-e061736faabe------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7effaeb7e22</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Ossama Shokry]]></dc:creator>
            <pubDate>Sat, 18 Feb 2023 03:17:25 GMT</pubDate>
            <atom:updated>2024-04-05T19:26:08.452Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@oshokry1/manage-configuration-changes-to-your-kubernetes-application-using-configmap-and-portainer-c0f5387e9276">Part 9</a> of this series, you learned how to manage configuration data of your application using the Kubernetes ConfigMap. You also installed Portainer and used its easy-to-use Web UI to manage your Kubernetes cluster.</p><p>In this part, you will complete the end-to-end Fibonacci Application. You will create the PHP Frontend Deployment and connect it to the Backend REST API Server. You will also use Portainer to manage Kubernetes Secrets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*fCo_IbmXR07elMA_kLChTQ.png" /><figcaption>A Kubernetes Application with a PHP Frontend and a REST API Backend</figcaption></figure><blockquote>Want to learn Docker and Kubernetes in 3 hours? Sign up to my course on Udemy now. Click this link → <a href="https://www.udemy.com/course/build-scalable-applications-using-docker-and-kubernetes/?referralCode=9650B00C60B732B30533"><strong>Build Scalable Applications using Docker and Kubernetes</strong></a></blockquote><h3>CD to the front-end application</h3><p>If you did not pull the <a href="https://github.com/oshokry/FibonacciSample">FibonacciSample</a> application Git repository locally in a previous part of this series, do so by running the following command:</p><pre>$git clone https://github.com/oshokry/FibonacciSample.git</pre><p>Change directory to the front-end application at <em>FibonacciSample/Fibonacci-frontend</em>. There is a directory named <em>php</em> which includes the front-end application code written in PHP. The code is simple, browse through it to take an idea. For now, I will point out two aspects that we need to be aware of when constructing the end-to-end application.</p><h4>The login PHP script</h4><p>The <a href="https://github.com/oshokry/FibonacciSample/blob/master/fibonacci-frontend/php/login.php">login.php</a> script authenticates the user that attempts to login to the application. It does so by comparing the passphrase that the user typed to the value stored in the <em>PASS_PHRASE</em> environment variable. Check <a href="https://github.com/oshokry/FibonacciSample/blob/master/fibonacci-frontend/php/login.php#L5-L12">lines 5–12</a>:</p><pre>5  $passphrase_from_user = $_POST[&#39;passphrase&#39;];<br>6  $password_from_secret = getenv(&#39;PASS_PHRASE&#39;);<br>7  if ($passphrase_from_user == $password_from_secret) {<br>8    $_SESSION[&#39;loggedin&#39;] = 1;<br>9  }<br>10 else {<br>11   $_SESSION[&#39;loginFailed&#39;] = 1;<br>12 }</pre><p>The value of the environment variable <em>PASS_PHRASE </em>will come from a Kubernetes Secret that we will create in a later section below.</p><h4>The invoke PHP script</h4><p>The <a href="https://github.com/oshokry/FibonacciSample/blob/master/fibonacci-frontend/php/invoke.php">invoke.php</a> script invokes the back-end Fibonacci REST API. Please pay attention to <a href="https://github.com/oshokry/FibonacciSample/blob/aa78df3377a4a3e8dca7efa351b2a14be7ffb8ca/fibonacci-frontend/php/invoke.php#L5">line 5</a>, where it expects the back-end’s end point at <a href="http://fibonacci-backend-cs:5000/">http://fibonacci-backend-cs:5000:</a></p><pre>5 $url = “http://fibonacci-backend-cs:5000/fibonacci?n=&quot;;</pre><p>We have exposed the back-end Fibonacci REST API at the above end point using a <a href="https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types"><em>ClusterIP</em></a> Kubernetes Service named <em>fibonacci-backend-cs</em>. We created this Service in <a href="https://medium.com/@oshokry1/use-a-kubernetes-service-to-expose-a-highly-available-rest-api-server-bbc1bcfdd4a3">Part 5</a> of this series.</p><h3>Define the front-end Passphrase using a Kubernetes Secret</h3><p>A Kubernetes <a href="https://kubernetes.io/docs/concepts/configuration/secret/"><em>Secret</em></a> is an object that contains a small amount of sensitive data such as a password, a token, or a key. Using a Secret allows you to avoid including confidential data in your application code. Secrets are similar to ConfigMaps but are specifically intended to hold confidential data.</p><p>A Secret can be used to <a href="https://kubernetes.io/docs/concepts/configuration/secret/#use-case-as-container-environment-variables">set an environment variable for a Container</a> which is exactly what we need to do here to set the value for environment variable <em>PASS_PHRASE</em>.</p><h4>Inspect the Passphrase Secret YAML file</h4><p>Check the contents of <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/passphrase-secret.yaml">FibonacciSample/K8/passphrase-secret.yaml</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b82ff3b4c18fda21c6fe15b4f384a241/href">https://medium.com/media/b82ff3b4c18fda21c6fe15b4f384a241/href</a></iframe><p>The file is simple. It defines a Kubernetes Secret that has one field named <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/passphrase-secret.yaml#L6"><em>passphrase</em></a>, with its value initialized to a placeholder <strong>x0x0x0x0</strong>. We will use Portainer to fill in an actual value for the passphrase.</p><h4>Create the Passphrase Secret</h4><p>Change directory to the K8 resources at the path <em>FibonacciSample/K8/</em>. Run the following command to create the Secret:</p><pre>$ kubectl create -f passphrase-secret.yaml<br>secret/passphrase-secret created</pre><p>let’s use <em>kubectl describe</em> to see what Kubernetes can print on the Terminal for a Secret:</p><pre>$ kubectl describe secret passphrase-secret<br>Name:         passphrase-secret<br>Namespace:    default<br>Labels:       &lt;none&gt;<br>Annotations:  &lt;none&gt;<br><br>Type:  Opaque<br><br>Data<br>====<br>passphrase:  8 bytes</pre><p>Please note that the value of the <em>passphrase</em> field is not shown in the output.</p><h4>Change the Passphrase in Portainer</h4><p>You installed Portainer in <a href="https://medium.com/@oshokry1/manage-configuration-changes-to-your-kubernetes-application-using-configmap-and-portainer-c0f5387e9276">Part 9</a>. Let’s launch it again using this link:</p><p><a href="http://localhost:30777/">http://localhost:30777</a></p><p>Login to Portainer and click on the K8 Environment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*dUE1UfwYLaiptnZ8v4VqDg.png" /><figcaption>Portainer shows the K8 Environment</figcaption></figure><p>Click on <strong>ConfigMaps &amp; Secrets</strong> from the left pane. Our Secret <em>passphrase-secret</em> appears on a table to the right, click on it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*W1BNRwEjxKyHSahoJkoqIw.png" /><figcaption>Click on the Kubernetes Secret</figcaption></figure><p>You can edit the value for the <em>passphrase</em> right in the browser. You will initially see placeholder text <strong>x0x0x0x0</strong>. Replace it with a value of your choice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*VNDDsyF4ulXuWePDBcd1yA.png" /><figcaption>Update the Kubernetes Secret to fill in the value of the Passphrase</figcaption></figure><p>Click <strong>Update Secret</strong> button at the end of the page to save the changes.</p><h3>Deploy the Fibonacci PHP front-end</h3><p>Inspect the contents of the front-end YAML file <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/frontend-resources.yaml">FibonacciSample/K8/frontend-resources.yaml</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3db24d29236ec6eaceee9b4863d06b15/href">https://medium.com/media/3db24d29236ec6eaceee9b4863d06b15/href</a></iframe><p>The file includes a Deployment with 1 replica for the PHP Frontend and a <a href="https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport">NodePort</a> Service. Let’s take a closer look at each of them.</p><h4>The front-end Deployment</h4><p>The YAML file includes Deployment <em>fibonacci-frontend-deployment</em> in <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/frontend-resources.yaml#L1-L30">lines 1–30</a>. note the following properties of the Deployment:</p><ul><li>We have <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/frontend-resources.yaml#L11">one replica</a> of the Pod. The Pod has the <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/frontend-resources.yaml#L18-L20">labels</a> <em>app= fibonacci, tier= frontend</em>.</li><li>The <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/frontend-resources.yaml#L23-L30">Container in the Pod</a> is based on image <em>oshokry/fibonacci-frontend</em> which containerizes the PHP front-end for the Fibonacci Application. If you want to learn how the container image was created, refer to my article <a href="https://medium.com/@oshokry1/containerize-the-front-end-d323264aa5db">Use Docker to containerize a PHP Application</a>.</li><li>The Container defines <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/frontend-resources.yaml#L25-L30">environment variable PASS_PHRASE</a> which gets its value from secret <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/passphrase-secret.yaml">passphrase-secret</a>.</li></ul><h4>The front-end Service</h4><p>The YAML file includes Kubernetes Service <em>fibonacci-frontend-nps</em> in <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/frontend-resources.yaml#L32-L44">lines 32–44</a>. Refer to <a href="https://medium.com/@oshokry1/use-a-kubernetes-service-to-expose-a-highly-available-rest-api-server-bbc1bcfdd4a3">Part 5</a> of this series for more information about K8 Services.</p><p>Note the following properties of the Service:</p><ul><li>Service type is <a href="https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport"><em>NodePort</em></a>. This type exposes the Pods on a port on the host machine of the Kubernetes Node. It allows us to access the front end from a browser on the host machine.</li><li>The <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/frontend-resources.yaml#L41">nodePort is 30099</a>, so this is the port we can use in the browser on the host machine.</li><li>The <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/frontend-resources.yaml#L42-L44">selector</a> of the Service matches the <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/frontend-resources.yaml#L18-L20">labels</a> in the Pod template of Deployment <em>app= fibonacci, tier= frontend</em>. This way, the Service knows the front-end Pod(s) it needs to expose.</li></ul><h4>Matching labels and selectors</h4><p>It is worth re-iterating the concept of labels and selectors in Kubernetes here. The front-end Deployment identifies its Pods with labels, and the front-end Service has its selector match those labels:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*rQs_1ypHVSB-M741zG8cHg.png" /><figcaption>The Service Definition on the left has Selectors that match the Labels of the Pod template in the Deployment Definition on the right</figcaption></figure><p>This is how the front-end Service identifies the front-end Pod(s) that it needs to expose. This is a general pattern in Kubernetes. An object in Kubernetes is identified by labels, and other objects can refer to it by selectors that match those labels.</p><h4>Create the front-end Deployment and Service</h4><p>Run the following command to create the front-end Deployment and Service:</p><pre>$ kubectl create -f frontend-resources.yaml<br>deployment.apps/fibonacci-frontend-deployment created<br>service/fibonacci-frontend-nps created</pre><p>Wait a minute then list the Pods In the cluster. There are 5 back-end Pods for the REST API and 1 front-end Pod for the PHP web site. On my machine, the front-end Pod got the name <em>fibonacci-frontend-deployment-85989cfffd-nkh77</em>:</p><pre>$ kubectl get pod<br>NAME                                             READY   STATUS    RESTARTS   AGE<br>fibonacci-backend-deployment-6c49d6c54c-kll7r    1/1     Running   0          24h<br>fibonacci-backend-deployment-6c49d6c54c-pcj5c    1/1     Running   0          24h<br>fibonacci-backend-deployment-6c49d6c54c-qdmbh    1/1     Running   0          24h<br>fibonacci-backend-deployment-6c49d6c54c-vswq4    1/1     Running   0          24h<br>fibonacci-backend-deployment-6c49d6c54c-zs58v    1/1     Running   0          24h<br>fibonacci-frontend-deployment-85989cfffd-nkh77   1/1     Running   0          23s</pre><h3>Test the Fibonacci End-to-End Application</h3><p>If you have reached this far in the series, congratulations! You have a fully working Kubernetes Application with a front-end PHP web site and a back-end REST API Server. Let’s test the application.</p><p>Launch the application at this link in a browser on the host machine:</p><p><a href="http://localhost:30099/">http://localhost:30099/</a></p><p>Login to the Fibonacci Application with the Passphrase that you filled in in Portainer earlier in this lab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*0j1D14Bfal9J771TgrwBog.png" /><figcaption>Type the Passphrase and click <strong>Login</strong></figcaption></figure><p>Let’s figure the Fibonacci of 44. Enter 44 and press <strong>Go</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*n533YfzaYfgi_h9zWk32qw.png" /><figcaption>Type 44 and press <strong>Go</strong></figcaption></figure><p>The result comes as 701408733. The request was served by v4.0 of the REST API Server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*slT1eeUrp8-KxEgS8IWBcg.png" /><figcaption>The PHP Frontend shows Fibonacci of 44 that was computed in v4.0 of the REST API Backend</figcaption></figure><p>Check if the PersistentVolume in the back-end is still working. Open the log file on the host machine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*S070s1--7r8CqaXtKzcDmw.png" /><figcaption>The log file is persisted on the host machine</figcaption></figure><p>The log entry for the Fibonacci of 44 is there:</p><pre>2023-02-17 18:13:09.904693<br>Fibonacci v4.0&lt;br&gt;Hello from &lt;b&gt;fibonacci-backend-deployment-6c49d6c54c-zs58v&lt;/b&gt;&lt;br&gt;Fibonnacci of 44 is &lt;b&gt;701408733&lt;/b&gt;<br>-----------------------------</pre><p>Feel free to play around with the application. Here are some ideas:</p><ol><li>Change the file name and file path in the ConfigMap in Portainer and see if the logs make it to the new file.</li><li>Change the Passphrase in Portainer, log off then login again and see if the new Passphrase works.</li><li>Browse through the Web UI of Portainer and check the K8 resources that we created for the Fibonacci Application. We have a lot of stuff there that together makes up the full Application:</li></ol><ul><li>A Deployment for the REST API Server</li><li>A NodePort Service for the REST API Server</li><li>A ClusterIP Service for the REST API Server</li><li>A PersistentVolume and PersistentVolumeClaim for the REST API Server</li><li>A ConfigMap for the log file of the REST API Server</li><li>A Deployment for the front-end PHP Web Site</li><li>A Secret for the front-end PHP Web Site</li><li>A NodePort Service for the PHP WebSite</li></ul><p>And we have Portainer to manage it all, right in our Web browser!</p><h3>Summary</h3><p>Thanks for reaching the end of this series! In this multi-part Kubernetes education path, you started by learning basic concepts about Containers, Docker, and Kubernetes. You then started to apply your knowledge bit by bit, starting with a <em>Hello, World!</em> Kubernetes Pod.</p><p>You created a single Kubernetes Pod that implements a REST API Server. Then you made the REST API Server highly available using Kubernetes ReplicaSet. You learned how to use Kubernetes Service to expose your Pods. You managed different revisions of your workloads using Kubernetes Deployment. You persisted the state of your application using Persistent Volumes and stored sensitive information securely in Secrets.</p><p>You then put it all together to have a fully working Kubernetes Application with a front-end PHP web site and a back-end REST API Server. Along the way you installed and used Portainer to manage your K8 resources and infrastructure.</p><p>I hope you have enjoyed this series and found it useful. Thanks again and congratulations for finishing this K8 practical education.</p><blockquote>Want to learn Docker and Kubernetes in 3 hours? Sign up to my course on Udemy now. Click this link → <a href="https://www.udemy.com/course/build-scalable-applications-using-docker-and-kubernetes/?referralCode=9650B00C60B732B30533"><strong>Build Scalable Applications using Docker and Kubernetes</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7effaeb7e22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manage Configuration Changes to your Kubernetes Application using ConfigMap and Portainer]]></title>
            <link>https://medium.com/@oshokry1/manage-configuration-changes-to-your-kubernetes-application-using-configmap-and-portainer-c0f5387e9276?source=rss-e061736faabe------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0f5387e9276</guid>
            <category><![CDATA[configmap]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[portainer]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Ossama Shokry]]></dc:creator>
            <pubDate>Fri, 17 Feb 2023 01:36:13 GMT</pubDate>
            <atom:updated>2024-04-05T19:25:42.694Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@oshokry1/persist-the-state-of-your-application-using-kubernetes-persistent-volume-41b9f58ac3c5">Part 8</a> of this series, you learned how to preserve the state of your application on the host machine with the help of Kubernetes PersistentVolume and PersistentVolumeClaim.</p><p>In this part, you will learn how to manage configuration data of your application using the Kubernetes ConfigMap. You will also install and use Portainer, a great Container Management tool with an easy-to-use Web UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*5gh3KiISMwvHTG2XprJS6A.png" /><figcaption>Use Portainer to edit a Kubernetes ConfigMap</figcaption></figure><blockquote>Want to learn Docker and Kubernetes in 3 hours? Sign up to my course on Udemy now. Click this link → <a href="https://www.udemy.com/course/build-scalable-applications-using-docker-and-kubernetes/?referralCode=9650B00C60B732B30533"><strong>Build Scalable Applications using Docker and Kubernetes</strong></a></blockquote><h3>CD to the K8 directory</h3><p>If you did not pull the <a href="https://github.com/oshokry/FibonacciSample">FibonacciSample</a> application Git repository locally in a previous part of this series, do so by running the following command:</p><pre>$git clone https://github.com/oshokry/FibonacciSample.git</pre><p>Change directory to this path where you can find Kubernetes objects defined in YAML file format:</p><pre>$ cd FibonacciSample/K8/</pre><h3>A Word about the log file</h3><p>You created v3 of the REST API Server Deployment in <a href="https://medium.com/@oshokry1/persist-the-state-of-your-application-using-kubernetes-persistent-volume-41b9f58ac3c5">Part 8</a>. The calls to the Fibonacci REST API are logged in the log file, but the file path is hard coded. Its value <em>“/logs/system.log”</em> comes from <a href="https://github.com/oshokry/FibonacciSample/blob/master/fibonacci-backend/api.py#L63">line 63 in api.py</a>. We can do better than that.</p><p>Check function <a href="https://github.com/oshokry/FibonacciSample/blob/master/fibonacci-backend/api.py#L53-L63"><em>getlogFile()</em></a> in the REST API implementation. It attempts to read the <em>logFilePath</em> and <em>logFileName</em> from a configuration file. The path to the configuration file is stored in an environment variable named <em>CONFIG_FILE</em>. We will use Kubernetes features to create this configuration file and fill in this environment variable.</p><h3>Install Portainer</h3><p><a href="https://www.portainer.io/">Portainer</a> is a Container Management Platform that provides an easy to use Web UI to manage your Container workloads. Portainer can be used to manage a variety of Container infrastructures. In this series we will use Portainer’s Web UI to easily edit the configuration changes of our Application and manage the Kubernetes cluster in general.</p><p>Run the following command to install Portainer on your Kubernetes cluster:</p><pre>$ kubectl apply -f https://raw.githubusercontent.com/portainer/k8s/master/deploy/manifests/portainer/portainer.yaml<br>namespace/portainer created<br>serviceaccount/portainer-sa-clusteradmin created<br>persistentvolumeclaim/portainer created<br>clusterrolebinding.rbac.authorization.k8s.io/portainer created<br>service/portainer created<br>deployment.apps/portainer created</pre><p>Wait for 1–2 minutes for the installation to complete, then launch Portainer in your browser using this link:</p><p><a href="http://localhost:30777/">http://localhost:30777</a></p><p>You will need to setup a Username and a password for the first time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*ob0f8xPSyIaL2WA7Z3xVeQ.png" /><figcaption>Enter a Username and password for Portainer</figcaption></figure><h3>Browse through the Portainer Web UI</h3><p>Login to Portainer with the Username/Password you just created and go to the Home screen. You will see your Kubernetes cluster environment under the <strong>Environments </strong>list. It lists properties of the K8 cluster such as the number of CPUs and the allocated RAM to the cluster. Click on the K8 Environment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kaMLaR0fuNTt1TykS-cl4Q.png" /><figcaption>Portainer shows the properties of the K8 environment</figcaption></figure><p>You are taken to the <strong>Dashboard </strong>view where you have a list of K8 resources that are present on the K8 environment. Click on <strong>Applications</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*F7-6mK_jScAENx15Qku9bA.png" /><figcaption>Portainer shows a list of K8 resources</figcaption></figure><p>You are greeted with the Fibonacci Backend Application. Click on it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*C-hOqBQ4d8aVaPyp0YHqzA.png" /><figcaption>The Fibonacci Backend Deployment appears under Applications</figcaption></figure><p>A page comes with all the information you need to know about the Application. Read through it to familiarize yourself with the contents. Scroll to the end where you see a list of the Pods under the Deployment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*-V2HEC9btqtz0Z3q_pCRdw.png" /><figcaption>A list of Pods in the Fibonacci Backend Deployment is shown</figcaption></figure><p>Notice the Actions column at the far right of the table. For each Pod, you can click <strong>Logs</strong> to see the Pod logs. You can also click <strong>Console</strong> to launch a terminal into the Pod’s container right inside the browser. Isn’t this cool!</p><p>Finally, from the left navigation pane, click on the <strong>kubectl shell</strong>. You will have access to a terminal inside the browser where you can issue commands against your K8 cluster. Type <em>kubectl get all</em> as a test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*JlyGyEq1MCw0Z3KngJUWNA.png" /><figcaption>Use the built in <strong>kubectl shell</strong> to issue commands against the K8 cluster right from the browser</figcaption></figure><p>Feel free to browse through Portainer further to get familiar with its features. We will use it later in this lab to create a few configurations to our application.</p><h3>Inspect the Log ConfigMap file</h3><p>Check contents of the file <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/log-config-map.yaml">FibonacciSample/K8/log-config-map.yaml</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7f8535d39e4dfeea07fe05fcc6bc022/href">https://medium.com/media/c7f8535d39e4dfeea07fe05fcc6bc022/href</a></iframe><p>A Kubernetes <a href="https://kubernetes.io/docs/concepts/configuration/configmap/"><em>ConfigMap</em></a> is an API object used to store non-confidential data in key-value pairs. Pods can consume ConfigMaps as environment variables, command-line arguments, or as configuration files in a volume. <strong>We will consume the ConfigMap <em>log-config-map</em> as a configuration file in a volume.</strong></p><p>The ConfigMap defines config parameters <em>path </em>and <em>filename </em>for the log file and fills them with placeholder values in <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/log-config-map.yaml#L10-L11">lines 10–11</a>. We will use Portainer in the next section to fill in proper config values.</p><h3>Create the ConfigMap and fill in config values</h3><p>Run the following command to create the ConfigMap:</p><pre>$ kubectl create -f log-config-map.yaml<br>configmap/log-config-map created</pre><p>The ConfigMap(CM) is created. Feel free to list existing CMs using the command <em>kubectl get configmap</em>. Also issue command <em>kubectl describe configmap log-config-map</em> to list the properties of the CM that we just created.</p><h4>Fill in config values in Portainer</h4><p>Go back to the Portainer Web UI in your browser and click on <strong>ConfigMaps &amp; Secrets</strong> from the left pane. Our CM <em>log-config-map</em> appears on a table to the right, click on it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P3VUS-3uw8Epl30uW7tuhw.png" /><figcaption>Access the list of ConfigMaps and Secrets in Portainer</figcaption></figure><p>You can edit the config data of your application right in the browser. You will initially see placeholder text<strong> x0x0x0x0</strong>. Replace it with proper values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*wz0mhCjgX3AWJyN08me9Fw.png" /><figcaption>Edit the contents of a ConfigMap in Portainer</figcaption></figure><ul><li>Enter “<em>/logs/”</em> for the <strong>path</strong> field since this is the path defined in the <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v4.yaml#L31-L32">Volume Mount</a>. Do not forget the forward slash / at the end. This is because the REST API implementation concatenates the <em>logFilePath</em> and <em>logFileName</em> at <a href="https://github.com/oshokry/FibonacciSample/blob/master/fibonacci-backend/api.py#L60">line 60</a>.</li><li>Fill in a value of your choice for the <strong>filename</strong> field(I put <em>“FibonacciRuns.txt”</em>).</li></ul><p>Click Update ConfigMap button at the end of the page to save the changes.</p><p>Let’s make use of these configurations in the Fibonacci REST API Deployment.</p><h3>Inspect the Fibonacci Deployment V4</h3><p>Check the file <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v4.yaml">FibonacciSample/K8/backend-deployment-v4.yaml</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/349da6168e139e8abe63c98092702ce5/href">https://medium.com/media/349da6168e139e8abe63c98092702ce5/href</a></iframe><p>It is similar to the v3 Deployment in <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v3.yaml">FibonacciSample/K8/backend-deployment-v3.yaml</a>, which we deployed in <a href="https://medium.com/@oshokry1/persist-the-state-of-your-application-using-kubernetes-persistent-volume-41b9f58ac3c5">Part 8</a>. It adds the following features related to Configuration:</p><ul><li>In <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v4.yaml#L39-L44">lines 39–44</a>, a Kubernetes Volume with the name <em>config</em> is created based on the CM <em>log-config-map</em>. The Volume will surface the contents of the CM as a file named <em>config.ini</em>.</li><li>In <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v4.yaml#L33-L34">lines 33–34</a>, the Container in the Pod mounts the said Volume to the path “<em>/var/private”</em>. This makes the contents of the CM accessible to the Container as file “<em>/var/private/config.ini</em>”.</li><li>In <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v4.yaml#L27-L29">lines 27–29</a>, an Environment Variable <em>CONFIG_FILE</em> is set to the value “<em>/var/private/config.ini</em>”.</li></ul><p>The above features in the v4 Deployment makes a configuration file accessible to the Container via the Environment Variable <em>CONFIG_FILE</em>. The function <a href="https://github.com/oshokry/FibonacciSample/blob/master/fibonacci-backend/api.py#L53-L63"><em>getlogFile()</em></a> in the REST API implementation can read the values for <em>logFilePath</em> and <em>logFileName</em> from the configuration file. Therefore, a custom name and path for the log file is made possible.</p><h3>Rollout V4 of the Fibonacci Backend</h3><p>Deploy v4 of the Fibonacci backend using the following command:</p><pre>$ kubectl apply -f backend-deployment-v4.yaml<br>deployment.apps/fibonacci-backend-deployment configured</pre><p>Wait for a minute for the v3 Pods to be deployed and the older Pods to be terminated. The Deployment will take care of this for you. Now check the deployment history:</p><pre>$ kubectl rollout history deployment fibonacci-backend-deployment<br>deployment.apps/fibonacci-backend-deployment<br>REVISION  CHANGE-CAUSE<br>2         Fibonacci-backend-v2<br>3         Fibonacci-backend-v1<br>4         Fibonacci-backend-v3<br>5         Fibonacci-backend-v4</pre><p>You get a list of revisions deployed so far. This time we deployed revision v4. The <em>CHANGE-CAUSE</em> that appears in the revision history comes from the Deployment <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v4.yaml#L8-L9">annotation</a>.</p><h3>Check the Configuration File inside the Pod</h3><p>Let’s put Portainer to good use again. Navigate to <strong>Applications</strong> from the Left Pane, then click on the Deployment <em>fibonacci-backend-deployment</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*mxd_4BzvlTRK-L3Go4UZcA.png" /><figcaption>Click on the Deployment <strong><em>fibonacci-backend-deployment</em></strong></figcaption></figure><p>Scroll down to see the list of the Pods. Remember, they are all replicas of the same Pod <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v4.yaml#L16-L44">template</a> from the Deployment. Pick a Pod of your choice and launch a Bash terminal to the Container in the Pod by clicking on the link <strong>Console</strong> at the far right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*3QWSuIgGsd1qyb8kJ9njsw.png" /><figcaption>Click on the <strong>Console </strong>for one of the Pods</figcaption></figure><p>A page appears for the <strong>Application console</strong>. Click on the <strong>Connect</strong> button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*kbTQWp1RJ4Vxgjq1oXakAQ.png" /><figcaption>Connect to the Console</figcaption></figure><p>A shell terminal is launched in the browser for the Container inside the Pod. Let’s confirm that the Container has access to the configuration data that it needs:</p><ul><li>Issue the command <em>cat /var/private/config.ini</em> to print the contents of the configuration file.</li><li>Issue the command <em>echo “$CONFIG_FILE”</em> to print the value of the environment variable.</li></ul><p>The Container in the Pod has access to the configuration data indeed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*N9WQkNYAvIEP3hcxn90mng.png" /><figcaption>A Shell Console to the Container is working right in the browser</figcaption></figure><h3>Test V4 of the Fibonacci Backend</h3><p>Let’s figure the Fibonacci of 100. Launch this URL in the browser:</p><p><a href="http://localhost:30070/fibonacci?n=100">http://localhost:30070/fibonacci?n=100</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*ncD2Kjm4coxG522Oa-xnSw.png" /><figcaption>Fibonacci of 100 coming from the REST API v4.0</figcaption></figure><p>Note that the version is coming as v4.0 as we configured it.</p><p>Now check if the logs made it to the custom log file on the host machine. On my machine I configured the path of the PersistentVolume to become <em>C:\Fibonacci\logs</em>. A new file <em>“FibonacciRuns.txt”</em> is created as per the config data we filled in earlier in Portainer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*4xXg7v6GWMYihvVTrEv1EA.png" /><figcaption>A log file with a new name is creted based on the configurations we filled in Portainer</figcaption></figure><p>Check the contents of the file, it has the result of the Fibonacci of 100 that we just ran:</p><pre>2023-02-16 18:24:22.173069<br>Fibonacci v4.0&lt;br&gt;Hello from &lt;b&gt;fibonacci-backend-deployment-6c49d6c54c-pcj5c&lt;/b&gt;&lt;br&gt;Fibonnacci of 100 is &lt;b&gt;354224848179261915075&lt;/b&gt;<br>-----------------------------</pre><p>Feel free to change the file name in Portainer and see how a new file is created for the logs. This demonstrates how we can use the Kubernetes ConfigMap to externalize configuration data from our Application. With the help of Portainer, an admin can easily change the configuration data of the application.</p><h3>What’s Next?</h3><p>In this part, you learned how to manage configuration data of your application using the Kubernetes ConfigMap. You also installed Portainer and used its easy-to-use Web UI to manage your Kubernetes cluster.</p><p>Head over to <a href="https://medium.com/@oshokry1/build-a-two-tier-kubernetes-application-with-a-php-front-end-and-a-flask-rest-api-backend-b7effaeb7e22">Part 10</a>, where you will complete the end-to-end Fibonacci Application. You will create the PHP Frontend Deployment and connect it to the Backend REST API Server. You will also use Portainer to manage Kubernetes Secrets.</p><blockquote>Want to learn Docker and Kubernetes in 3 hours? Sign up to my course on Udemy now. Click this link → <a href="https://www.udemy.com/course/build-scalable-applications-using-docker-and-kubernetes/?referralCode=9650B00C60B732B30533"><strong>Build Scalable Applications using Docker and Kubernetes</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0f5387e9276" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Persist the state of your Application using Kubernetes Persistent Volume]]></title>
            <link>https://medium.com/@oshokry1/persist-the-state-of-your-application-using-kubernetes-persistent-volume-41b9f58ac3c5?source=rss-e061736faabe------2</link>
            <guid isPermaLink="false">https://medium.com/p/41b9f58ac3c5</guid>
            <category><![CDATA[persistent-volume-claim]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[persistent-volume]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Ossama Shokry]]></dc:creator>
            <pubDate>Wed, 15 Feb 2023 04:01:44 GMT</pubDate>
            <atom:updated>2024-04-05T19:25:15.361Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@oshokry1/manage-revisions-of-a-rest-api-server-using-kubernetes-deployment-9c987306697">Part 7</a> of this series, you used the Kubernetes Deployment to manage revisions of your REST API Server.</p><p>In this part, you will preserve the state of your application on the host machine with the help of Kubernetes Persistent Volume.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sox_p19gAprmHx3MHF1BPw.png" /><figcaption>Pods in a Kubernetes Deployment can preserve state on a <strong><em>PersistentVolume</em></strong>, which can be mounted to a directory on the host machine of the Kubernetes Node</figcaption></figure><blockquote>Want to learn Docker and Kubernetes in 3 hours? Sign up to my course on Udemy now. Click this link → <a href="https://www.udemy.com/course/build-scalable-applications-using-docker-and-kubernetes/?referralCode=9650B00C60B732B30533"><strong>Build Scalable Applications using Docker and Kubernetes</strong></a></blockquote><h3>CD to the K8 directory</h3><p>If you did not pull the <a href="https://github.com/oshokry/FibonacciSample">FibonacciSample</a> application Git repository locally in a previous part of this series, do so by running the following command:</p><pre>$git clone https://github.com/oshokry/FibonacciSample.git</pre><p>Change directory to this path where you can find Kubernetes objects defined in YAML file format:</p><pre>$ cd FibonacciSample/K8/</pre><h3>How to persist state on the host machine</h3><p>A Kubernetes Pod runs one or more Containers. If you do not specify a volume for your Pod, then a Container in the Pod become stateless. This means that any changes to the Container’s file system are lost if the Container is destroyed.</p><p>If you want more consistent storage that is independent of the Container, you can assign a <a href="https://kubernetes.io/docs/concepts/storage/volumes/">Volume</a> to your Pods. If you want to persist the state of your application beyond the lifetime of a Pod, you can use a Persistent Volume(PV) and allocate this PV to your Pod via a Persistent Volume Claim(PVC).</p><h4>PersistentVolume(PV)</h4><p>A <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/"><em>PersistentVolume</em></a>(PV) is a piece of storage in the cluster that has a lifecycle independent of any individual Pod that uses the PV. There are several <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/#types-of-persistent-volumes">types</a> of Persistent Volumes and each type has a different way of mounting the volume. In this lab we will use a PersistentVolume of the type <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/#persistentvolumes-typed-hostpath">hostPath</a>, where the volume is mounted to a path on the Kubernetes node host machine. Please note that this PV type should not be used on a Production Environment.</p><h4>PersistentVolumeClaim(PVC)</h4><p>A <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/#persistentvolumeclaims">PersistentVolumeClaim</a>(PVC) is an object that declares a specific storage need which can be satisfied by a matching PV. If a Pod needs Persistent Storage, it defines a volume that refers to a PVC that defines the specs of the needed storage.</p><h4>Managing PVs and PVCs in a Kubernetes Cluster</h4><p>An Administrator of a Kubernetes cluster can create a pool of PVs to be made available for requestors that need storage. Each storage requestor can create a PVC to specify the specs of the storage it needs. Kubernetes will then bind PVCs to PVs that match their specs(e.g., storage size). We will see how PV, PVC, and Pod work together later in this lab.</p><h3>Inspect the Backend Storage YAML file</h3><p>Check the definition of the PV and the PVC that we will use in the Fibonacci backend in the file <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-storage.yaml">FibonacciSample/K8/backend-storage.yaml</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38f82475773c4b5e47d90d818b849eba/href">https://medium.com/media/38f82475773c4b5e47d90d818b849eba/href</a></iframe><p>The PV is defined in <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-storage.yaml#L1-L14">lines 1–14</a>. Note the following properties in the definition:</p><ul><li>The storage cpacity is specified as 1 Gigabytes(<em>storage: 1Gi</em>).</li><li>The <a href="https://kubernetes.io/docs/concepts/storage/persistent-volumes/#access-modes">Access Mode</a> is specified as <em>ReadWriteOnce</em>. This means that the volume can be mounted as read-write by a single node. It also allows multiple pods to access the volume when the pods are running on the same node.</li><li>Host Path is “<em>/run/desktop/mnt/host/c/Fibonacci/logs</em>”. On a Windows machine running Docker Desktop, this translates to a local path of “<em>C:\Fibonacci\logs</em>”. <strong>Change this path to the one you prefer to use on your host machine</strong>.</li></ul><p>The PVC is defined in lines <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-storage.yaml#L16-L26">16–26</a>. Note the following properties in the definition:</p><ul><li>The Access Mode is specified as <em>ReadWriteOnce</em>. This makes it match the Access Mode on the PV we defined above.</li><li>The Storage Request is 1 Gigabyte which also matches the capacity of the PV.</li></ul><h3>Create the PV and the PVC</h3><p>Run the following command to create the PV and the PVC:</p><pre>$ kubectl apply -f backend-storage.yaml<br>persistentvolume/fibonacci-backend-pv created<br>persistentvolumeclaim/fibonacci-backend-pvc created</pre><p>The PV and the PVC are created. let’s list the available PVs and PVCs:</p><pre>$ kubectl get pv<br>NAME                                       CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM                           STORAGECLASS   REASON   AGE<br>fibonacci-backend-pv                       1Gi        RWO            Retain           Bound    default/fibonacci-backend-pvc   manual                  27h<br>pvc-bcfc13bf-7fce-4f2b-99e5-833056142b6e   10Gi       RWO            Delete           Bound    portainer/portainer             hostpath                16d</pre><pre>$ kubectl get pvc<br>NAME                    STATUS   VOLUME                 CAPACITY   ACCESS MODES   STORAGECLASS   AGE<br>fibonacci-backend-pvc   Bound    fibonacci-backend-pv   1Gi        RWO            manual         27h</pre><p>The listing shows us that there is a PV with the name <em>fibonacci-backend-pv</em> and it is Bound to a PVC with the name <em>fibonacci-backend-pvc</em>. Note that the status of the PVC is <em>Bound </em>and under its VOLUME you can find the name of the PV it is bound to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*UTOBPEQWb4qDHG5zmRYmaA.png" /><figcaption>Kubernetes binds a PVC to a PV if one is available and satisfies the request in the PVC</figcaption></figure><h3>Inspect the Fibonacci Deployment V3</h3><p>Check the file <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v3.yaml">FibonacciSample/K8/backend-deployment-v3.yaml</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1321dec9b8ee66f932b993bccad6fbbd/href">https://medium.com/media/1321dec9b8ee66f932b993bccad6fbbd/href</a></iframe><p>It is similar to the Deployment v2 version <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v2.yaml">FibonacciSample/K8/backend-deployment-v2.yaml</a> that we used in <a href="https://medium.com/@oshokry1/manage-revisions-of-a-rest-api-server-using-kubernetes-deployment-9c987306697">Part 7</a>. It does however have the following differences:</p><ul><li>The args is specified in <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v3.yaml#L26">line 26</a> as <em>[“-v”, “v3.0”, “-l”, “true”]</em>. This makes the REST API print a version of “v3.0” and enable logging as defined in <a href="https://github.com/oshokry/FibonacciSample/blob/master/fibonacci-backend/api.py#L18">line 18 of api.py</a>(this is where the REST API is implemented).</li><li>The Pod spec defines the volume in <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v3.yaml#L30-L33">lines 30–33</a> where it refers to the PVC <em>fibonacci-backend-pvc</em>.</li><li>The Pod spec mounts the volume at path “/logs” inside the Container, see <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v3.yaml#L27-L29">lines 27–29</a>. This allows the REST API to write the logs to the default file path <em>“/logs/system.log”</em>. See <a href="https://github.com/oshokry/FibonacciSample/blob/master/fibonacci-backend/api.py#L63">line 63 in api.py</a>.</li></ul><p>Now we have the Deployment which creates a ReplicaSet. The ReplicaSet creates 5 Pods. All the Pods are attached to one PVC, which is possible because all the Pods run on the same Kubernetes Node. Then the PVC is bound to the PV. This way, any of the 5 Pods can write to the log file which will be stored on the host machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*JbybGNRI7jHghHljOD9jcA.png" /><figcaption>A Deployment owns replics of a Pod on one Node. All the Pods, being on the same Node, can write to the same PV. The PV is mounted to a path on the host machine of the Kubernetes Node.</figcaption></figure><p>Let me reiterate that this PV type of <em>hostPath</em> should not be used in a Production Environment.</p><h3>Roll out V3 of the Fibonacci Backend</h3><p>Deploy v3 of the Fibonacci backend using the following command:</p><pre>$ kubectl apply -f backend-deployment-v3.yaml<br>deployment.apps/fibonacci-backend-deployment configured</pre><p>Wait for a minute for the v3 Pods to be deployed and the older Pods to be terminated. The Deployment will take care of this for you. Now check the deployment history:</p><pre>$ kubectl rollout history deployment fibonacci-backend-deployment<br>deployment.apps/fibonacci-backend-deployment<br>REVISION  CHANGE-CAUSE<br>2         Fibonacci-backend-v2<br>3         Fibonacci-backend-v1<br>4         Fibonacci-backend-v3</pre><p>We deployed revisions v1 and v2 in <a href="https://medium.com/@oshokry1/create-a-highly-available-rest-api-server-using-kubernetes-deployment-f7672be2efe">Part 6</a> and <a href="https://medium.com/@oshokry1/manage-revisions-of-a-rest-api-server-using-kubernetes-deployment-9c987306697">Part 7</a> respectively. This part added the revision v3. The <em>CHANGE-CAUSE</em> that appears in the revision history comes from the Deployment <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v3.yaml#L8-L9">annotation</a>.</p><p>Now let’s list the ReplicaSets:</p><pre>$ kubectl get rs<br>NAME                                      DESIRED   CURRENT   READY   AGE<br>fibonacci-backend-deployment-574644c474   5         5         5       27h<br>fibonacci-backend-deployment-5cc75ccd48   0         0         0       2d6h<br>fibonacci-backend-deployment-74597f7484   0         0         0       2d6h</pre><p>A new ReplicaSet has been created for revision v3, its name is <em>fibonacci-backend-deployment-574644c474</em>(<strong>the name will be different on your setup</strong>). It has 5 replicas of the v3 Pod, while the ReplicaSets for v1 and v2 are scaled down to 0 replicas.</p><h3>Test V3 of the Fibonacci Backend</h3><p>Let’s figure the Fibonacci of 50. Launch this URL in the browser:</p><p><a href="http://localhost:30070/fibonacci?n=50">http://localhost:30070/fibonacci?n=50</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*RaBdZvGUZVuk1XV2-Hb90w.png" /><figcaption>Fibonacci of 50 coming from the REST API v3.0</figcaption></figure><p>Note that the version is coming as <strong>v3.0</strong> as we configured it. Refresh the browser a few times to get the response from different Pods in the Deployment.</p><p>Now check if the logs made it to the log file on the host machine. On my machine I configured the path of the log file to become <em>C:\Fibonacci\logs\system.log.</em></p><p>The REST API Server is printing the results to the log file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c96cdfd30fbb01e528b5dc010fc0a6f0/href">https://medium.com/media/c96cdfd30fbb01e528b5dc010fc0a6f0/href</a></iframe><p>Our REST API Application persisted state on a directory on the host machine. For demonstration that was just a log file. You can use a PV to preserve important state information such as the contents of Database. If persisted on a PV, the data will outlive the Pods.</p><h3>What’s Next?</h3><p>In this part, you learned how to preserve the state of your application on the host machine with the help of Kubernetes PersistentVolume and PersistentVolumeClaim.</p><p>In <a href="https://medium.com/@oshokry1/manage-configuration-changes-to-your-kubernetes-application-using-configmap-and-portainer-c0f5387e9276">Part 9</a> you will learn how to add configuration flexibility to your application with the help of Kubernetes ConfigMap.</p><blockquote>Want to learn Docker and Kubernetes in 3 hours? Sign up to my course on Udemy now. Click this link → <a href="https://www.udemy.com/course/build-scalable-applications-using-docker-and-kubernetes/?referralCode=9650B00C60B732B30533"><strong>Build Scalable Applications using Docker and Kubernetes</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41b9f58ac3c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manage Revisions of a REST API Server using Kubernetes Deployment]]></title>
            <link>https://medium.com/@oshokry1/manage-revisions-of-a-rest-api-server-using-kubernetes-deployment-9c987306697?source=rss-e061736faabe------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c987306697</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Ossama Shokry]]></dc:creator>
            <pubDate>Wed, 15 Feb 2023 03:59:39 GMT</pubDate>
            <atom:updated>2024-04-05T19:24:49.962Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@oshokry1/create-a-highly-available-rest-api-server-using-kubernetes-deployment-f7672be2efe">Part 6</a> of this series, you created a Kubernetes Deployment for your REST API Server.</p><p>In this part, you will use the Kubernetes Deployment to manage revisions of your REST API Server. You will roll out a new version, roll back to a previous version, and check Deployment history of your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*vXX7xpf6bPP_fWd-pDDJWA.png" /><figcaption>Use a Kubernetes Deployment to Rollout/Pause/Rollback updates to your application</figcaption></figure><blockquote>Want to learn Docker and Kubernetes in 3 hours? Sign up to my course on Udemy now. Click this link → <a href="https://www.udemy.com/course/build-scalable-applications-using-docker-and-kubernetes/?referralCode=9650B00C60B732B30533"><strong>Build Scalable Applications using Docker and Kubernetes</strong></a></blockquote><h3>CD to the K8 directory</h3><p>If you did not pull the <a href="https://github.com/oshokry/FibonacciSample">FibonacciSample</a> application Git repository locally in a previous part of this series, do so by running the following command:</p><pre>$git clone https://github.com/oshokry/FibonacciSample.git</pre><p>Change directory to this path where you can find Kubernetes objects defined in YAML file format:</p><pre>$ cd FibonacciSample/K8/</pre><h3>Inspect the Backend Deployment YAML file(v2)</h3><p>Check the contents of <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v2.yaml">FibonacciSample/K8/backend-deployment-v2.yaml</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1469c9939abdafc46e7a139f96fcf78e/href">https://medium.com/media/1469c9939abdafc46e7a139f96fcf78e/href</a></iframe><p>The contents of the file are slightly different than v1 of the Deployment in file <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v1.yaml">FibonacciSample/K8/backend-deployment-v1.yaml</a>. Let’s start with the similarities. The Deployment name is the same: <em>fibonacci-backend-deployment</em>. <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v2.yaml#L5-L7">Labels</a>, <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v2.yaml#L12-L15">selectors</a>, and <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v2.yaml#L11">replicas</a> are also the same. Now let’s look at the differences.</p><h4>Deployment v2 annotation</h4><p>Check the <strong>annotations</strong> section at <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v2.yaml#L8-L9">lines 8–9</a>. The annotation value is <em>Fibonacci-backend-v2</em>, while in v1 it was <em>Fibonacci-backend-v1</em>. The annotation is an identifier to the Deployment, and it will be useful when we check the Deployment history later in this lab.</p><pre>  annotations:<br>    kubernetes.io/change-cause: Fibonacci-backend-v2</pre><h4>Deployment v2 Container Arguments</h4><p>Check the <strong>args</strong> defined in the last <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v2.yaml#L26">line 26</a>:</p><pre>args: [“-v”, “v2.0”]</pre><p>The container <em>oshokry/fibonacci-backend</em> takes an optional parameter “-v” to specify the REST API version in the Fibonacci function’s response. If no value is passed, the version defaults to “v1.0”. Check how this logic is implemented in the REST API flask code in api.py at <a href="https://github.com/oshokry/FibonacciSample/blob/master/fibonacci-backend/api.py#L11">line 11</a> and <a href="https://github.com/oshokry/FibonacciSample/blob/master/fibonacci-backend/api.py#L72-L73">lines 72–73</a>.</p><p>When you specify an <strong>args</strong> value in a Kubernetes Container spec, the args replace the CMD instruction of the Container. To understand what this means, check <a href="https://github.com/oshokry/FibonacciSample/blob/master/fibonacci-backend/Dockerfile#L11-L12">lines 11–12 of the Dockerfile</a> for the container:</p><pre>ENTRYPOINT [“python3”, “-u”, “/scripts/api.py”]<br># CMD [&quot;-v&quot;, &quot;v3.0&quot;, &quot;-l&quot;, &quot;true&quot;]</pre><p>The <em>ENTRYPOINT</em> Docker instruction is the command that the container will run, in this case it is “<em>python3 -u /scripts/api.py</em>”. The CMD Docker instruction appends parameters to the ENTRYPOINT. In the Dockerfile above this line is commented out. But in our Kubernetes YAML manifest file we specified <em>args: [“-v”, “v2.0”]</em> which results in a Docker instruction <em>CMD [“-v”, “v2.0”]</em>. This makes the container run the following command:</p><pre>python3 -u /scripts/api.py -v v2.0</pre><p>In short, the YAML file of the v2 Deployment runs the container in a way that makes it print “v2.0” as the version in the Fibonacci function result.</p><p>If you want to learn how the container image was created, refer to my article on this subject <a href="https://medium.com/@oshokry1/containerize-your-application-3f13a2f4901f">Use Docker to containerize a REST API made with Flask</a>.</p><h4>Deployment Strategy</h4><p>Since we did not specify a Deployment Strategy, the Deployment will have a strategy of <a href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#rolling-update-deployment"><em>RollingUpdate</em></a> by default. The Deployment with a RollingUpdate strategy will update Pods gradually. For instance, if you deploy v2 of the Pods, as you will see in the next section, then v1 Pods are taken down gradually while new v2 Pods are created. This ensures your service will have minimal or no downtime.</p><h3>Review the existing Fibonacci REST API v1</h3><p>In <a href="https://medium.com/@oshokry1/create-a-highly-available-rest-api-server-using-kubernetes-deployment-f7672be2efe">Part 6</a> you deployed v1 of the Fibonacci backend. List existing deployments using this command:</p><pre>$ kubectl get deployment<br>NAME                           READY   UP-TO-DATE   AVAILABLE   AGE<br>fibonacci-backend-deployment   5/5     5            5           5s</pre><p>The Deployment is up and running with 5 Replicas. To identify the ReplicaSet of the Deployment, list the existing ReplicaSets:</p><pre>$ kubectl get rs<br>NAME                                      DESIRED   CURRENT   READY   AGE<br>fibonacci-backend-deployment-74597f7484   5         5         5       83s</pre><p>The Deployment owns ReplicaSet <em>fibonacci-backend-deployment-74597f7484</em> which has 5 Replicas(Pods) of v1 of the REST API.</p><p>Launch this link in the browser to figure the Fibonacci of 15:</p><p><a href="http://localhost:30070/fibonacci?n=15">http://localhost:30070/fibonacci?n=15</a></p><p>The result shows version “v1.0”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*GTHzGpGH20ouTrOf8-bfPA.png" /><figcaption>Fibonacci RESt API v1</figcaption></figure><h3>Roll out Fibonacci v2</h3><p>You can deploy v2 of the backend using this command: <em>kubectl apply -f backend-deployment-v2.yaml</em>. You can monitor the rollout status of the deployment using this command: <em>kubectl rollout status deployment fibonacci-backend-deployment</em>. Let’s do them both in one bash command(separated by &amp;&amp;) so that we can monitor the deployment status on the terminal immediately after it starts. Run this command and watch updates of the Deployment rollout on the terminal:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9cf3ba457add179f2b2b51a0b80a7ba/href">https://medium.com/media/e9cf3ba457add179f2b2b51a0b80a7ba/href</a></iframe><p>You can see from the terminal output how Kubernetes is gradually scaling up the replicas(Pods) of the new deployment up to 5 replicas. E.g. <strong><em>2 out of 5 new replicas have been updated…</em></strong> .</p><p>You can also see how Kubernetes gradually terminates the replicas(Pods) of the old deployment. E.g. <strong><em>1 old replicas are pending termination…</em></strong> .</p><h4>Test the Fibonacci REST API v2</h4><p>If you check the REST API in the browser now, it shows version “v2.0”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*YylySWADY22pMeyRmPCAXA.png" /><figcaption>Fibonacci RESt API is upgraded to v2</figcaption></figure><h3>Inspect v2 of the Deployment</h3><p>Let’s list the existing ReplicaSets:</p><pre>$ kubectl get rs<br>NAME                                      DESIRED   CURRENT   READY   AGE<br>fibonacci-backend-deployment-5cc75ccd48   5         5         5       20m<br>fibonacci-backend-deployment-74597f7484   0         0         0       22m</pre><p>The Deployment now owns two ReplicaSets:</p><ul><li>ReplicaSet <em>fibonacci-backend-deployment-5cc75ccd48</em> is the currently active one with 5 Replicas of the v2 Pod.</li><li>ReplicaSet <em>fibonacci-backend-deployment-74597f7484</em> is the one from v1 and it is scaled down completely to 0. It does not have any Replicas.</li></ul><p>Run the following command to get more info about the deployment:</p><pre>$ kubectl describe deployment fibonacci-backend-deployment</pre><p>A lot of important information is printed about the deployment, for instance we get info about Replicas and Deployment Strategy:</p><pre>Replicas:               5 desired | 5 updated | 5 total | 5 available | 0 unavailable<br>StrategyType:           RollingUpdate</pre><p>Also check the Events section at the end of the <em>kubectl describe deployment</em> command output. We have useful logs about the scale up and scale down actions that happened to the ReplicaSets:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f39f234bf0fea9ad1be49c1d5367d61c/href">https://medium.com/media/f39f234bf0fea9ad1be49c1d5367d61c/href</a></iframe><p>Run this command to list the Deployment History:</p><pre>$ kubectl rollout history deployment fibonacci-backend-deployment<br>deployment.apps/fibonacci-backend-deployment<br>REVISION  CHANGE-CAUSE<br>1         Fibonacci-backend-v1<br>2         Fibonacci-backend-v2</pre><p>You get a nice list of Deployment Revisions, each one of them having a CHANGE_CAUSE that came from the Deployment <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v2.yaml#L8-L9">annotation</a>.</p><h3>Roll back to Fibonacci v1</h3><p>Let’s say you found a bug in v2 of the Fibonacci backend REST API Server and you want to revert to v1. You can simply rollback the Deployment using this command:</p><pre>$ kubectl rollout undo deployment fibonacci-backend-deployment &amp;&amp; kubectl rollout status deployment fibonacci-backend-deployment</pre><p>Watch updates printed on the terminal showing gradual scale up of the v1 Pods and gradual termination of the v2 Pods.</p><p>If you check the REST API in the browser now, it is back to showing version “v1.0”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*SsrRZX9hUMeZbWfCwSqNWg.png" /><figcaption>Fibonacci RESt API is reverted to v1</figcaption></figure><h3>Inspect the rolled back Deployment</h3><p>Let’s list the existing ReplicaSets again to see what changed after the rollback:</p><pre>$ kubectl get rs<br>NAME                                      DESIRED   CURRENT   READY   AGE<br>fibonacci-backend-deployment-5cc75ccd48   0         0         0       40m<br>fibonacci-backend-deployment-74597f7484   5         5         5       42m</pre><p>Note the difference after we rolled back to v1:</p><ul><li>ReplicaSet <em>fibonacci-backend-deployment-5cc75ccd48</em> which owns the v2 Replicas is scaled down to 0 Pods.</li><li>ReplicaSet fibonacci-backend-deployment-74597f7484 which owns the v1 Replicas is scaled up to 5 Pods.</li></ul><p>Now check Deployment history again:</p><pre>$ kubectl rollout history deployment fibonacci-backend-deployment<br>deployment.apps/fibonacci-backend-deployment<br>REVISION  CHANGE-CAUSE<br>2         Fibonacci-backend-v2<br>3         Fibonacci-backend-v1</pre><p>You see that the latest revision is 3 and it is v1 of the Fibonacci REST API. The revision 1 is gone because it was identical to revision 3. Kubernetes Deployment history keeps only one revision entry for a specific Deployment configuration.</p><p>Finally, let’s list the events that happened to each ReplicaSet so far. Remember the v1 ReplicaSet name ended in <em>74597f7484</em>, while the v2 ReplicaSet name ended in <em>5cc75ccd48</em>. We will use the power of the <em>grep</em> command to zero in on the events that took place to each ReplicaSet.</p><p><strong>Note that on your machine you will have different ids in the ReplicaSet names so check them and alter the commands below accordingly.</strong></p><p>List the events that took place to the v1 ReplicaSet using this command:</p><pre>$ kubectl describe deployment fibonacci-backend-deployment | grep 74597f7484</pre><ul><li>The Events show that the ReplicaSet was scaled up to 5 Replicas when we first deployed v1. Then it was scaled down to 0 Replicas when we deployed v2. Then it was scaled up again to 5 Replicas when we reverted to v1.</li></ul><p>List the events that took place to the v2 ReplicaSet using this command:</p><pre>$ kubectl describe deployment fibonacci-backend-deployment | grep 5cc75ccd48</pre><ul><li>The Events show that the ReplicaSet was scaled up to 5 Replicas when we deployed v2. Then it was scaled down to 0 Replicas when we reverted to v1.</li></ul><h3>What’s Next?</h3><p>In this part, you used the Kubernetes Deployment to manage revisions of your REST API Server. You rolled out a new version, rolled back to a previous version, and checked Deployment history of your application.</p><p>Head over to <a href="https://medium.com/@oshokry1/persist-the-state-of-your-application-using-kubernetes-persistent-volume-41b9f58ac3c5">Part 8</a>, where you will learn how to use Persistent Volumes to persist state of your Deployment on the host machine.</p><blockquote>Want to learn Docker and Kubernetes in 3 hours? Sign up to my course on Udemy now. Click this link → <a href="https://www.udemy.com/course/build-scalable-applications-using-docker-and-kubernetes/?referralCode=9650B00C60B732B30533"><strong>Build Scalable Applications using Docker and Kubernetes</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c987306697" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Highly Available REST API Server using Kubernetes Deployment]]></title>
            <link>https://medium.com/@oshokry1/create-a-highly-available-rest-api-server-using-kubernetes-deployment-f7672be2efe?source=rss-e061736faabe------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7672be2efe</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Ossama Shokry]]></dc:creator>
            <pubDate>Wed, 15 Feb 2023 03:56:45 GMT</pubDate>
            <atom:updated>2024-04-05T19:24:24.135Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@oshokry1/use-a-kubernetes-service-to-expose-a-highly-available-rest-api-server-bbc1bcfdd4a3">Part 5</a> of this series, you used a Kubernetes Service to expose multiple Pods in a <em>ReplicaSet</em> and load balance requests to them.</p><p>In this part, you will create a Kubernetes <em>Deployment</em> for your REST API Server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*s8vjvT532aJdRDH6DmWIBQ.png" /><figcaption>A Kubernetes Deployment manages a ReplicaSet of Pods</figcaption></figure><blockquote>Want to learn Docker and Kubernetes in 3 hours? Sign up to my course on Udemy now. Click this link → <a href="https://www.udemy.com/course/build-scalable-applications-using-docker-and-kubernetes/?referralCode=9650B00C60B732B30533"><strong>Build Scalable Applications using Docker and Kubernetes</strong></a></blockquote><h3>CD to the K8 directory</h3><p>If you did not pull the <a href="https://github.com/oshokry/FibonacciSample">FibonacciSample</a> application Git repository locally in a previous part of this series, do so by running the following command:</p><pre>$git clone https://github.com/oshokry/FibonacciSample.git</pre><p>Change directory to this path where you can find Kubernetes objects defined in YAML file format:</p><pre>$ cd FibonacciSample/K8/</pre><h3>Inspect the Backend Deployment YAML file</h3><p>Check the contents of <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v1.yaml">FibonacciSample/K8/backend-deployment-v1.yaml</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4bc8b5096d8c9070e904e4b480282e5/href">https://medium.com/media/d4bc8b5096d8c9070e904e4b480282e5/href</a></iframe><p>The file looks similar to the ReplicaSet file <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-replicaset.yaml">FibonacciSample/K8/backend-replicaset.yaml</a> from <a href="https://medium.com/@oshokry1/improve-application-scalability-and-fault-tolerance-using-kubernetes-replicasets-and-services-5d8b71d945fc">Part 4</a>, except that the kind is a <em>Deployment</em> instead of a <em>ReplicaSet</em> and we have 5 replicas instead of 3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*sBp5NDB1T7DivLy1gK71tg.png" /><figcaption>YAML files for a Deployment and a ReplicaSet are very similar</figcaption></figure><p>Just like the ReplicaSet, the Deployment identifies the Pods it needs to create and/or maintain using labels. Specifically:</p><ul><li>The <em>selector</em> section at <a href="https://gist.github.com/oshokry/940435b015cbe46edb546a31f82a704d#file-backend-deployment-v1-yaml-L10-L13">lines 10–13</a> identifies which Pods the Deployment owns.</li><li>The <em>template</em> section at <a href="https://gist.github.com/oshokry/940435b015cbe46edb546a31f82a704d#file-backend-deployment-v1-yaml-L16-L25">lines 16–25</a> defines the specification of the Pods the Deployment creates.</li></ul><p>With these identifiers and Pod specifications, any Pod that has labels <em>app=fibonacci</em> and <em>tier=backend</em> will fall under the control of the Deployment <em>fibonacci-backend-deployment</em>.</p><h4>Note about annotations</h4><p>The other difference with the Deployment YAML file is the <em>annotations</em> section. Think of this as an identifier to the Deployment. We will see how this will be useful when we list Deployment history in <a href="https://medium.com/TBD">Part 7</a>.</p><h3>Create the Fibonacci Backend Deployment</h3><p>Run this command to create the Deployment and list all the available Kubernetes objects right after:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/726865933dba9a8e12eb7d66f73ee339/href">https://medium.com/media/726865933dba9a8e12eb7d66f73ee339/href</a></iframe><p>Please note the following in the command output:</p><ul><li>Check the very last line. The Deployment created a ReplicaSet with the name <em>fibonacci-backend-deployment-74597f7484</em>. Please note that the ReplicaSet name comes from appending a random identifier to the <strong>Deployment</strong> name.</li><li>The ReplicaSet has a desired/current number of Pods of 5. There is currently 0 ready Pods as the Pods are still being created.</li><li>Check at the beginning of the console output. You will see 5 Pods being created. E.g., there is a Pod with the name <em>fibonacci-backend-deployment-74597f7484–5jsnj</em>. Please note that the Pod name comes from appending a random identifier to the <strong>ReplicaSet</strong> name.</li></ul><p>Wait a few seconds then list all Kubernetes objects in the cluster again using the command <em>kubectl get all</em>. You should have 5 Pods in the Running status and the ReplicaSet should have a count of 5 Ready Pods.</p><p>To learn more about a Deployment, use the <em>kubectl describe</em> command. A lot of interesting information about the Deployment is printed to the console. I’m showing the last few lines of the output only below as a sample:</p><pre>$ kubectl describe deployment fibonacci-backend-deployment<br>...<br>NewReplicaSet:   fibonacci-backend-deployment-74597f7484 (5/5 replicas created)<br>Events:<br>  Type    Reason             Age   From                   Message<br>  ----    ------             ----  ----                   -------<br>  Normal  ScalingReplicaSet  3m4s  deployment-controller  Scaled up replica set fibonacci-backend-deployment-74597f7484 to 5</pre><p>Those lines tell us that the Deployment created a ReplicaSet and scaled it up to 5 Pods.</p><h3>Test the REST API in the Browser</h3><p>You still have the <a href="https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport">NodePort</a> Service <em>fibonacci-backend-nps</em> that you created in <a href="https://medium.com/@oshokry1/improve-application-scalability-and-fault-tolerance-using-kubernetes-replicasets-and-services-5d8b71d945fc">Part 4</a>. If you do not have it, create it using this command:</p><pre>$ kubectl apply -f backend-services.yaml<br>service/fibonacci-backend-nps created<br>service/fibonacci-backend-cs created</pre><p>The <em>NodePort </em>service exposes the REST API Pods that the Deployment created because they match its label <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-services.yaml#L11-L13">selector</a>(<em>app=fibonacci</em> and <em>tier=backend</em>). The Service is available at host port 30070. Launch this URL in your browser to figure the Fibonacci of 15:</p><p><a href="http://localhost:30070/fibonacci?n=15">http://localhost:30070/fibonacci?n=15</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*0SRXzQBwpM486VdXWT-QeQ.png" /><figcaption>Kubernetes Service forwarded the request to Pod <strong>fibonacci-backend-deployment-74597f7484–5l7kb</strong></figcaption></figure><p>We got a response from Pod <em>fibonacci-backend-deployment-74597f7484–5l7kb</em><strong>.</strong></p><p>If you refresh the link long enough, you’ll see the service cycle the requests through all the available 5 Pods.</p><p>For instance, this time we got a response from Pod<em> fibonacci-backend-deployment-74597f7484-m85rw</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*8vlsnygdgwi4SWCPKFbB9Q.png" /><figcaption>Kubernetes Service forwarded the request to Pod <strong>fibonacci-backend-deployment-74597f7484-m85rw</strong></figcaption></figure><h3>Scale the Deployment down</h3><p>Issue the following command to scale the Deployment down to 3 replicas:</p><pre>$ kubectl scale deployment fibonacci-backend-deployment --replicas=3<br>deployment.apps/fibonacci-backend-deployment scaled</pre><p>Wait a few seconds then list the available Pods with the command <em>kubectl get pod</em>. You should see only 3 Pods in the Running state.</p><h3>Delete a Pod and see what happens</h3><p>What happens if we delete one of the remaining 3 Pods?</p><p>Run the following command to delete a Pod (<strong>Get the correct Pod name from your cluster, the name will be different!</strong>):</p><pre>$ kubectl delete pod fibonacci-backend-deployment-74597f7484-5jsnj<br>pod &quot;fibonacci-backend-deployment-74597f7484-5jsnj&quot; deleted</pre><p>If you list the available Pods again, you will still have 3 Pods because the Deployment created a new Pod in place of the one you just deleted. The Deployment keeps its promise of always maintaining 3 replicas of the Pod.</p><h3>Edit the Deployment using kubectl edit command</h3><p>Let’s scale the Deployment up to 5 Pods gain. This time, run this command to edit Kubernetes’s YAML representation of the Deployment:</p><pre>$ kubectl edit deployment fibonacci-backend-deployment</pre><p>You will see a YAML file for the Deployment open in the default system editor, usually <a href="https://www.cs.colostate.edu/helpdocs/vi.html"><em>vi</em></a>. The contents of this YAML file is much more extensive than the YAML file <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-deployment-v1.yaml">backend-deployment-v1.yaml</a> which we used to create the Deployment. This is because <a href="https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#edit">kubectl edit</a> command enables you to edit all the properties of a Kubernetes object, including properties that you did not specify when you created the object and therefore got a default value.</p><p>Let me explain this by example. We did not specify a Deployment Strategy in the original YAML file, yet the kubectl edit command brings a YAML file that includes the definition of a Deployment Strategy with default values. Check the contents of the <em>strategy</em> section under the <em>spec</em> section:</p><pre>spec:<br>  progressDeadlineSeconds: 600<br>  replicas: 5<br>  revisionHistoryLimit: 10<br>  selector:<br>    matchLabels:<br>      app: fibonacci<br>      tier: backend<br>  strategy:<br>    rollingUpdate:<br>      maxSurge: 25%<br>      maxUnavailable: 25%<br>    type: RollingUpdate</pre><p>We have a strategy type of <a href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#rolling-update-deployment"><em>RollingUpdate</em></a> by default. We will look further into the RollingUpdate in <a href="https://medium.com/TBD">Part 7</a>. For now, let’s use the open editor to change the replicase to 5 and save. If you have the file open in <a href="https://www.cs.colostate.edu/helpdocs/vi.html"><em>vi</em></a>, you can do this as follows:</p><ul><li>Press the letter <strong>i</strong> on your keyboard to bring <a href="https://www.cs.colostate.edu/helpdocs/vi.html"><em>vi</em></a><em> </em>to the <em>Insert Mode</em>.</li><li>Move your cursor to <em>replicas: 3</em> and change it to <em>replicas: 5</em>.</li><li>Press the <strong>Escape </strong>key on your keyboard to exit <a href="https://www.cs.colostate.edu/helpdocs/vi.html"><em>vi</em></a>’s <em>Insert Mode</em>.</li><li>Type the letters <strong>:wq</strong> then press Enter to save your changes.</li></ul><p>You get a message that the deployment has been edited:</p><pre>$ kubectl edit deployment fibonacci-backend-deployment<br>deployment.apps/fibonacci-backend-deployment edited</pre><p>Run this command to confirm that the Deployment has 5 replicas: <em>kubectl get deployment fibonacci-backend-deployment</em>.</p><h3>Change the default Editor for kubectl</h3><p>If you prefer to use a different editor with the <em>kubectl edit</em> command than the default <a href="https://www.cs.colostate.edu/helpdocs/vi.html"><em>vi</em></a><em> </em>editor, you can do so by setting the value for the <strong>KUBE_EDITOR</strong> environment variable. For instance, run the following command to use <em>nano</em> as your editor while editing the Deployment:</p><pre>KUBE_EDITOR=&quot;nano&quot; kubectl edit deployment fibonacci-backend-deployment</pre><h3>What’s Next?</h3><p>In this part, you created a Kubernetes Deployment for your REST API Server. You scaled the Deployment down to 3 Pods then up to 5 Pods. You saw how the Deployment maintains a stable number of Pods and in doing so terminates Pods or creates new Pods as needed.</p><p>In <a href="https://medium.com/@oshokry1/manage-the-lifecycle-of-a-rest-api-server-using-kubernetes-deployment-9c987306697">Part 7</a>, you will use the Kubernetes Deployment to roll out a new version, roll back to a previous version, and check Deployment history of your application.</p><blockquote>Want to learn Docker and Kubernetes in 3 hours? Sign up to my course on Udemy now. Click this link → <a href="https://www.udemy.com/course/build-scalable-applications-using-docker-and-kubernetes/?referralCode=9650B00C60B732B30533"><strong>Build Scalable Applications using Docker and Kubernetes</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7672be2efe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use A Kubernetes Service to expose a Highly Available REST API Server]]></title>
            <link>https://medium.com/@oshokry1/use-a-kubernetes-service-to-expose-a-highly-available-rest-api-server-bbc1bcfdd4a3?source=rss-e061736faabe------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbc1bcfdd4a3</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubernetes-service]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Ossama Shokry]]></dc:creator>
            <pubDate>Wed, 08 Feb 2023 20:25:04 GMT</pubDate>
            <atom:updated>2024-04-05T19:23:49.715Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@oshokry1/create-a-highly-available-rest-api-server-using-kubernetes-replicaset-336d649741ad">Part 4</a> of this series, you made the REST API server highly available by running multiple Pods of it in a Kubernetes <em>ReplicaSet</em>.</p><p>In this part, you will use a Kubernetes <em>Service</em> to expose the Pods and load balance requests to them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*T6bMB6znZMWYA2P7uoG24Q.png" /><figcaption>A Kubernetes Service exposes multiple Pods(owned by a ReplicaSet) and load balances requests to them</figcaption></figure><blockquote>Want to learn Docker and Kubernetes in 3 hours? Sign up to my course on Udemy now. Click this link → <a href="https://www.udemy.com/course/build-scalable-applications-using-docker-and-kubernetes/?referralCode=9650B00C60B732B30533"><strong>Build Scalable Applications using Docker and Kubernetes</strong></a></blockquote><h3>CD to the K8 directory</h3><p>If you did not pull the <a href="https://github.com/oshokry/FibonacciSample">FibonacciSample</a> application Git repository locally in a previous part of this series, do so by running the following command:</p><pre>$git clone https://github.com/oshokry/FibonacciSample.git</pre><p>Change directory to this path where you can find Kubernetes objects defined in YAML file format:</p><pre>$ cd FibonacciSample/K8/</pre><h3>Inspect the Backend Services YAML file</h3><p>Check the contents of <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-services.yaml">FibonacciSample/K8/backend-services.yaml</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e3dec90b5898bfcf611eb9d864391c3/href">https://medium.com/media/5e3dec90b5898bfcf611eb9d864391c3/href</a></iframe><p>Just like the ReplicaSet identified its Pods with labels, the Service identifies its Pods with labels too. We have two services defined in this file. Both have the same <em>selector</em> which identifies the Pods that the Service routes request to. Here is the selector definition:</p><pre>selector:<br>    app: fibonacci<br>    tier: backend</pre><p>The Services will expose any Pod with the labels <em>app=fibonacci</em> and <em>tier=backend</em>. Therefore, it covers Pods created by the ReplicaSet in file <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-replicaset.yaml">backend-replicaset.yaml</a> and the Pod created by the file <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-pod.yaml">backend-pod.yaml</a>.</p><h4>The NodePort Service</h4><p>A Service with the name <em>fibonacci-backend-nps</em> is defined in <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-services.yaml#L1-L13">lines 1–13</a>. The type of this service is <a href="https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport"><em>NodePort</em></a>. This is the Service type that we want to use to expose a set of Pods on a port on the host machine of the Kubernetes Node. With multiple nodes, each node proxies that port (the same port number on every Node) into the Service. <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-services.yaml#L10">Line 10</a> specifies the <em>nodePort</em> as <em>30070</em>, so this is the port we can use on the Kubernetes host machine to access the REST API from a browser.</p><h4>The ClusterIP Service</h4><p>A Service with the name <em>fibonacci-backend-cs</em> is defined in <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-services.yaml#L15-L24">lines 15–24</a>. Since no type was specified, the type of the Service defaults to <a href="https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types"><em>CusterIP</em></a>. This type exposes the Service on a cluster-internal IP which makes it accessible only from within the cluster.</p><p>Since the front-end will be deployed on the same Kubernetes cluster, a <em>ClusterIP</em> Service that is accessible only from within the cluster is what we want. Check <a href="https://github.com/oshokry/FibonacciSample/blob/master/fibonacci-frontend/php/invoke.php#L5">line 5</a> in file <em>FibonacciSample/fibonacci-frontend/php/invoke.php</em> from the front-end PHP code to see how the front end uses this Service as an end point to the Fibonacci REST API. We will deploy the front-end PHP application in <a href="https://medium.com/@oshokry1/build-a-two-tier-kubernetes-application-with-a-php-front-end-and-a-flask-rest-api-backend-b7effaeb7e22">Part 10</a> of this series.</p><h3>Create the Backend Services</h3><p>We created a ReplicaSet in <a href="https://medium.com/@oshokry1/create-a-highly-available-rest-api-server-using-kubernetes-replicaset-336d649741ad">Part 4</a> that maintains a stable set of 3 Pods serving the REST API. Now it is time to create a Kubernetes Service as a single entry point in front of the Pods. The Service will also load balance the requests to the Pods.</p><p>Run this command to create the NodePort and the ClusterIP Services:</p><pre>$ kubectl apply -f backend-services.yaml<br>service/fibonacci-backend-nps created<br>service/fibonacci-backend-cs created</pre><p>Two Services have been created. Run this command to get a list of Services:</p><pre>$ kubectl get svc<br>NAME                    TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE<br>fibonacci-backend-cs    ClusterIP   10.101.100.58   &lt;none&gt;        5000/TCP         13s<br>fibonacci-backend-nps   NodePort    10.109.55.139   &lt;none&gt;        5000:30070/TCP   13s<br>fibonacci-backend-pod   NodePort    10.99.246.122   &lt;none&gt;        5000:31042/TCP   18h<br>kubernetes              ClusterIP   10.96.0.1       &lt;none&gt;        443/TCP          11d</pre><p>The list shows that we now have a <em>NodePort</em> Service with the name <em>fibonacci-backend-nps</em> exposed on host port <em>30070</em>. There is also a <em>ClusterIP</em> service with the name <em>fibonacci-backend-cs</em>.</p><p>If you still have the <em>NodePort</em> Service with the name <em>fibonacci-backend-pod</em>(we created it in <a href="https://medium.com/@oshokry1/create-a-rest-api-server-in-a-kubernetes-pod-d24c73d032c">Part 3</a> of this series), feel free to delete it as we’ve just created a new <em>NodePort</em> Service:</p><pre>$ kubectl delete svc fibonacci-backend-pod<br>service &quot;fibonacci-backend-pod&quot; deleted</pre><h3>Access the REST API using the NodePort Service</h3><p>Launch this URL in your browser to figure the Fibonacci of 17:</p><p><a href="http://localhost:30070/fibonacci?n=17">http://localhost:30070/fibonacci?n=17</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*Isxlcm7DtY4_psnjSJ-pog.png" /><figcaption>Response from Pod <strong>fibonacci-backend-rs-48b6m</strong></figcaption></figure><p>The Fibonacci REST API prints the name of the host, which is also the name of the Pod. See how this is done in api.py at <a href="https://github.com/oshokry/FibonacciSample/blob/master/fibonacci-backend/api.py#L23">line 23</a>.</p><p>We got a response from Pod <em>fibonacci-backend-rs-48b6m</em>. Refresh the link a few times and see the responses coming from the other two Pods too:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*kPUIUF1jrnetwpXu4QjTyA.png" /><figcaption>Response from Pod <strong>fibonacci-backend-rs-rpbnw</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*ZSkzGhTZUMMdNFQQ0tzq_g.png" /><figcaption>Response from Pod <strong>fibonacci-backend-rs-jxfdw</strong></figcaption></figure><p>You see, the NodePort service is doing the load balancing for us to all the Pods in the ReplicaSet.</p><h3>A word about Labels and Selectors</h3><p>We are creating the REST API Pods with the labels <em>app=fibonacci</em> and <em>tier=backend</em>. So far, we have seen how Kubernetes resources <em>ReplicaSet </em>and<em> Service</em> match these labels via their selectors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZGDPJfgtUeT7e0AWd0GGg.png" /><figcaption>A Pod identifies itself using <strong>labels</strong>. A ReplicaSet and a Service refer to this Pod using <strong>selectors</strong>.</figcaption></figure><p>This is a general pattern in Kubernetes. An object in Kubernetes is identified by labels, and other objects can refer to it by selectors that match those labels.</p><h3>Delete the ReplicaSet</h3><p>ReplicaSet is great, but Kubernetes <em>Deployment</em> is even better. A Deployment owns a ReplicaSet and adds more features to it, so it is advisable to use a Deployment instead of a plain ReplicaSet. Let’s delete the ReplicaSet for now.</p><p>Do not worry! We will create a Deployment in the next part of this series, and the Deployment will create a ReplicaSet for us and provide better manageability for our application.</p><p>Now run the following command to delete the ReplicaSet:</p><pre>$ kubectl delete rs fibonacci-backend-rs<br>replicaset.apps &quot;fibonacci-backend-rs&quot; deleted</pre><h3>What’s Next?</h3><p>In this part, you used a Kubernetes <em>Service</em> to expose multiple Pods in a ReplicaSet and load balance requests to them.</p><p>In <a href="https://medium.com/@oshokry1/create-a-highly-available-rest-api-server-using-kubernetes-deployment-f7672be2efe">Part 6</a>, where you will create a Kubernetes <em>Deployment </em>for your REST API Server.</p><blockquote>Want to learn Docker and Kubernetes in 3 hours? Sign up to my course on Udemy now. Click this link → <a href="https://www.udemy.com/course/build-scalable-applications-using-docker-and-kubernetes/?referralCode=9650B00C60B732B30533"><strong>Build Scalable Applications using Docker and Kubernetes</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbc1bcfdd4a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Highly Available REST API Server using Kubernetes ReplicaSet]]></title>
            <link>https://medium.com/@oshokry1/create-a-highly-available-rest-api-server-using-kubernetes-replicaset-336d649741ad?source=rss-e061736faabe------2</link>
            <guid isPermaLink="false">https://medium.com/p/336d649741ad</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[replicaset]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Ossama Shokry]]></dc:creator>
            <pubDate>Wed, 08 Feb 2023 20:23:22 GMT</pubDate>
            <atom:updated>2024-04-05T19:23:12.263Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@oshokry1/create-a-rest-api-server-in-a-kubernetes-pod-d24c73d032c">Part 3</a> of this series, you created a Pod that exposes a REST API and made the API accessible from your host machine.</p><p>In this part, you will make the REST API server highly available by running multiple Pods of it in a Kubernetes <em>ReplicaSet</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*VCXpNFoRB9yLBHBCd1ZKEA.png" /><figcaption>A Kubernetes ReplicaSet mainains a stable number of Pods</figcaption></figure><blockquote>Want to learn Docker and Kubernetes in 3 hours? Sign up to my course on Udemy now. Click this link → <a href="https://www.udemy.com/course/build-scalable-applications-using-docker-and-kubernetes/?referralCode=9650B00C60B732B30533"><strong>Build Scalable Applications using Docker and Kubernetes</strong></a></blockquote><h3>CD to the K8 directory</h3><p>If you did not pull the <a href="https://github.com/oshokry/FibonacciSample">FibonacciSample</a> application Git repository locally in a previous part of this series, do so by running the following command:</p><pre>$git clone https://github.com/oshokry/FibonacciSample.git</pre><p>Change directory to this path where you can find Kubernetes objects defined in YAML file format:</p><pre>$ cd FibonacciSample/K8/</pre><h3>Still have that single Pod?</h3><p>If you did <a href="https://medium.com/@oshokry1/create-a-rest-api-server-in-a-kubernetes-pod-d24c73d032c">Part 3</a> of this series, you should have one Pod running the Fibonacci REST API container. Check that the Pod is there using this command:</p><pre>$ kubectl get pod<br>NAME                    READY   STATUS    RESTARTS   AGE<br>fibonacci-backend-pod   1/1     Running   0          2m20s</pre><p>If the Pod is not there, create it with this command:</p><pre>$ kubectl apply -f backend-pod.yaml<br>pod/fibonacci-backend-pod created</pre><h3>Inspect the Backend ReplicaSet YAML file</h3><p>Check the contents of <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-replicaset.yaml">FibonacciSample/K8/backend-replicaset.yaml</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b80cb789f95d79d8761b9856e768e2e/href">https://medium.com/media/2b80cb789f95d79d8761b9856e768e2e/href</a></iframe><p>The YAML file <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-replicaset.yaml">backend-replicaset.yaml</a> defines a ReplicaSet object with 3 replicas of the Pod <em>fibonacci-backend-pod</em>. To do so it specifies the kind as <em>ReplicaSet</em> at <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-replicaset.yaml#L2">line 2</a>, and the replica count as 3 at <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-replicaset.yaml#L9">line 9</a>.</p><p>The ReplicaSet needs to know the specification of the Pods it needs to create and/or maintain. To learn how this is happening, put the ReplicaSet YAML file <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-replicaset.yaml">backend-replicaset.yaml</a> and the Pod YAML file <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-pod.yaml">backend-pod.yaml</a> side by side. You will notice an interesting similarity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*_o5dChOpDqQgbPdE-3_MjQ.png" /><figcaption>How a ReplicaSet knows its Pods</figcaption></figure><h4>Pod Identification</h4><p>The <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-replicaset.yaml#L11-L13"><em>matchLabels</em> </a>section in the ReplicaSet YAML file <em>backend-replicaset.yaml</em> is how the ReplicaSet identifies the Pods it needs to <strong>acquire and/or maintain</strong>. This section is just copied from the Pod YAML file backend-pod.yaml <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-pod.yaml#L5-L7"><em>labels</em> </a>section.</p><p>1. The <em>matchLabels</em> section identifies the Pods that the ReplicaSet owns. Any Pod with labels <em>app=fibonacci</em> and <em>tier=backend</em> will be acquired by the ReplicaSet.</p><p>2. Since the Pod created by the Pod YAML file backend-pod.yaml matches the labels <em>app=fibonacci</em> and <em>tier=backend</em>, the ReplicaSet will acquire it and maintain it even though it did not create it.</p><h4>Pod Specification</h4><p>The <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-replicaset.yaml#L14-L23"><em>template</em></a> section in the ReplicaSet YAML file <em>backend-replicaset.yaml</em> is how the ReplicaSet defines the specification of the Pods it needs to <strong>create</strong>. This section is just copied from the Pod YAML file backend-pod.yaml <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-pod.yaml#L3-L11"><em>metadata</em> and <em>spec</em></a> sections.</p><p>1. The <em>metadata</em> subsection identifies the Pod with a name of <em>fibonacci-backend-pod</em> and a couple of labels <em>app=fibonacci</em> and <em>tier=backend</em>.</p><p>2. The spec subsection declares that the pod will run one container with the name <em>fibonacci-backend</em>, based on the image <em>oshokry/fibonacci-backend</em>.</p><h3>Create the Fibonacci Backend ReplicaSet</h3><p>Run this command to create the ReplicaSet and list the available Pods right after:</p><pre>$ kubectl apply -f backend-replicaset.yaml &amp;&amp; kubectl get pod<br>replicaset.apps/fibonacci-backend-rs created<br>NAME                         READY   STATUS              RESTARTS   AGE<br>fibonacci-backend-pod        1/1     Running             0          12s<br>fibonacci-backend-rs-kn7sn   0/1     ContainerCreating   0          0s<br>fibonacci-backend-rs-rfzm4   0/1     ContainerCreating   0          0s</pre><p>There are 2 Pods being created(<em>STATUS=ContainerCreating</em>). Each Pod’s name starts with the ReplicaSet name <em>fibonacci-backend-rs</em>, then a random 5 character id is appended to it to make the name unique. Check again after a few seconds and you will see that there is a total of 3 Pods running:</p><pre>$ kubectl get pod<br>NAME                         READY   STATUS    RESTARTS   AGE<br>fibonacci-backend-pod        1/1     Running   0          2m11s<br>fibonacci-backend-rs-kn7sn   1/1     Running   0          119s<br>fibonacci-backend-rs-rfzm4   1/1     Running   0          119s</pre><p>Now check the ReplicaSet. It has the 3 Pods it needs in a READY state:</p><pre>$ kubectl get rs<br>NAME                   DESIRED   CURRENT   READY   AGE<br>fibonacci-backend-rs   3         3         3       2m50s</pre><p>Why did the ReplicaSet create 2 Pods only although it has <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-replicaset.yaml#L9">replicas: 3</a>? The ReplicaSet was able to identify the Pod that was created using the YAML file <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-pod.yaml">backend-pod.yaml</a> as one of its own because it matched its labels. So, the ReplicaSet acquired that Pod. To bring the number of replicas to 3, The ReplicaSet needed to create just 2 more Pods.</p><p>Issue the following command to get a list of all objects running on the Kubernetes cluster:</p><pre>$ kubectl get all<br>NAME                             READY   STATUS    RESTARTS   AGE<br>pod/fibonacci-backend-pod        1/1     Running   0          3m19s<br>pod/fibonacci-backend-rs-kn7sn   1/1     Running   0          3m7s<br>pod/fibonacci-backend-rs-rfzm4   1/1     Running   0          3m7s<br>NAME                            TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE<br>service/fibonacci-backend-pod   NodePort    10.99.246.122   &lt;none&gt;        5000:31042/TCP   5h58m<br>service/kubernetes              ClusterIP   10.96.0.1       &lt;none&gt;        443/TCP          10d<br>NAME                                   DESIRED   CURRENT   READY   AGE<br>replicaset.apps/fibonacci-backend-rs   3         3         3       3m7s</pre><p>A list of the available 3 Pods, 2 Services, and 1 ReplicaSet is returned. Use the <em>kubectl describe</em> command to learn more about the ReplicaSet(output abbreviated a bit):</p><pre>$ kubectl describe rs fibonacci-backend-rs<br>Name:         fibonacci-backend-rs<br>Namespace:    default<br>Selector:     app=fibonacci,tier=backend<br>Labels:       app=fibonacci<br>              tier=backend<br>Annotations:  &lt;none&gt;<br>Replicas:     3 current / 3 desired<br>Pods Status:  3 Running / 0 Waiting / 0 Succeeded / 0 Failed<br>Pod Template:<br>  Labels:  app=fibonacci<br>           tier=backend<br>...<br>Events:<br>  Type    Reason            Age    From                   Message<br>  ----    ------            ----   ----                   -------<br>  Normal  SuccessfulCreate  4m46s  replicaset-controller  Created pod: fibonacci-backend-rs-rfzm4<br>  Normal  SuccessfulCreate  4m46s  replicaset-controller  Created pod: fibonacci-backend-rs-kn7sn</pre><p>Note that the <em>Selector</em> labels match the <em>Pod Template</em> labels(both having <em>app=fibonacci, tier=backend</em>). Furthermore, note under the Events section that the ReplicaSet created two Pods successfully.</p><h3>Manage the ReplicaSet</h3><p>Let’s first delete the ReplicaSet and see what happens to the Pod named <em>fibonacci-backend-pod</em> that we created even before creating the ReplicaSet. Run a command to delete the ReplicaSet followed by a command to list the available Pods:</p><pre>$ kubectl delete rs fibonacci-backend-rs &amp;&amp; kubectl get pod<br>replicaset.apps &quot;fibonacci-backend-rs&quot; deleted<br>NAME                         READY   STATUS        RESTARTS   AGE<br>fibonacci-backend-pod        1/1     Terminating   0          22m<br>fibonacci-backend-rs-kn7sn   1/1     Terminating   0          22m<br>fibonacci-backend-rs-rfzm4   1/1     Terminating   0          22m</pre><p>Deleting the ReplicaSet deleted the Pod named <em>fibonacci-backend-pod </em>too, although the ReplicaSet did not create it. This is expected because the ReplicaSet acquired the Pod since the <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-pod.yaml#L5-L7">Pod’s labels</a> matched the ReplicaSet’s <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-replicaset.yaml#L10-L13">label selector</a>.</p><p>Check the Pods in the cluster after a few seconds, they should be gone by now:</p><pre>$ kubectl get pod<br>No resources found in default namespace.</pre><p>Let’s create the ReplicaSet again and check the Pods. Run this command:</p><pre>$ kubectl apply -f backend-replicaset.yaml &amp;&amp; kubectl get pod<br>replicaset.apps/fibonacci-backend-rs created<br>NAME                         READY   STATUS              RESTARTS   AGE<br>fibonacci-backend-rs-48b6m   0/1     ContainerCreating   0          0s<br>fibonacci-backend-rs-jxfdw   0/1     ContainerCreating   0          0s<br>fibonacci-backend-rs-rpbnw   0/1     ContainerCreating   0          0s</pre><p>See? This time because there was no Pods that match the ReplicaSet’s selector, the ReplicaSet created 3 Pods. Wait a few seconds for the Pods to start, then list the available Pods using the command <em>kubectl get pod</em>. You should see 3 Pods in a Running state.</p><h4>Scale the ReplicaSet</h4><p>Run the following command to scale the ReplicaSet up to 5 Pods and list the Pods immediately after that:</p><pre>$ kubectl scale --replicas=5 -f backend-replicaset.yaml &amp;&amp; kubectl get pod<br>replicaset.apps/fibonacci-backend-rs scaled<br>NAME                         READY   STATUS              RESTARTS   AGE<br>fibonacci-backend-rs-48b6m   1/1     Running             0          112s<br>fibonacci-backend-rs-8kl5z   0/1     ContainerCreating   0          0s<br>fibonacci-backend-rs-g5q2m   0/1     ContainerCreating   0          0s<br>fibonacci-backend-rs-jxfdw   1/1     Running             0          112s<br>fibonacci-backend-rs-rpbnw   1/1     Running             0          112s</pre><p>Two more Pods are being created to bring the total number of replicas to 5 as instructed. Please note that although we used the ReplicaSet YAML file <em>backend-replicaset.yaml</em> in the command, <strong>the contents of the file are NOT changed</strong>. View the file on your machine, it still has <em>replicas: 3</em>.</p><p>Let’s scale the ReplicaSet down to 3 replicas again. This time without referencing the ReplicaSet YAML file. Run the following command:</p><pre>$ kubectl scale rs fibonacci-backend-rs --replicas=3 &amp;&amp; kubectl get pod<br>replicaset.apps/fibonacci-backend-rs scaled<br>NAME                         READY   STATUS        RESTARTS   AGE<br>fibonacci-backend-rs-48b6m   1/1     Running       0          3m26s<br>fibonacci-backend-rs-8kl5z   1/1     Terminating   0          94s<br>fibonacci-backend-rs-g5q2m   1/1     Terminating   0          94s<br>fibonacci-backend-rs-jxfdw   1/1     Running       0          3m26s<br>fibonacci-backend-rs-rpbnw   1/1     Running       0          3m26s</pre><p>The ReplicaSet kept 3 Pods and is terminating 2 Pods. In a few seconds list the available Pods, you should only find 3:</p><pre>$ kubectl get pod<br>NAME                         READY   STATUS    RESTARTS   AGE<br>fibonacci-backend-rs-48b6m   1/1     Running   0          4m27s<br>fibonacci-backend-rs-jxfdw   1/1     Running   0          4m27s<br>fibonacci-backend-rs-rpbnw   1/1     Running   0          4m27s</pre><h3>What’s Next?</h3><p>In this part, you made the REST API Server highly available by running multiple Pods of it in a Kubernetes <em>ReplicaSet</em>.</p><p>In <a href="https://medium.com/@oshokry1/use-a-kubernetes-service-to-expose-a-highly-available-rest-api-server-bbc1bcfdd4a3">Part 5</a>, you will use a Kubernetes <em>Service</em> to expose the Pods and load balance requests to them.</p><blockquote>Want to learn Docker and Kubernetes in 3 hours? Sign up to my course on Udemy now. Click this link → <a href="https://www.udemy.com/course/build-scalable-applications-using-docker-and-kubernetes/?referralCode=9650B00C60B732B30533"><strong>Build Scalable Applications using Docker and Kubernetes</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=336d649741ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Install Kubernetes on your machine and run a Hello World Pod]]></title>
            <link>https://medium.com/@oshokry1/install-kubernetes-on-your-machine-and-run-a-hello-world-pod-6aa378a51e81?source=rss-e061736faabe------2</link>
            <guid isPermaLink="false">https://medium.com/p/6aa378a51e81</guid>
            <category><![CDATA[container-images]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[hello-world]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Ossama Shokry]]></dc:creator>
            <pubDate>Tue, 07 Feb 2023 00:28:59 GMT</pubDate>
            <atom:updated>2024-04-05T19:22:06.317Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@oshokry1/a-practical-introduction-to-kubernetes-2390682c6139">Part 1</a> of this series, you started with a brief overview about Containers and Docker. You then went through Kubernetes concepts, and explored several of Kubernetes’s constructs such as Pods, ReplicaSets, and Deployments.</p><p>In this part, you will install Kubernetes on your machine and run a Pod with a <em>hello-world</em> container image on your own Kubernetes cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*tZaampH4gC5a-nl4AKjehw.png" /><figcaption>Hello, World! from Kubernetes</figcaption></figure><blockquote>Want to learn Docker and Kubernetes in 3 hours? Sign up to my course on Udemy now. Click this link → <a href="https://www.udemy.com/course/build-scalable-applications-using-docker-and-kubernetes/?referralCode=9650B00C60B732B30533"><strong>Build Scalable Applications using Docker and Kubernetes</strong></a></blockquote><h3>Install Kubernetes</h3><p>Let’s first install Kubernetes on your machine. If you have Windows, Linux on PC, or a Mac, I recommend installing Docker Desktop as it comes with Kubernetes too. Follow Docker Desktop installation instructions for your platform from the <a href="https://docs.docker.com/get-docker/">Get Docker</a> documentation page. Once you have Docker Desktop installed, open the settings page and enable Kubernetes by selecting the Kubernetes tab then simply select the “Enable Kubernetes” check box. Click Apply &amp; restart and you will have your local Kubernetes cluster up and running within minutes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*1xZ30owhyqW3jCBtQiNkmg.png" /><figcaption>Enable Kubernetes on Docker Desktop</figcaption></figure><h4>Install Kubernetes on Raspberry Pi</h4><p>You can install Kubernetes on any <strong>Raspberry Pi 4</strong>. I recommend installing <a href="https://k3s.io/">K3S</a>, which is a lightweight version of Kubernetes designed for IoT and Edge computing.</p><p>First you need to enable <strong>cgroups </strong>by adding “cgroup_memory=1 cgroup_enable=memory” to the file <em>/boot/cmdline.txt</em>. Edit the file:</p><pre>pi@raspberrypi:~ $ sudo nano /boot/cmdline.txt</pre><p>Append “cgroup_memory=1 cgroup_enable=memory” to the end of the file like so and save it:</p><pre>console=serial0,115200 console=tty1 root=PARTUUID=fce96a78–02 rootfstype=ext4 fsck.repair=yes rootwait cgroup_memory=1 cgroup_enable=memory</pre><p>Reboot your Raspberry Pi:</p><pre>pi@raspberrypi:~ $ sudo reboot</pre><p>Now install K3S:</p><pre># Run this command to install K3S. The ‘ — write-kubeconfig-mode=644’ option lets you use K3S without sudo<br>pi@raspberrypi:~ $ curl -sfL https://get.k3s.io | INSTALL_K3S_EXEC=&#39; - write-kubeconfig-mode=644&#39; sh -<br># Check for Ready node, takes ~30 seconds<br>pi@raspberrypi:~ $ k3s kubectl get node</pre><h3>Hello, World! Kubernetes Edition</h3><p>Let’s first confirm that your Kubernetes setup is functioning properly. Check the Kubernetes cluster using its Command Line tool <em>kubectl</em>. Issue the following command from your terminal:</p><pre># if you installed K3S on a Raspberry Pi, use &quot;k3s kubectl get node&quot; instead<br>$ kubectl get node<br>NAME             STATUS   ROLES           AGE   VERSION<br>docker-desktop   Ready    control-plane   10d   v1.25.4</pre><p>The command output confirms that we have a working Kubernetes node. Now issue the following command from your terminal to run a hello-world container in a Kubernetes Pod(rest of output not shown):</p><pre>$ kubectl run test --restart=Never --image=hello-world -it<br>Hello from Docker!<br>This message shows that your installation appears to be working correctly.<br>...</pre><p>Now let’s explain what happened. The above command instructed Kubernetes to run a container in a Pod with the following specifications:</p><ul><li><em>run test</em>: Launch a Pod with the name <em>test</em>.</li><li><em>--restart=Never</em>:<em> </em>Do not restart the Pod if it exits.</li><li><em>--image=hello-world</em>:<em> </em>Container image is <em>hello-world</em>.</li><li>Flags <em>-it</em>: run the Pod in the foreground so that its output is printed on the host terminal.</li></ul><p>A Pod with one container of the <em>hello-world</em> image was run and printed its output on your terminal. Then the Pod exited because the <em>hello-world</em> container prints that message and exits.</p><p>Kubernetes keeps restarting a stopped Pod by default so it would have kept restarting the Pod forever if we have not prevented it from doing so with the --<em>restart=Never </em>option. Let’s check the existing Pods in the Kubernetes cluster:</p><pre>$ kubectl get pod<br>NAME                    READY   STATUS      RESTARTS      AGE<br>test                    0/1     Completed   0             2m48s</pre><p>There is one Pod in the <em>Completed</em> status, because the <em>test</em> Pod have exited after the <em>hello-world</em> container exited. Get more information about the Pod using the <em>kubectl describe pod</em> command(command output abbreviated below):</p><pre>$ kubectl describe pod test<br>Name:             test<br>Namespace:        default<br>Priority:         0<br>Service Account:  default<br>Node:             docker-desktop/192.168.65.4<br>Start Time:       Sun, 05 Feb 2023 13:32:29 -0600<br>Labels:           run=test<br>Annotations:      &lt;none&gt;<br>Status:           Succeeded<br>IP:               10.1.0.139<br>IPs:<br>  IP:  10.1.0.139<br>Containers:<br>  test:<br>    Container ID:   docker://bf17d738b26b595f9f416a6231153ada0331a793be396b90f69c79eb57011f5b<br>    Image:          hello-world<br>    Image ID:       docker-pullable://hello-world@sha256:aa0cc8055b82dc2509bed2e19b275c8f463506616377219d9642221ab53cf9fe<br>...</pre><p>The <em>describe</em> command gives extensive information about the Pod, such as the Node it runs on(docker-desktop/192.168.65.4), the Pod IP address(10.1.0.139), the Pod status(Succeeded) and container specification etc.</p><p>Delete the Pod:</p><pre>$ kubectl delete pod test<br>pod &quot;test&quot; deleted</pre><p>Now let’s run the Pod again and delete it immediately this time after it exits, by adding the -<em>-rm</em> option:</p><pre>$ kubectl run test --restart=Never --rm --image=hello-world -it<br>Hello from Docker!<br>This message shows that your installation appears to be working correctly.<br>...<br>pod &quot;test&quot; deleted</pre><p>There you have it! You just ran the famous Hello, World! application on your own Kubernetes cluster.</p><h3>What’s Next?</h3><p>In this part, you installed Kubernetes on your machine and successfully ran a Hello, World! Pod on your own Kubernetes cluster.</p><p>In <a href="https://medium.com/@oshokry1/create-a-rest-api-server-in-a-kubernetes-pod-d24c73d032c">Part 3</a>, you will create a Pod that exposes a REST API and make the API accessible from your host machine.</p><blockquote>Want to learn Docker and Kubernetes in 3 hours? Sign up to my course on Udemy now. Click this link → <a href="https://www.udemy.com/course/build-scalable-applications-using-docker-and-kubernetes/?referralCode=9650B00C60B732B30533"><strong>Build Scalable Applications using Docker and Kubernetes</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6aa378a51e81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a REST API Server in a Kubernetes Pod]]></title>
            <link>https://medium.com/@oshokry1/create-a-rest-api-server-in-a-kubernetes-pod-d24c73d032c?source=rss-e061736faabe------2</link>
            <guid isPermaLink="false">https://medium.com/p/d24c73d032c</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[container-images]]></category>
            <dc:creator><![CDATA[Ossama Shokry]]></dc:creator>
            <pubDate>Tue, 07 Feb 2023 00:28:46 GMT</pubDate>
            <atom:updated>2024-04-05T19:22:44.522Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/@oshokry1/install-kubernetes-on-your-machine-and-run-a-hello-world-pod-6aa378a51e81">Part 2</a> of this series, you installed Kubernetes on your machine and successfully ran a hello-world Pod on your own Kubernetes cluster.</p><p>In this part, you will create a Pod that exposes a REST API and make the API accessible from your host machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*q-KNLhuQgMcyOCLxjsSm_A.png" /><figcaption>A Kubernetes Pod serving a REST API</figcaption></figure><blockquote>Want to learn Docker and Kubernetes in 3 hours? Sign up to my course on Udemy now. Click this link → <a href="https://www.udemy.com/course/build-scalable-applications-using-docker-and-kubernetes/?referralCode=9650B00C60B732B30533"><strong>Build Scalable Applications using Docker and Kubernetes</strong></a></blockquote><h3>Introducing the FibonacciSample Application</h3><p>Moving forward, we will be using the <a href="https://github.com/oshokry/FibonacciSample">FibonacciSample</a> application. This application has two layers: a backend which implements the <a href="https://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci</a> function as a <a href="https://www.redhat.com/en/topics/api/what-is-a-rest-api">REST API</a> and a front end that invokes the REST API and prints the result. In this part we will focus on the backend layer. Run the following command to get the application source code:</p><pre>$git clone https://github.com/oshokry/FibonacciSample.git</pre><p>A REST API that serves the Fibonacci function is implemented using the <a href="https://palletsprojects.com/p/flask/">Flask</a> web framework. The input is an integer, and the response is the Fibonacci value for that integer in an HTML format. Check the API implementation in the <a href="https://github.com/oshokry/FibonacciSample/blob/master/fibonacci-backend/api.py">FibonacciSample/fibonacci-backend/api.py</a> file. The REST API is containerized in Docker image <a href="https://hub.docker.com/r/oshokry/fibonacci-backend">oshokry/fibonacci-backend</a>. If you want to learn how the container image was created, refer to my article on this subject <a href="https://medium.com/@oshokry1/containerize-your-application-3f13a2f4901f">Use Docker to containerize a REST API made with Flask</a>.</p><h3>Inspect the Pod YAML file</h3><p>Change directory to this path in the Fibonacci application’s Git repository that you just cloned: <em>FibonacciSample/K8.</em></p><p>Check the contents of <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-pod.yaml">FibonacciSample/K8/backend-pod.yaml</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a39dffaed52828a7804aeb071b31f682/href">https://medium.com/media/a39dffaed52828a7804aeb071b31f682/href</a></iframe><p>You can describe the specification of a Kubernetes object using a YAML(YAML Ain’t Markup Language) file. YAML is a human readable data serialization language. The basic structure in a YAML file is a map of key-value pairs simply written in this format:</p><blockquote><strong>key</strong>: value</blockquote><p>For instance, in <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-pod.yaml#L1">line 1</a> of backend-pod.yaml file above, the <em>apiVersion</em> has a value of “v1”:</p><pre>01 apiVersion: v1</pre><p>To define nested data structures, you use space indentation. You indent using spaces, not tabs. It is a good idea to stick to a two-space indentation per level. An example of the YAML file above is the contents of the <em>metadata</em> section in <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-pod.yaml#L3-L7">lines 3–7</a>:</p><pre>03 metadata:<br>04  name: fibonacci-backend-pod<br>05  labels:<br>06    app: fibonacci<br>07    tier: backend</pre><p>Here <em>metadata</em> has a child property with the name <em>name</em>. It has another child property with the name <em>labels</em> and the latter has two child properties <em>app</em> and <em>tier</em>. If you would represent the <em>metadata</em> construct using XML, it would look something like this:</p><pre>&lt;metadata&gt;<br>  &lt;name&gt;fibonacci-backend-pod&lt;/name&gt;<br>  &lt;labels&gt;<br>    &lt;app&gt;fibonacci&lt;/app&gt;<br>    &lt;tier&gt;backend&lt;/tier&gt;<br>  &lt;/labels&gt;<br>&lt;/metadata&gt;</pre><p>To declare an array in YAML, you use dashes. Since a Pod in Kubernetes can have one or more containers, the Pod YAML file defines an array of containers. In this example it has an array of one, see lines <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-pod.yaml#L9-L11">9–11</a>:</p><pre>09 containers:<br>10    - name: fibonacci-backend<br>11      image: oshokry/fibonacci-backend</pre><p>I like to use a tool such as <a href="https://code.visualstudio.com/">VS Code</a> to edit YAML files. It gives you a visual representation of the structure of the file and allows you to collapse or expand sections of the file. This makes it easy to understand the nested structure of the YAML file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*pp-IzRH3wXTbKRz4u1tRZA.png" /><figcaption>A YAML file’s structure is shown in VS Code</figcaption></figure><p>I have found this <a href="https://circleci.com/blog/what-is-yaml-a-beginner-s-guide/">YAML beginner’s guide</a> by Alek Sharma to be useful and brief, feel free to check it out.</p><h3>Required Fields in a Kubernetes YAML file</h3><p>A YAML file that defines a Kubernetes object must define the following four sections:</p><ul><li><strong>apiVersion</strong> - Which version of the Kubernetes API you’re using to create this object. In <em>backend-pod.yaml</em> file <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-pod.yaml#L1">line 1</a> this is defined as “v1”.</li><li><strong>kind</strong> - What kind of object you want to create. In <em>backend-pod.yaml</em> file <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-pod.yaml#L2">line 2</a> we specify the kind is a Pod.</li><li><strong>metadata</strong> - Data that helps uniquely identify the object. In <em>backend-pod.yaml</em> <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-pod.yaml#L3-L7">lines 3–7</a> we gave the Pod a name and a couple of labels.</li><li><strong>spec </strong>-<strong> </strong>What state you desire for the object. In <em>backend-pod.yaml</em> file <a href="https://github.com/oshokry/FibonacciSample/blob/master/K8/backend-pod.yaml#L8-L11">lines 8–11</a> we specified that the Pod would have one container and specified the name and the image for that container.</li></ul><h3>Create the REST API Pod</h3><p>Make sure you are still in the directory <em>FibonacciSample/K8</em>. Run the following command to create the Pod using the specification in the <em>backend-pod.yaml</em> YAML file:</p><pre>$ kubectl apply -f backend-pod.yaml<br>pod/fibonacci-backend-pod created</pre><p>A Pod has just been created that can compute the Fibonacci value for a number. The Fibonacci function is exposed as a REST API. To confirm that the Pod is in a Running state, run the following command to get a list of available Pods:</p><pre>$ kubectl get pod<br>NAME                    READY   STATUS    RESTARTS      AGE<br>fibonacci-backend-pod   1/1     Running   1 (30h ago)   42h</pre><p>The Pod is in a Running state and the REST API is available. The server is not exposed though, so we need to login to the server’s container and test the REST API using the curl utility. Run the following command to access the bash shell of the container:</p><pre>$ kubectl exec -it fibonacci-backend-pod -- bash<br>root@fibonacci-backend-pod:/#</pre><p>Note that the prompt shows the name of the Pod and that you are logged in using root which is the default user in a container instance. Furthermore, please note that the <strong>hostname </strong>has the same value as the Pod name. You can verify this using the hostname command:</p><pre>root@fibonacci-backend-pod:/# hostname<br>fibonacci-backend-pod</pre><p>Now test the REST API using the <em>curl </em>utility. Let’s try to get Fibonacci value for 8, which should come as 21:</p><pre>root@fibonacci-backend-pod:/# curl localhost:5000/fibonacci?n=8<br>Fibonacci v1.0&lt;br&gt;Hello from &lt;b&gt;fibonacci-backend-pod&lt;/b&gt;&lt;br&gt;Fibonnacci of 8 is &lt;b&gt;21&lt;/b&gt;root@fibonacci-backend-pod:/#</pre><p>Type <strong>exit </strong>to return to the bash shell of the host machine.</p><h3>Expose the Pod on the host machine</h3><p>We want to be able to reach the REST API from within the host machine. Run the following command to expose the Pod on the Kubernetes host machine:</p><pre>$ kubectl expose pod fibonacci-backend-pod --port 5000 --type NodePort<br>service/fibonacci-backend-pod exposed</pre><p>Let’s make sense of the above command:</p><ul><li><em>kubectl expose pod fibonacci-backend-pod</em>: Specify the name of the Pod that we want to expose.</li><li><em>--port 5000</em>: We know that a <a href="https://palletsprojects.com/p/flask/">Flask</a> Server serves requests at port <em>5000 </em>by default, so that is the port that we want to expose.</li><li><em>--type NodePort</em>: Create a service that will expose the Pod on the host machine of the Kubernetes Node that hosts the Pod.</li></ul><p>We will talk more about Kubernetes services in <a href="https://medium.com/@oshokry1/improve-application-scalability-and-fault-tolerance-using-kubernetes-replicasets-and-services-5d8b71d945fc">Part 4</a>. For now it is sufficient to know that a service type of <em>NodePort </em>is what we need here.</p><p>Let’s list the available services to identify which port on the host is mapped to the Pod’s port <em>5000</em>:</p><pre>$ kubectl get svc<br>NAME                    TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)         AGE<br>fibonacci-backend-pod   NodePort    10.102.87.196   &lt;none&gt;        5000:31042/TCP   32s<br>kubernetes              ClusterIP   10.96.0.1       &lt;none&gt;        443/TCP         10d</pre><p>A service named <em>fibonacci-backend-pod</em> has been created. Notice under PORT(S) we have <em>5000:31042/TCP</em>. This tells us that the REST API is exposed on port <em>31042</em> on the host machine. Now you can open a browser on the host machine and invoke the REST API. Let’s figure the Fibonacci value for 30. Launch this URL in your web browser:</p><p><a href="http://localhost:31042/fibonacci?n=30">http://localhost:31042/fibonacci?n=30</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*eTIqnb0adJ_c7djhcbXjdA.png" /><figcaption>Figuring the Fibonacci of 30</figcaption></figure><p>The REST API server is up and running.</p><h3>What’s Next?</h3><p>In this part, you created a Pod that exposes a REST API and made the API accessible from your host machine.</p><p>In <a href="https://medium.com/@oshokry1/create-a-highly-available-rest-api-server-using-kubernetes-replicaset-336d649741ad">Part 4</a>, you will make the REST API server highly available by running multiple Pods of it in a Kubernetes <em>ReplicaSet</em>.</p><blockquote>Want to learn Docker and Kubernetes in 3 hours? Sign up to my course on Udemy now. Click this link → <a href="https://www.udemy.com/course/build-scalable-applications-using-docker-and-kubernetes/?referralCode=9650B00C60B732B30533"><strong>Build Scalable Applications using Docker and Kubernetes</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d24c73d032c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Introduction to Kubernetes]]></title>
            <link>https://medium.com/@oshokry1/a-practical-introduction-to-kubernetes-2390682c6139?source=rss-e061736faabe------2</link>
            <guid isPermaLink="false">https://medium.com/p/2390682c6139</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[container-images]]></category>
            <dc:creator><![CDATA[Ossama Shokry]]></dc:creator>
            <pubDate>Tue, 07 Feb 2023 00:28:15 GMT</pubDate>
            <atom:updated>2024-04-05T19:21:08.204Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to this practical, hands-on introduction to Kubernetes. In this multi-part series, you will start by having a brief overview about Containers and Docker. You will then learn Kubernetes concepts, and what features it adds on top of a container runtimes such as Docker. You will do several hands-on labs to explore Kubernetes concepts, such as Pods, ReplicaSets, and Deployments. Let’s get started.</p><blockquote>Want to learn Docker and Kubernetes in 3 hours? Sign up to my course on Udemy now. Click this link → <a href="https://www.udemy.com/course/build-scalable-applications-using-docker-and-kubernetes/?referralCode=9650B00C60B732B30533"><strong>Build Scalable Applications using Docker and Kubernetes</strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*2NpPWMJLEesGUqnI5jvT3w.png" /><figcaption>The K8 Wheel</figcaption></figure><h3>Recap of Docker and Containers</h3><p>Docker is a container runtime platform that enables you to create container images, share them on a Registry, and create running containers based on the container images.</p><p>A Container is a sandbox process on your machine that is isolated from all other processes on the host machine. It has its own file system with all needed software and dependencies to run your application. A container even has its own IP address. This isolation is possible using features in the OS kernel.</p><p>A Container Image is the template that you can use to create a container. Think of it as a binary file that includes all the needed software, dependencies, and configurations that are needed to run a container instance.</p><p>Containers are lightweight compared to VMs(Virtual Machines). This is because containers do not have the overhead of the guest OS that comes with VMs. A container is just a process running on your host machine, sharing your OS kernel with other containers. Therefore, a container has a much smaller storage and CPU footprint, which allows you to run 10s of containers on a single host compared to a few VMs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*wfoK380q1PcE3TZO6pHi4A.png" /><figcaption>Containers vs VMs - <a href="https://www.docker.com/resources/what-container/">Source</a></figcaption></figure><p>For more information on Docker and containers, please refer to my series <a href="https://medium.com/@oshokry1/list/yaitd-yet-another-introduction-to-docker-a9bfb6ef9c50">YAITD: Yet Another Introduction to Docker</a>. I recommend going through <a href="https://medium.com/@oshokry1/what-is-docker-and-how-it-can-help-you-5b9f165c18b2">Part1</a>(concept overview) and <a href="https://medium.com/@oshokry1/hello-world-docker-edition-183f34296fbf">Part2</a>(Hello, World!) of the series to get a good overview about Docker and Containers. Feel free to finish the 7 parts Docker series if you wish, but doing so is not a pre-requisite to this series.</p><h3>Enter Kubernetes</h3><p>The name Kubernetes originates from Greek, meaning helmsman or pilot. Kubernetes is usually abbreviated as K8s. K8s as an abbreviation results from counting the eight letters between the “K” and the “s”.</p><p>Kubernetes helps you manage your containerized workloads. We will see what that means in a moment, but let’s first start with an example application.</p><p>Let’s assume you have a three-tier application composed of a WebApp front end tier, a Controller middle tier, and a Backend tier. Each tier is containerized in its own container image. To improve the scalability of your application and to better utilize your infrastructure, you will want to have multiple running containers from each tier:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a6aAadzvZcbZu9D9L81zOg.png" /><figcaption>A Multi Tier Application with several Containers at each tier</figcaption></figure><p>The need arises for a system that supports the following features:</p><p>1. Scale up or scale down your application according to incoming traffic. Preferably scaling the number of running containers in each tier independently from other tiers.</p><p>2. Load balance requests to each tier among its containers.</p><p>3. Keep an eye on the health of containers. If a container crashes, start a new one.</p><p>4. Roll out new versions of containers with minimal downtime.</p><p>5. Roll back containers to a previous version.</p><p>6. Make your application highly available through horizontal scaling (running multiple containers on multiple infrastructure nodes).</p><p>Kubernetes provides all the above features to you and then some. Let’s explore some of these features in Kubernetes.</p><h4>Pod</h4><p>A <a href="https://kubernetes.io/docs/concepts/workloads/pods/">Pod</a> is the smallest deployable unit of computing that you can create and manage in Kubernetes. A Pod encapsulates one or more containers, with shared storage and network resources, and a specification for how to run containers.</p><p>Most of the time you will have one container per Pod. However, there are use cases where it makes sense for a Pod to run multiple containers. For example, you might have a container that acts as a web server for files in a shared volume, and a separate “sidecar” container that updates those files from a remote source, as in the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*LyI8WE71Gzhzic6V8ySYhw.png" /><figcaption>A Multi-Container Pod - <a href="https://kubernetes.io/docs/concepts/workloads/pods/#how-pods-manage-multiple-containers">Source</a></figcaption></figure><h4>Node</h4><p>Kubernetes runs your workload by placing containers into Pods to run on <a href="https://kubernetes.io/docs/concepts/architecture/nodes/">Nodes</a>. A Kubernetes setup contains one or more nodes and is called a cluster. A node may be a virtual or physical machine, depending on the cluster. A node will have a container runtime, such as Docker, to run your containers.</p><p>Typically, you have several nodes in a cluster; in a learning or resource-limited environment, you might have only one node. There are two types of nodes:</p><p>1. <strong>Worker Node</strong>: this node hosts the Pods that are the components of the application workload.</p><p>2. <strong>Control Plane</strong>: this node manages the Worker Nodes and the Pods in the cluster.</p><p>Here is a simplified overview of what the Kubernetes cluster does when you instruct it to run a Pod:</p><p>1. You issue a command to deploy a Pod, say one Pod of the hello-world container. The command can be issued using Kubernetes’s <a href="https://kubernetes.io/docs/reference/kubectl/"><em>kubectl</em></a> command line tool.</p><p>2. The <em>kubectl</em> tool invokes the <strong>API Server</strong> on the Control Plane node, telling it to “Please run one Pod with these given specs: one container of the hello-world container image”.</p><p>3. The API Server on the Control Plane communicates with a worker node via its <a href="https://kubernetes.io/docs/reference/command-line-tools-reference/kubelet/"><strong>kubelet</strong></a>, asking it to launch the said Pod.</p><p>4. The kubelet, which is an agent that runs on each worker node, creates the Pod on that node with the given Specs.</p><p>Going back to our three-tier application, assume you want Kubernetes to deploy 7 Pods of the WebApp, 4 Pods of the Controller, and 3 Pods of the Backend. The Control Plane node’s API Server will communicate with each Worker Node via its kubelet to create the Pods. It will make sure you always have the specified number of Pods from each tier, and it will distribute them across multiple nodes to insure fault tolerance and high availability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*gRTE17uPuQA4DWfeMjJ9yA.png" /><figcaption>Kubernetes Cluster with Control Plane node and multiple Worker nodes</figcaption></figure><p>The above explanation is simplified. For more information on how a Kubernetes Cluster works, refer to <a href="https://kubernetes.io/docs/concepts/overview/components/">Kubernetes Components</a> from the official Kubernetes documentation.</p><h4>ReplicaSet</h4><p>A <a href="https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/">ReplicaSet</a> is the Kubernetes resource that you can use to insure you have a set number of Pods running at any given time. For example, you can have three ReplicaSets to insure you always have 7 Pods of the WebApp, 4 Pods of the Controller, and 3 Pods of the Backend:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*ApMt2-VhXOyZT_tDR2i2wA.png" /><figcaption>Using ReplicaSets to scale applications horizontally</figcaption></figure><p>If a Pod would crash, the respective ReplicaSet will replace it with a new Pod. Furthermore, you can scale out or scale in a ReplicaSet as needed. Say, you have a higher load expected during a sale event coming to your WebApp Pods and the current 7 Pods will not be enough. You can scale the WebApp ReplicaSet out to have 15 Pods. Then after the sale event s over you can scale it back in to 7 Pods.</p><h4>Deployment</h4><p>A <a href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/">Deployment</a> is a Kubernetes resource that owns a ReplicaSet and provides more features on top of it. An important feature of the Deployment is the <em>Deployment Strategy</em>, where you declare what happens when you deploy a new version of your application. Let’s say you currently have v1 deployed and you would like to deploy v2 gradually, meaning upgrading one Pod at a time from v1 to v2 to avoid service downtime. A Deployment with its Deployment Strategy set to <em>RollingUpdate</em> can do just that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Y973en4PiYK1lnMoGoLFpQ.png" /><figcaption>A Kubernetes Deployment performing a RollingUpdate from V1 to V2</figcaption></figure><p>Like the ReplicaSet, you can also scale out or scale in a Deployment to change the number of Pods in it up or down respectively. Furthermore, a Deployment provides you with more features, such as:</p><p>1. Monitor the status of a Deployment while the updates take place. E.g., monitor your Pods while they flip from V1 to V2 one by one.</p><p>2. Pause or Resume an ongoing Deployment.</p><p>3. See a history of revisions of a Deployment.</p><p>4. Rollback a Deployment to a previous revision.</p><p>Given that a Deployment owns a ReplicaSet and adds more features, it is recommended to use a Deployment instead of a ReplicaSet.</p><h4>Service</h4><p>A Kubernetes <a href="https://kubernetes.io/docs/concepts/services-networking/service/">Service</a> exposes a set of Pods as a single end point. While Kubernetes gives each Pod its own IP address, a service provides a single DNS name for all the Pods behind it. A client invokes the service, and the service forwards the request to several Pods and load balances the requests among the Pods. Going back to our three tier application, each tier’s set of Pods can be exposed using a service:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEYtOA2jP9yw1IQuNQThBw.png" /><figcaption>Kubernetes Services Load Balance requests to Pods</figcaption></figure><h3>What’s Next?</h3><p>In this part, you started with a brief overview about Containers and Docker. You then went through Kubernetes concepts, and explored several of Kubernetes’s constructs such as Pods, ReplicaSets, and Deployments.</p><p>In <a href="https://medium.com/@oshokry1/install-kubernetes-on-your-machine-and-run-a-hello-world-pod-6aa378a51e81">Part 2</a>, you will install Kubernetes on your machine and have a hands-on lab about Kubernetes Pods.</p><blockquote>Want to learn Docker and Kubernetes in 3 hours? Sign up to my course on Udemy now. Click this link → <a href="https://www.udemy.com/course/build-scalable-applications-using-docker-and-kubernetes/?referralCode=9650B00C60B732B30533"><strong>Build Scalable Applications using Docker and Kubernetes</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2390682c6139" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>