<?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 Augustas Berneckas on Medium]]></title>
        <description><![CDATA[Stories by Augustas Berneckas on Medium]]></description>
        <link>https://medium.com/@augustasberneckas?source=rss-17b8ec428343------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KtvojSSgORoV1g8b.</url>
            <title>Stories by Augustas Berneckas on Medium</title>
            <link>https://medium.com/@augustasberneckas?source=rss-17b8ec428343------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:08:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@augustasberneckas/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[Migrate Kubernetes from Docker to Containerd]]></title>
            <link>https://medium.com/analytics-vidhya/migrate-kubernetes-from-docker-to-containerd-2fba80779280?source=rss-17b8ec428343------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fba80779280</guid>
            <category><![CDATA[kubenetes]]></category>
            <category><![CDATA[containerd]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubeadm]]></category>
            <dc:creator><![CDATA[Augustas Berneckas]]></dc:creator>
            <pubDate>Mon, 03 May 2021 14:31:16 GMT</pubDate>
            <atom:updated>2021-11-10T04:39:06.825Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5XF6kThbwT7uvPt2b7xKw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ventiviews?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Cameron Venti</a> on <a href="https://unsplash.com/s/photos/shipping-container?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>As most of you probably know, Kubernetes decided to deprecate Docker as container runtime after <strong>v1.20</strong></p><p>Explanation of why Kubernetes decided to deprecate Docker can be found here: <a href="https://kubernetes.io/blog/2020/12/02/dont-panic-kubernetes-and-docker/">https://kubernetes.io/blog/2020/12/02/dont-panic-kubernetes-and-docker/</a></p><p>What that means for us, end-users is that one way or another we will have to migrate to another container runtime. There are several container runtime interfaces, but probably well known are:</p><ul><li><a href="https://github.com/containerd">containerd</a></li><li><a href="https://cri-o.io/">cri-o</a></li></ul><p>In this post, we are going to migrate Kubernetes cluster from Docker to Containerd. These changes will apply to all nodes in the cluster. I recommend starting migrating from worker nodes.</p><p>I will migrate my playground cluster which has 3 masters and 3 workers nodes with Docker as a runtime</p><pre>NAME           STATUS   ROLES                  AGE   VERSION   INTERNAL-IP    EXTERNAL-IP   OS-IMAGE             KERNEL-VERSION     CONTAINER-RUNTIME<br>k8s-master-1   Ready    control-plane,master   xxd   v1.20.6   xxx.xxx.x.xx   &lt;none&gt;        Ubuntu 20.04.x LTS   x.x.x-xx-generic   docker://19.03.6<br>k8s-master-2   Ready    control-plane,master   xxd   v1.20.6   xxx.xxx.x.xx   &lt;none&gt;        Ubuntu 20.04.x LTS   x.x.x-xx-generic   docker://19.03.6<br>k8s-master-3   Ready    control-plane,master   xxd   v1.20.6   xxx.xxx.x.xx   &lt;none&gt;        Ubuntu 20.04.x LTS   x.x.x-xx-generic   docker://19.03.6<br>k8s-worker-1   Ready    worker                 xxd   v1.20.6   xxx.xxx.x.xx   &lt;none&gt;        Ubuntu 20.04.x LTS   x.x.x-xx-generic   docker://19.03.6<br>k8s-worker-2   Ready    worker                 xxd   v1.20.6   xxx.xxx.x.xx   &lt;none&gt;        Ubuntu 20.04.x LTS   x.x.x-xx-generic   docker://19.03.6<br>k8s-worker-3   Ready    worker                 xxd   v1.20.6   xxx.xxx.x.xx   &lt;none&gt;        Ubuntu 20.04.x LTS   x.x.x-xx-generic   docker://19.03.6</pre><h3>Prepare node</h3><p>First of all, scheduling must be disabled and all unnecessary workloads, except daemon sets, must be evicted.</p><p>Start by cordoning the node</p><pre>kubectl cordon k8s-worker-3<br>node/k8s-worker-3 cordoned</pre><p>Drain node</p><pre>kubectl drain k8s-worker-3 --ignore-daemonsets --delete-emptydir-data<br>node/k8s-worker-3 already cordoned<br>&lt;...&gt;<br>node/k8s-worker-3 evicted</pre><p>Stop Kubelet and docker</p><pre>systemctl stop kubelet<br>systemctl stop docker</pre><h3>Switch to containerd</h3><p>Node is ready to be migrated to containerd. Start by removing docker as it will not be needed anymore</p><pre>apt purge docker-ce docker-ce-cli</pre><p>Ensure containerd is installed:</p><pre>ctr -n moby container list</pre><p>Ensure that config file for containerd in /etc/containerd/config.toml is present. You can generate it with</p><pre>sudo mkdir -p /etc/containerd<br>containerd config default | sudo tee /etc/containerd/config.toml</pre><p>If you are using the systemd as a cgroup driver, you must configure it in containerd config. In /etc/containerd/config.toml Add</p><pre>&lt;...&gt;<br>[plugins.&quot;io.containerd.grpc.v1.cri&quot;.containerd.runtimes.runc]<br>  &lt;...&gt;<br>  [plugins.&quot;io.containerd.grpc.v1.cri&quot;.containerd.runtimes.runc.options]<br>    SystemdCgroup = true # &lt;--- This line<br>&lt;...&gt;</pre><p>Restart containerd</p><pre>systemctl restart containerd</pre><p>Edit /var/lib/kubelet/kubeadm-flags.env file by adding container runtime flags</p><ul><li>--container-runtime=remote</li><li>--container-runtime-endpoint=unix:///run/containerd/containerd.sock</li></ul><p>kubeadm-flags.env file should now look something like this:</p><pre>cat /var/lib/kubelet/kubeadm-flags.env <br>KUBELET_KUBEADM_ARGS=&quot;--network-plugin=cni --pod-infra-container-image=k8s.gcr.io/pause:3.2 --container-runtime=remote --container-runtime-endpoint=unix:///run/containerd/containerd.sock&quot;</pre><p>Start Kubelet</p><pre>systemctl start kubelet</pre><p>Check cluster status</p><pre>NAME           STATUS                      ROLES                  AGE   VERSION   INTERNAL-IP    EXTERNAL-IP   OS-IMAGE             KERNEL-VERSION     CONTAINER-RUNTIME<br>k8s-master-1   Ready                       control-plane,master   xxd   v1.20.6   xxx.xxx.x.xx   &lt;none&gt;        Ubuntu 20.04.x LTS   x.x.x-xx-generic   docker://19.03.6<br>k8s-master-2   Ready                       control-plane,master   xxd   v1.20.6   xxx.xxx.x.xx   &lt;none&gt;        Ubuntu 20.04.x LTS   x.x.x-xx-generic   docker://19.03.6<br>k8s-master-3   Ready                       control-plane,master   xxd   v1.20.6   xxx.xxx.x.xx   &lt;none&gt;        Ubuntu 20.04.x LTS   x.x.x-xx-generic   docker://19.03.6<br>k8s-worker-1   Ready                       worker                 xxd   v1.20.6   xxx.xxx.x.xx   &lt;none&gt;        Ubuntu 20.04.x LTS   x.x.x-xx-generic   docker://19.03.6<br>k8s-worker-2   Ready                       worker                 xxd   v1.20.6   xxx.xxx.x.xx   &lt;none&gt;        Ubuntu 20.04.x LTS   x.x.x-xx-generic   docker://19.03.6<br>k8s-worker-3   Ready,SchedulingDisabled    worker                 xxd   v1.20.6   xxx.xxx.x.xx   &lt;none&gt;        Ubuntu 20.04.x LTS   x.x.x-xx-generic   containerd://1.4.4</pre><p>As you can see, the worker started using containerd as its&#39; runtime. Check if daemonsets are running without issues. Uncordon the node if everything looks good</p><pre>kubectl uncordon k8s-worker-3</pre><p>Repeat the procedure for all nodes (one by one)</p><h3>Post-migration</h3><p>Congratulations on migrating your cluster to containerd. However, few things left to do to be fully migrated. Let&#39;s free up some space by removing docker-related folders. They will not be needed anymore</p><pre>rm -r /etc/docker<br>rm -r /var/lib/docker<br>rm -r /var/lib/dockershim</pre><p>If you are using kubeadm to manage your cluster initialization, joins, and updates, you might want to re-annotate nodes, so kubeadm will not get confused on your next update whether you are using docker or containterd as a runtime:</p><pre>kubectl annotate node k8s-worker-3 --overwrite kubeadm.alpha.kubernetes.io/cri-socket=unix:///run/containerd/containerd.sock</pre><p>Note that removals and annotate must be executed on all nodes after the whole cluster will be migrated to containerd and ensured that the migration was successful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fba80779280" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/migrate-kubernetes-from-docker-to-containerd-2fba80779280">Migrate Kubernetes from Docker to Containerd</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write helm charts for python flask app]]></title>
            <link>https://augustasberneckas.medium.com/write-helm-charts-for-python-flask-app-ee2777fb458c?source=rss-17b8ec428343------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee2777fb458c</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[helm]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[minikube]]></category>
            <dc:creator><![CDATA[Augustas Berneckas]]></dc:creator>
            <pubDate>Tue, 27 Apr 2021 10:35:06 GMT</pubDate>
            <atom:updated>2021-04-27T10:35:06.811Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is part of the series <a href="https://augustasberneckas.medium.com/prepare-and-deploy-python-app-to-kubernetes-736b13fe4cef"><strong>Prepare and Deploy python app to Kubernetes</strong></a></p><p><a href="https://augustasberneckas.medium.com/write-kubernetes-manifests-for-python-flask-app-aa9e3bee710b">👈 Previous post: Write Kubernetes manifests for python flask app</a></p><p>At the end of this series, we will have a fully working flask app in Kubernetes. The app itself that we are using, can be found here: <a href="https://github.com/brnck/k8s-python-demo-app/tree/manifests">https://github.com/brnck/k8s-python-demo-app/tree/manifests</a></p><h3>Prerequisites</h3><p>We are using minikube to deploy our application to Kubernetes. If you are not familiar with it, head over to <a href="https://augustasberneckas.medium.com/getting-to-know-minikube-e93f9676dea7">this post</a> to learn more, as we are going to cover topics such as how to use Minikube here.</p><h3>Moving forward</h3><p>Until this moment, we have containerized the application, write Kubernetes manifests and deployed it to the Minikube cluster. As time goes by, we decide to deploy our application Kubernetes production cluster and even maybe to the staging cluster as well. Every cluster (Minikube, staging, production) is a little different in terms of resources and load that it needs to be able to process. For example, you want to deploy only one web pod to your Minikube and staging clusters, but it must be scaled to 10 in production. Also, Gunicorn must boot up 10 workers instead of 2.</p><p>You have probably noticed that all these changes will require modifying Kubernetes manifests hence three different versions of manifests must be maintained. That is where templating comes in. It can change the values to placeholders and replace them with your provided values when you deploy the application. Some known tools are:</p><ul><li><a href="https://helm.sh/">Helm</a></li><li><a href="https://kustomize.io/">Kustomize</a></li></ul><p>We are going to concentrate on helm here.</p><h3>What is helm?</h3><p>While helm positions itself as a package manager and indeed, <strong>Redis</strong>, S<strong>entry</strong>, <strong>etc.</strong> environments are usually only one helm install &lt;...&gt; command away, it is also a very neat tool when it comes to deploying your own application across different environments. Not only, helm templates your manifests, but it also helps with rollbacks. Bad code accidentally slipped to production? Execute helm rollback and you can calmly investigate issues without affecting your clients.</p><p>Whenever you are thinking about deploying some third-party service to Kubernetes, head over to the <a href="https://artifacthub.io/packages/search?kind=0">Helm charts hub</a> where you will definitely find <strong>helm-charts</strong> and instructions on how to deploy that service to Kubernetes.</p><p>We are not going to deploy 3rd party helm-charts on this post. Instead, we will write our own helm-charts. For more information on how to deploy public <strong>helm-charts</strong> check the <a href="https://helm.sh/docs/intro/quickstart/">Helm quickstart guide</a></p><h3>First things first</h3><p>Create a directory for helm-charts according to the <a href="https://helm.sh/docs/topics/charts/#the-chart-file-structure">Charts guide</a>. Note, that we are not going to use all the features that helm provides. Instead, we will create a basic chart to only fulfill our goal — deploy differently configured applications across environments. Start by creating initial files and folders:</p><pre>mkdir -p helm-charts/templates<br>touch helm-charts/Chart.yaml<br>touch helm-charts/values.yaml</pre><p>Add helm-charts directory to the .dockerignore file.</p><p>The templates directory is where we are going to put templated manifests. Helm will combine it with provided values in the values.yaml file and generate valid Kubernetes manifests. Chart.yaml acts as a metadata file. It stores information about helm-charts like <strong>name</strong>, <strong>version,</strong> and so on.</p><p>Finally, let’s copy files from k8s-manifests/ to helm-charts/templates/:</p><pre>cp -r k8s-manifests/ helm-charts/templates/</pre><p>At this moment, <strong>helm-charts</strong> directory should look like this:</p><pre>ls helm-charts/*<br>helm-charts/Chart.yaml helm-charts/values.yaml</pre><pre>helm-charts/templates:<br>deployment.yaml ingress.yaml    job.yaml        namespace.yaml  service.yaml</pre><h3>Chart.yaml file</h3><p>According to the <a href="https://helm.sh/docs/topics/charts/#the-chartyaml-file">documentation</a>, <strong>Chart.yaml</strong> is required for a chart. It must contain few required fields:</p><pre>apiVersion: The chart API version (required)<br>name: The name of the chart (required)<br>version: A SemVer 2 version (required)</pre><p><strong>apiVersion</strong> should be <em>v1</em> or <em>v2</em> depending on the Helm version. Since we are using <strong>helm 3</strong>, it should be <em>v2</em>. As for the name, we will name it <strong>python-demo-app</strong>. Every chart must have a <strong>version</strong> number. It might not be relevant if you are not going to publish your chart, however, it will be our first helm-charts version, we can set it to <em>1.0.0</em>.</p><p>This is how chart.yaml should look after the changes:</p><pre>apiVersion: v2<br>name: demo-python-app<br>version: 1.0.0</pre><h3>Templating the manifests</h3><p>Helm uses <a href="https://pkg.go.dev/text/template">Go templates</a> for templating resource files. If you are not familiar with it, I strongly recommend checking that out, otherwise, it might be hard to catch up with what we will be doing here.</p><p>As you might remember from the previous guide, namespace.yaml creates Kubernetes namespace for us. Luckily, Helm can create the namespace for us just by adding a flag for install or upgrade command:</p><pre>helm install --help | grep namespace<br>      --create-namespace             create the release namespace if not present<br>  -n, --namespace string            namespace scope for this request</pre><pre>helm upgrade --help | grep namespace<br>      --create-namespace             if --install is set, create the release namespace if not present<br>  -n, --namespace string            namespace scope for this request</pre><p>We can safely remove helm-charts/templates/namespace.yaml file:</p><pre>rm helm-charts/templates/namespace.yaml</pre><p>As for the other files… We are not going to template everything we can, as the main goal of this guide is to understand what helm is and what it does.</p><h3>Templating deployment.yaml</h3><p>Let’s start by defining what values we want to be able to change dynamically. I would like to:</p><ul><li>Use &lt;release_name&gt;-web as deployment resource <em>name</em>;</li><li>Provide <em>namespace</em> on deploy (passed through --namespace flag when installing/upgrading helm-chart);</li><li>Provide different <em>replicas</em> number;</li><li>Use &lt;release_name&gt;-web as container <em>name</em>;</li><li>Provide different image <em>name</em> and <em>tag</em>;</li><li>Provide different <em>args</em>;</li><li>Provide different resources (<em>requests</em> and <em>limits</em>) for the container.</li></ul><p>Start by changing hardcoded values to placeholders in the metadata key:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: {{ .Release.Name }}-web<br>  namespace: {{ .Release.Namespace }}<br>&lt;...&gt;</pre><p>Moving to .spec, let&#39;s make replicas configurable:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: {{ .Release.Name }}-web<br>  namespace: {{ .Release.Namespace }}<br>spec:<br>  replicas: {{ .Values.web.replicas }}</pre><p>You have probably noticed that .Release was used in the <em>metadata</em> while for the <em>replicas</em> we have used .Values. Both of these are built-in objects which <strong>Helm</strong> passes into a template. The difference between them is that the <strong>Release</strong> describes the release itself while <strong>Values</strong> are the values passed into the template from the values.yaml file. You can find more info about all the built-in objects <a href="https://helm.sh/docs/chart_template_guide/builtin_objects/">here</a></p><p>This is how the deployment file looks after all the values have been changes with placeholders:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: {{ .Release.Name }}-web<br>  namespace: {{ .Release.Namespace }}<br>spec:<br>  replicas: {{ .Values.web.replicas }}<br>  selector:<br>    matchLabels:<br>      app: python-demo-app<br>      role: web<br>  template:<br>    metadata:<br>      labels:<br>        app: python-demo-app<br>        role: web<br>    spec:<br>      securityContext:<br>        runAsGroup: 1000<br>        runAsUser: 1000<br>      containers:<br>        - name: {{ .Release.Name }}-web<br>          image: {{ .Values.web.image }}:{{ .Values.web.tag }}<br>          args:<br>          {{- range .Values.web.args }}<br>            - {{ quote . }}<br>          {{- end }}<br>          ports:<br>            - name: gunicorn<br>              containerPort: 8000<br>          resources: {{ toYaml .Values.web.resources | nindent 12 }}<br>          readinessProbe:<br>            initialDelaySeconds: 10<br>            httpGet:<br>              port: gunicorn<br>              path: /<br>          livenessProbe:<br>            initialDelaySeconds: 10<br>            exec:<br>              command:<br>                - /bin/sh<br>                - -c<br>                - &#39;pidof -x gunicorn&#39;</pre><p>This thing probably raised your eyebrow:</p><pre>args:<br>          {{- range .Values.web.args }}<br>            - {{ quote . }}<br>          {{- end }}</pre><p>It might look scary, but everything we do here is just iterating through .Values.web.args key and adding values to args array. The <em>quote</em> function wraps values in double-quotes.</p><p>Another thing that might be new for you is:</p><pre>resources: {{ toYaml .Values.web.resources | nindent 12 }}</pre><p>Basically, we are telling to convert the value, provided in .Values.web.resources to YAML and using another function (piping the output of the first function result to another function) to add new line to the beginning and indent every line by additional 12 spaces. You will soon see that in action. Let&#39;s add values to values.yaml:</p><pre>web:<br>  replicas: 2<br>  image: python-demo-app<br>  tag: init<br>  args:<br>    - &#39;--bind&#39;<br>    - &#39;0.0.0.0&#39;<br>    - &#39;app:app&#39;<br>  resources:<br>    requests:<br>      memory: 128Mi<br>      cpu: 100m<br>    limits:<br>      memory: 256Mi<br>      cpu: 200m</pre><p>We can generate the manifest without deploying to check if everything is okay:</p><pre>cd helm-charts<br>helm template -s templates/deployment.yaml --namespace namespace-to-be app-name .<br>---<br># Source: demo-python-app/templates/deployment.yaml<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: app-name-web<br>  namespace: namespace-to-be<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: python-demo-app<br>      role: web<br>  template:<br>    metadata:<br>      labels:<br>        app: python-demo-app<br>        role: web<br>    spec:<br>      securityContext:<br>        runAsGroup: 1000<br>        runAsUser: 1000<br>      containers:<br>        - name: app-name-web<br>          image: python-demo-app:init<br>          args:<br>            - &quot;--bind&quot;<br>            - &quot;0.0.0.0&quot;<br>            - &quot;app:app&quot;<br>          ports:<br>            - name: gunicorn<br>              containerPort: 8000<br>          resources: <br>            limits:<br>              cpu: 200m<br>              memory: 256Mi<br>            requests:<br>              cpu: 100m<br>              memory: 128Mi<br>          readinessProbe:<br>            initialDelaySeconds: 10<br>            httpGet:<br>              port: gunicorn<br>              path: /<br>          livenessProbe:<br>            initialDelaySeconds: 10<br>            exec:<br>              command:<br>                - /bin/sh<br>                - -c<br>                - &#39;pidof -x gunicorn&#39;</pre><p>Helm took our values.yaml file by default and generated deployment manifest with it. Let&#39;s create templates for the rest of the resources</p><h3>Templating job.yaml</h3><p>I am not going to dive deep into this one. As well as for deployment, let’s define what we want to do here:</p><ul><li>Use &lt;release_name&gt;-job as deployment resource <em>name</em>;</li><li>Provide <em>namespace</em> on deploy (passed through --namespace flag when installing/upgrading helm-chart);</li><li>Use &lt;release_name&gt;-job as container <em>name</em>;</li><li>Provide different image <em>name</em> and <em>tag</em>;</li><li>Provide different <em>command</em>;</li><li>Provide different <em>args</em>;</li><li>Provide different resources (<em>requests</em> and <em>limits</em>) for the container.</li></ul><p>Try to do that by yourself. Take deployment.yaml template as an example. I will share a solution as it almost the same:</p><pre>apiVersion: batch/v1<br>kind: Job<br>metadata:<br>  name: {{ .Release.Name }}-job<br>  namespace: {{ .Release.Namespace }}<br>spec:<br>  template:<br>    metadata:<br>      labels:<br>        app: python-demo-app<br>        role: hello-world-job<br>    spec:<br>      restartPolicy: Never<br>      securityContext:<br>        runAsGroup: 1000<br>        runAsUser: 1000<br>      containers:<br>        - name: {{ .Release.Name }}-job<br>          image: {{ .Values.job.image }}:{{ .Values.job.tag }}<br>          command:<br>          {{- range .Values.job.command }}<br>            - {{ quote . }}<br>          {{- end }}<br>          args:<br>          {{- range .Values.job.args }}<br>            - {{ quote . }}<br>          {{- end }}<br>          resources: {{ toYaml .Values.job.resources | nindent 12 }}</pre><p>After adding job values, our values.yaml file now looks like this:</p><pre>web:<br>  replicas: 2<br>  image: python-demo-app<br>  tag: init<br>  args:<br>    - &#39;--bind&#39;<br>    - &#39;0.0.0.0&#39;<br>    - &#39;app:app&#39;<br>  resources:<br>    requests:<br>      memory: 128Mi<br>      cpu: 100m<br>    limits:<br>      memory: 256Mi<br>      cpu: 200m</pre><pre>job:<br>  image: python-demo-app<br>  tag: init<br>  command:<br>    - python3<br>  args:<br>    - cli.py<br>  resources:<br>    requests:<br>      memory: 128Mi<br>      cpu: 100m<br>    limits:<br>      memory: 256Mi<br>      cpu: 200m</pre><p>Finally, the rendered job manifest looks like this:</p><pre>helm template -s templates/job.yaml --namespace namespace-to-be app-name .<br>---<br># Source: demo-python-app/templates/job.yaml<br>apiVersion: batch/v1<br>kind: Job<br>metadata:<br>  name: app-name-job<br>  namespace: namespace-to-be<br>spec:<br>  template:<br>    metadata:<br>      labels:<br>        app: python-demo-app<br>        role: hello-world-job<br>    spec:<br>      restartPolicy: Never<br>      securityContext:<br>        runAsGroup: 1000<br>        runAsUser: 1000<br>      containers:<br>        - name: app-name-job<br>          image: python-demo-app:init<br>          command:<br>            - &quot;python3&quot;<br>          args:<br>            - &quot;cli.py&quot;<br>          resources: <br>            limits:<br>              cpu: 200m<br>              memory: 256Mi<br>            requests:<br>              cpu: 100m<br>              memory: 128Mi</pre><h3>Templating service.yaml</h3><p>The application has only one service with only one port to forward traffic to so let’s not spend a lot of time here and only change .metadata.name and .metadata.namespace to the placeholders:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: {{ .Release.Name }}-web<br>  namespace: {{ .Release.Namespace }}<br>spec:<br>  selector:<br>    app: python-demo-app<br>    role: web<br>  ports:<br>    - name: http<br>      port: 80<br>      targetPort: gunicorn</pre><p>Check generated manifest:</p><pre>helm template -s templates/service.yaml --namespace namespace-to-be app-name .<br>---<br># Source: demo-python-app/templates/service.yaml<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: app-name-web<br>  namespace: namespace-to-be<br>spec:<br>  selector:<br>    app: python-demo-app<br>    role: web<br>  ports:<br>    - name: http<br>      port: 80<br>      targetPort: gunicorn</pre><h3>Templating ingress.yaml</h3><p>As for all resources, change .metadata.name and .metadata.namespace to the placeholders. We can also support multiple hosts for this application. To do that, multiple rules must be supported therefore .spec.rules value must be wrapped to {{- range .Values.ingress.rules }}. Also, service name should be templated according to the name in the service.yaml template:</p><pre>apiVersion: networking.k8s.io/v1beta1<br>kind: Ingress<br>metadata:<br>  name: {{ .Release.Name }}-web<br>  namespace: {{ .Release.Namespace }}<br>spec:<br>  rules:<br>  {{- range .Values.ingress.rules }}<br>    - host: {{ .host }}<br>      http:<br>        paths:<br>          - path: /<br>            pathType: Prefix<br>            backend:<br>              serviceName: {{ $.Release.Name }}-web<br>              servicePort: http<br>  {{- end }}</pre><p>Let’s add ingress key to the values.yaml file:</p><pre>ingress:<br>  rules:<br>    - host: python-app.demo.com<br>    - host: second-host-python-app.demo.com</pre><p>Test how helm generates manifest:</p><pre>helm template -s templates/ingress.yaml --namespace namespace-to-be app-name .<br>---<br># Source: demo-python-app/templates/ingress.yaml<br>apiVersion: networking.k8s.io/v1beta1<br>kind: Ingress<br>metadata:<br>  name: app-name-web<br>  namespace: namespace-to-be<br>spec:<br>  rules:<br>    - host: python-app.demo.com<br>      http:<br>        paths:<br>          - path: /<br>            pathType: Prefix<br>            backend:<br>              serviceName: app-name-web<br>              servicePort: http<br>    - host: second-host-python-app.demo.com<br>      http:<br>        paths:<br>          - path: /<br>            pathType: Prefix<br>            backend:<br>              serviceName: app-name-web<br>              servicePort: http</pre><p>All templates are now ready. Final values.yaml look like this:</p><pre>web:<br>  replicas: 2<br>  image: python-demo-app<br>  tag: init<br>  args:<br>    - &#39;--bind&#39;<br>    - &#39;0.0.0.0&#39;<br>    - &#39;app:app&#39;<br>  resources:<br>    requests:<br>      memory: 128Mi<br>      cpu: 100m<br>    limits:<br>      memory: 256Mi<br>      cpu: 200m</pre><pre>job:<br>  image: python-demo-app<br>  tag: init<br>  command:<br>    - python3<br>  args:<br>    - cli.py<br>  resources:<br>    requests:<br>      memory: 128Mi<br>      cpu: 100m<br>    limits:<br>      memory: 256Mi<br>      cpu: 200m</pre><pre>ingress:<br>  rules:<br>    - host: python-app.demo.com<br>    - host: second-host-python-app.demo.com</pre><h3>Deploy helm-charts</h3><p>Start Minikube cluster:</p><pre>minikube start --driver=virtualbox --kubernetes-version=1.20.5 --addons ingress<br>&lt;...&gt;<br>🏄  Done! kubectl is now configured to use &quot;minikube&quot; cluster and &quot;default&quot; namespace by default</pre><p>We are not using any public nor private docker registry, so let’s build image in the Minikube virtual machine. Make sure you are in the root directory of you application:</p><pre>eval $(minikube docker-env)<br>docker build -t python-demo-app:init .<br>minikube ssh docker images | grep python-demo-app<br>python-demo-app                           init         c18672872873   About a minute ago   125MB</pre><p>Deploy helm-charts to Kubernetes:</p><pre>helm upgrade --install --create-namespace --namespace python-demo-app demo-app helm-charts/<br>Release &quot;demo-app&quot; does not exist. Installing it now.<br>W0426 20:50:05.625960   70845 warnings.go:70] networking.k8s.io/v1beta1 Ingress is deprecated in v1.19+, unavailable in v1.22+; use networking.k8s.io/v1 Ingress<br>W0426 20:50:05.721498   70845 warnings.go:70] networking.k8s.io/v1beta1 Ingress is deprecated in v1.19+, unavailable in v1.22+; use networking.k8s.io/v1 Ingress<br>NAME: demo-app<br>LAST DEPLOYED: Mon Apr 26 20:50:05 2021<br>NAMESPACE: python-demo-app<br>STATUS: deployed<br>REVISION: 1<br>TEST SUITE: None</pre><p>We have already covered why we are using old apiVersion of the Ingress in the previous guide. As for the command, let&#39;s breakdown it into parts. You have probably noticed that I am using upgrade instead of install, but I am using it with the --install flag which tells helm to upgrade or install release if it does not exist. It is one command to rule them all. --create-namespace - well, creates namespace if it does not exist. Next, I am passing the namespace name, release name, and charts folder. Additionally, we could add --file helm-charts/values.yaml to explicitly tell helm to that file for values. Luckily, helm does that by default. Let&#39;s check how Helm deployment went:</p><pre>helm list --namespace python-demo-app<br>NAME    	NAMESPACE      	REVISION	UPDATED                              	STATUS  	CHART                	APP VERSION<br>demo-app	python-demo-app	1       	2021-04-26 20:50:05.446109 +0300 EEST	deployed	demo-python-app-1.0.0</pre><p>Helm itself deployed successfully. How about all the resources:</p><pre>kubectl get pods,jobs,service,ingress -n python-demo-app<br>NAME                               READY   STATUS      RESTARTS   AGE<br>pod/demo-app-job-cttcx             0/1     Completed   0          6m58s<br>pod/demo-app-web-5d64656cd-g8d9d   1/1     Running     0          6m58s<br>pod/demo-app-web-5d64656cd-s6qg4   1/1     Running     0          6m58s</pre><pre>NAME                     COMPLETIONS   DURATION   AGE<br>job.batch/demo-app-job   1/1           3s         6m58s</pre><pre>NAME                   TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE<br>service/demo-app-web   ClusterIP   10.105.213.47   &lt;none&gt;        80/TCP    6m58s</pre><pre>NAME                                     CLASS    HOSTS                                                 ADDRESS   PORTS   AGE<br>ingress.networking.k8s.io/demo-app-web   &lt;none&gt;   python-app.demo.com,second-host-python-app.demo.com             80      6m58s</pre><p>It’s running without any issues. Let’s try to access our app using both hosts:</p><pre>curl -H &quot;Host: python-app.demo.com&quot; $(minikube ip)/<br>Hello, World!<br>curl -H &quot;Host: second-host-python-app.demo.com&quot; $(minikube ip)/<br>Hello, World!</pre><h3>Deploy another application using the same charts</h3><p>Imagine we are now deploying our app to the staging cluster. Simulate different deployment by deploying 4 web replicas, with each requesting cpu: 200m and memory: 256Mi. Also, each web server must boot up 6 Gunicorn workers. The application should use staging-app.demo.com as its&#39; ingress host. Finally, the application must be deployed to staging-python-app namespace.</p><p>We will start by copying our values.yaml so we could modify it:</p><pre>cp helm-charts/values.yaml helm-charts/staging.yaml</pre><p>Let’s clear up some values and modify others according to our requirements. The final staging.yaml file should look like this:</p><pre>web:<br>  replicas: 4<br>  args:<br>    - &#39;--bind&#39;<br>    - &#39;0.0.0.0&#39;<br>    - &#39;--workers&#39;<br>    - &#39;6&#39;<br>    - &#39;app:app&#39;<br>  resources:<br>    requests:<br>      memory: 256Mi<br>      cpu: 200m<br>    limits:<br>      memory: 256Mi<br>      cpu: 200m</pre><pre>ingress:<br>  rules:<br>    - host: staging-app.demo.com</pre><p>Some values that are present in the values.yaml are missing here. Ignore it for now. I will get back to it. Let&#39;s deploy the application using staging.yaml file:</p><pre>helm upgrade --install --create-namespace \<br>  --namespace staging-python-app \<br>  -f helm-charts/staging.yaml \<br>  staging-python-app \<br>  helm-charts/<br>Release &quot;staging-python-app&quot; does not exist. Installing it now.<br>W0426 21:15:06.059332   72411 warnings.go:70] networking.k8s.io/v1beta1 Ingress is deprecated in v1.19+, unavailable in v1.22+; use networking.k8s.io/v1 Ingress<br>W0426 21:15:06.255467   72411 warnings.go:70] networking.k8s.io/v1beta1 Ingress is deprecated in v1.19+, unavailable in v1.22+; use networking.k8s.io/v1 Ingress<br>NAME: staging-python-app<br>LAST DEPLOYED: Mon Apr 26 21:15:05 2021<br>NAMESPACE: staging-python-app<br>STATUS: deployed<br>REVISION: 1<br>TEST SUITE: None</pre><p>Check resources in the namespace:</p><pre>kubectl get pods,jobs,service,ingress -n staging-python-app<br>NAME                                          READY   STATUS      RESTARTS   AGE<br>pod/staging-python-app-job-c9m65              0/1     Completed   0          4m41s<br>pod/staging-python-app-web-57b85c68b4-9jjml   1/1     Running     0          4m41s<br>pod/staging-python-app-web-57b85c68b4-fs9pl   1/1     Running     0          4m41s<br>pod/staging-python-app-web-57b85c68b4-lpgj8   1/1     Running     0          4m41s<br>pod/staging-python-app-web-57b85c68b4-qr27p   1/1     Running     0          4m41s</pre><pre>NAME                               COMPLETIONS   DURATION   AGE<br>job.batch/staging-python-app-job   1/1           2s         4m41s</pre><pre>NAME                             TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE<br>service/staging-python-app-web   ClusterIP   10.106.155.106   &lt;none&gt;        80/TCP    4m41s</pre><pre>NAME                                               CLASS    HOSTS                  ADDRESS          PORTS   AGE<br>ingress.networking.k8s.io/staging-python-app-web   &lt;none&gt;   staging-app.demo.com   192.168.99.107   80      4m41s</pre><p>Check ingress access:</p><pre>curl -H &quot;Host: staging-app.demo.com&quot; $(minikube ip)/<br>Hello, World!</pre><p>Check how many workers Gunicorn boots up:</p><pre>kubectl logs staging-python-app-web-57b85c68b4-9jjml -n staging-python-app | grep Booting | wc -l<br>       6</pre><p>As you can see, we have successfully used the same manifests to deploy applications with a different configuration. However, staging.yaml has fewer values provided than values.yaml. That is because values.yaml acts as a default values file. If there are no values for the specific key provided in the -f &lt;file&gt;, then the default value takes place.</p><h3>Clean up</h3><p>Destroy Minikube cluster:</p><pre>minikube delete</pre><p>Also, k8s-manifests/ directory is not needed since we have helm-charts. Let&#39;s remove it:</p><pre>rm -r k8s-manifests</pre><p>Do not forget to remove the directory from .dockerignore as well.</p><h3>Conclusion</h3><p>Congratulations on finishing this guide! If you wish to move forward by yourself, you can:</p><ul><li>Implement configurable ports in service.yaml, deployment.yaml, ingress.yaml</li><li>Implement support for multiple jobs</li><li>Implement option to disable one-off jobs</li><li>Write unit tests for your templates using <a href="https://github.com/lrills/helm-unittest">helm-unittest</a></li></ul><p>A fully finished application can be found here: <a href="https://github.com/brnck/k8s-python-demo-app/tree/helm">https://github.com/brnck/k8s-python-demo-app/tree/helm</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee2777fb458c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write Kubernetes manifests for python flask app]]></title>
            <link>https://medium.com/analytics-vidhya/write-kubernetes-manifests-for-python-flask-app-aa9e3bee710b?source=rss-17b8ec428343------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa9e3bee710b</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[minikube]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[helm]]></category>
            <dc:creator><![CDATA[Augustas Berneckas]]></dc:creator>
            <pubDate>Tue, 27 Apr 2021 10:25:54 GMT</pubDate>
            <atom:updated>2021-04-30T16:47:23.324Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is part of the series <a href="https://augustasberneckas.medium.com/prepare-and-deploy-python-app-to-kubernetes-736b13fe4cef"><strong>Prepare and Deploy python app to Kubernetes</strong></a></p><p><a href="https://augustasberneckas.medium.com/containerizing-python-flask-application-19faa9db031c">👈 Previous post: Containerizing python flask application</a></p><p><a href="https://augustasberneckas.medium.com/getting-to-know-minikube-e93f9676dea7">👈 Previous post: Getting to know Minikube</a></p><p>At the end of this series, we will have a fully working flask app in Kubernetes. The app itself that we are using, can be found here: <a href="https://github.com/brnck/k8s-python-demo-app/tree/docker">https://github.com/brnck/k8s-python-demo-app/tree/docker</a></p><h3>Prerequisites</h3><p>We are going to use minikube to deploy our application to Kubernetes. If you are not familiar with it, head over to <a href="https://augustasberneckas.medium.com/getting-to-know-minikube-e93f9676dea7">this post</a> to learn more, as we are going to cover topics such as how to use Minikube here.</p><h3>Defining use case</h3><p>Before we even start writing Kubernetes manifests, we need to clearly define our application use case for ourselves. It’d be easier to identify what resources we will need to deploy to Kubernetes.</p><p>So we have an application which:</p><ul><li>Handles our app users HTTP requests and returns some content;</li><li>Has a CLI command which also does something. It could be a one-off job or a cronjob. Let’s say we need a one-off job.</li></ul><p>That means we need to:</p><ul><li>Access the app from the outside of the cluster;</li><li>Be able to independently scale application;</li><li>Be able to run a one-off job.</li></ul><p>These use cases clearly indicate what <a href="https://kubernetes.io/docs/concepts/workloads/">workloads</a> we are going to use for our application. Now I am not going to dive deeper into the workloads explanation as I am assuming you are already more or less aware what are the differences between them. In addition to the workloads, we must also add additional resources around them so, f.i. clients would be able to reach our app.</p><p>To summarize everything, these are the Kubernetes resources we are going to deploy to our Kubernetes cluster:</p><ul><li><a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/">Namespace</a></li><li><a href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/">Deployment</a></li><li><a href="https://kubernetes.io/docs/concepts/workloads/controllers/job/">Job</a></li><li><a href="https://kubernetes.io/docs/concepts/services-networking/service/">Service</a></li><li><a href="https://kubernetes.io/docs/concepts/services-networking/ingress/">Ingress</a></li></ul><h3>Preparing directory and files</h3><p>Create a directory for manifests and add empty (for now) files:</p><pre>mkdir k8s-manifests<br>touch k8s-manifests/namespace.yaml<br>touch k8s-manifests/deployment.yaml<br>touch k8s-manifests/job.yaml<br>touch k8s-manifests/service.yaml<br>touch k8s-manifests/ingress.yaml</pre><p>Also, add k8s-manifests folder to .dockerignore file as there is no point in adding manifests into an image. If you have been using Kubernetes for some time you might have noticed that some public vendors use only one file for all the manifests. Now while there is nothing wrong with that as it produces the same result as having everything in separate files and deploying one by one. In fact, having all manifests in one file, helps with the ordering of resources deployment, because namespace must be deployed first before anything else. However, for the sake of clarity and readability, we are going to split files by resource.</p><h3>Creating namespace manifest</h3><p>Creating namespaces is usually based on context. The most common ones are probably team or project. You could either create one namespace for the whole development team, and it will be used to deploy all kinds of applications. They might even not be related to each other at all. The other way is to create a namespace only for the project. That is what we are going to do with our app as well. Creating a namespace for a project instead of a team prevents issues like “what if the team collaboratively manages applications with other teams?” from even appearing because from the administrator perspective we can easier control accesses and give them only to the applications that the developer or team needs access to.</p><p>Our application is called <strong>k8s-python-demo-app</strong>. We can drop the k8s- prefix and name our namespace python-demo-app.</p><p>Our final namespace.yaml file should look like this:</p><pre>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: python-demo-app</pre><h3>Creating deployment manifest</h3><p>To better understand what things are required for our web part of the application, let’s dive deeper and define the use case, as we did with the whole app. It will help to better understand how to write a deployment manifest.</p><p>Starting from the very beginning, a deployment called python-demo-app-web must be created in a namespace python-demo-app. It should use python-demo-app as an image and init as an image tag. Moreover, the container must be started as an app (id 1000) user with no privilege escalation. The container should request 128Mi memory and 100 CPU cycles. Also, resources should be limited to 256Mi and 200 CPU cycles. There should be 2 replicas deployed to Kubernetes. Finally, health checks must be performed. <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#define-readiness-probes">Readiness probe</a> should be constantly checking 8000 port and / endpoint. <a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#define-a-liveness-command">Liveness probe</a> should look for Gunicorn master process and ensure that it is running properly.</p><p>The use case is defined. Now start by translating it to deployment resource manifest.</p><p>First, start by adding metadata:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: python-demo-app-web<br>  namespace: python-demo-app</pre><p>Moving on to .spec part. Add replicas: 2 to .spec:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: python-demo-app-web<br>  namespace: python-demo-app<br>spec:<br>  replicas: 2</pre><p>We also need to add .spec.selector. According to the documentation, the .spec.selector field defines how the Deployment finds which Pods to manage. In this case, you select labels that are defined in the Pod template (app: python-demo-app and role: web). However, more sophisticated selection rules are possible, as long as the Pod template itself satisfies the rule.</p><p>Let’s define both of these:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: python-demo-app-web<br>  namespace: python-demo-app<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: python-demo-app<br>      role: web<br>  template:<br>    metadata:<br>      labels:<br>        app: python-demo-app<br>        role: web</pre><p>Moving further to .spec.template.spec. Before defining the container, let&#39;s handle security first. We can do that by adding securitycontext key with values runAsGroup: 1000 and runAsUser: 1000 (Because our image user is app (id 1000)). Defining securitycontext for a pod will make Kubernetes apply that context for all the containers that live in that pod. Proceed by adding container name, image, tag, and container port. Remember the previous lesson with docker? We have talked about gunicorn the default listening port which is 8000. It should be defined and name gunicorn. While naming a port is optional, it will help us later.</p><p>With the described changes, the deployment file should now look like this:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: python-demo-app-web<br>  namespace: python-demo-app<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: python-demo-app<br>      role: web<br>  template:<br>    metadata:<br>      labels:<br>        app: python-demo-app<br>        role: web<br>    spec:<br>      securityContext:<br>        runAsGroup: 1000<br>        runAsUser: 1000 <br>      containers:<br>        - name: python-demo-app-web<br>          image: python-demo-app:init<br>          ports:<br>            - name: gunicorn <br>              containerPort: 8000</pre><p>Resources that need to be allocated and limited for a container. By default, workloads can have no resources defined. It means that your application can potentially take over the whole cluster. Imagine having a memory leak in an app. This would create problems in a staging cluster and probably catastrophe in a production cluster. That is why it is usually a very good practice to allocate and limit resources for all the containers. However, this is a very deep topic that requires good knowledge of your application and how it works under a big load when booting up and idling. Setting low limits will result in unnecessary application restarts. On the other hand, do not set too high limits as it is a waste of resources and makes your cluster fewer efficient. For the sake of this is only the guide and that we are learning, let’s not concentrate more here and just define some logical resources requests and limits. As I have mentioned above:</p><blockquote><em>Container should request 128Mi memory and 100 CPU cycles. Also, resources should be limited to 256Mi and 200 CPU cycles</em></blockquote><p>Finally, let’s add liveness and readiness health checks. With the readiness we will check whether our web server responds to HTTP requests with the status 200 and with the liveness we will check the PID of gunicorn the process to ensure it is running. Also, let&#39;s give it some initial delay so gunicorn workers can be boot up.</p><p>The final deployment manifest should look like this:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: python-demo-app-web<br>  namespace: python-demo-app<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: python-demo-app<br>      role: web<br>  template:<br>    metadata:<br>      labels:<br>        app: python-demo-app<br>        role: web<br>    spec:<br>      securityContext:<br>        runAsGroup: 1000<br>        runAsUser: 1000<br>      containers:<br>        - name: python-demo-app-web<br>          image: python-demo-app:init<br>          ports:<br>            - name: gunicorn<br>              containerPort: 8000<br>          resources:<br>            requests:<br>              memory: 128Mi<br>              cpu: 100m<br>            limits:<br>              memory: 256Mi<br>              cpu: 200m<br>          readinessProbe:<br>            initialDelaySeconds: 10<br>            httpGet:<br>              port: gunicorn<br>              path: /<br>          livenessProbe:<br>            initialDelaySeconds: 10<br>            exec:<br>              command:<br>                - /bin/sh<br>                - -c <br>                - &quot;pidof -x gunicorn&quot;</pre><h3>Creating service manifest</h3><p>An abstract way to expose an application running on a set of Pods as a network service. Kubernetes gives Pods their own IP addresses and a single DNS name for a set of Pods and can load-balance across them.</p><p>As usual, create metadata first:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: python-demo-app-web<br>  namespace: python-demo-app</pre><p>Moving on to .spec, selector needs to be defined. It works pretty much the same as in deployment. Service needs to know which pods are eligible for the traffic to be routed to. Even the same labels can be added:</p><pre>spec:<br>  selector:<br>    app: python-demo-app<br>    role: web</pre><p>Finally, service needs to know not only to which pod route traffic to, but also to which port of the exposed ports. While it can map any port to a targeted pod port and for convenience, the targetPort is set to the same value as the port field let’s use 80 port for the service, name ithttp and route traffic to gunicorn (yes, we can use a name instead of a port number) port in a pod. If you did everything correctly, your final service manifest should look like this:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: python-demo-app-web<br>  namespace: python-demo-app<br>spec:<br>  selector:<br>    app: python-demo-app<br>    role: web<br>  ports:<br>    - name: http<br>      port: 80<br>      targetPort: gunicorn</pre><p>If we deploy the application now, any other application that runs inside a cluster could reach this app by simply using service-name.namespace-name syntax. You can read more about inside cluster DNS resolution <a href="https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#namespaces-of-services">here</a>. However, our goal is to let our customers consume the app. That is where ingress comes in</p><h3>Creating ingress manifest</h3><p>Ingress is basically HTTP and HTTPS router from outside the cluster to services. Routing is based on rules, so you can use one domain and route to completely different pods based on rules. This has only one route / so we are not going to dive deeper into routing to multiple services through one ingress. Instead, we will configure ingress to route traffic to python-demo-app-web service when HTTP request to Kubernetes comes with a host python-app.demo.com and / endpoint</p><p>I want to put a big <strong>disclaimer</strong> here. There is a <a href="https://github.com/kubernetes/ingress-nginx/pull/6187">bug</a> in the <strong>Nginx</strong> ingress controller. The one that is going to be used in minikube cluster. That is why old <strong>apiVersion</strong> will be used (you will get a warning when applying ingress). You can take it as a challenge and deploy the ingress controller with the image version that has this bug fixed.</p><p>You know the drill already. Metadata :)</p><pre>apiVersion: networking.k8s.io/v1beta1<br>kind: Ingress<br>metadata:<br>  name: python-demo-app-web<br>  namespace: python-demo-app</pre><p>In the .spec section, we will define the ingress class name which I have already mentioned in a disclaimer. Also, rules array must be defined. We can start by adding our rule with the host python-app.demo.com</p><pre>spec:<br>  rules:<br>    - host: python-app.demo.com</pre><p>Host it done. Now we need to add an endpoint and attach service to this rule. Everything is definable under host sibling - http. The final result should look like this:</p><pre>apiVersion: networking.k8s.io/v1beta1<br>kind: Ingress<br>metadata:<br>  name: python-demo-app-web<br>  namespace: python-demo-app<br>spec:<br>  rules:<br>    - host: python-app.demo.com<br>      http:<br>        paths:<br>          - path: /<br>            pathType: Prefix<br>            backend:<br>              serviceName: python-demo-app-web<br>              servicePort: http</pre><p>As key names are pretty self-explainable you have probably already known that this manifest translates to:</p><blockquote><em>All http requests coming through ingress controller with the host python-app.demo.com and an endpoint starting with / must be forwarded to the service named python-demo-app and its port http which (if we look to the service manifest again) should forward traffic to one of the app: python-demo-app, role: web labeled pods and its gunicorn port, which is 8000</em></blockquote><p>Everything for web traffic handling is ready. Let’s create the last manifest for running a one-off job</p><h3>Creating job manifest</h3><p><a href="https://kubernetes.io/docs/concepts/workloads/controllers/job/">Job</a> is basically a pod or pods which are scheduled to run until successful completion or until they are deleted. F.i. jobs could be used to run database schema updates, do some kind of maintenance task. Our job in this application is very simple — to print out Hello, world from CLI!.</p><p>As with all other manifests, described above, a Job needs apiVersion, kind, and metadata fields.</p><pre>apiVersion: batch/v1<br>kind: Job<br>metadata:<br>  name: hello-world-job<br>  namespace: python-demo-app</pre><p>The .spec.template is the only required field of the .spec. What&#39;s more, .spec.template is a pod template. It has exactly the same schema as a pod, except it is nested and does not have an apiVersion or kind. In fact, when we will finish creating this file, you will notice that there are many similarities between deployment and job.</p><p>As in deployment let&#39;s add labels to template:</p><pre>spec:<br>  template:<br>    metadata:<br>      labels:<br>        app: python-demo-app<br>        role: hello-world-job</pre><p>Proceed by adding .spec.template.spec.securityContext. We want this container to run as a user <strong>app</strong> as well. Have you wondered what happens if the job fails? Does Kubernetes restart the job? Or it just marks it as failed and do nothing? Well according to the documentation:</p><blockquote><em>Job is only appropriate for pods with RestartPolicy equal to OnFailure or Never. (Note: If RestartPolicy is not set, the default value is Always</em></blockquote><p>Or in other words, Kubernetes by default, set restartPolicy as Always. If the job would be deployed without setting an appropriate restartPolicy, deployment itself would fail. To solve that, let&#39;s also add restartPolicy: OnFailure</p><pre>spec:<br>  template:<br>    metadata:<br>      labels:<br>        app: python-demo-app<br>        role: hello-world-job<br>    spec:<br>      securityContext:<br>        runAsGroup: 1000<br>        runAsUser: 1000<br>      restartPolicy: OnFailure</pre><p>For the containers part, there will be some differences. First, we don’t need to expose any container port as this is a CLI command. Next up we won’t do any readiness checks, because the container does not accept any traffic. Also, for the sake of this guide let&#39;s not do liveness check as well as this command will run very quickly, so it&#39;s useless for this case.</p><p>After applying changes containers part should look like this:</p><pre>      containers:<br>        - name: python-demo-app-hello-world-job<br>          image: python-demo-app:init<br>          command:<br>            - python3<br>          args:<br>            - cli.py<br>          resources:<br>            requests:<br>              memory: 128Mi<br>              cpu: 100m<br>            limits:<br>              memory: 256Mi<br>              cpu: 200m</pre><p>You have probably noticed that there two new keys (command and args that was not present in the deployment). Let me explain what we are doing here. If you are following this guide from the beginning you will probably remember that we have used the same image to run our web server and CLI command. The only difference was that we changed the container entrypoint and cmd. That is what we are doing here as well. More explanation about command and args can be found <a href="https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/">here</a>. An approach like that is not always good. Most of the time separate image specifically for the CLI would be better, but let&#39;s not get into the details as that is out of the scope of this guide.</p><p>Our final job should look like this:</p><pre>apiVersion: batch/v1<br>kind: Job<br>metadata:<br>  name: hello-world-job<br>  namespace: python-demo-app<br>spec:<br>  template:<br>    metadata:<br>      labels:<br>        app: python-demo-app<br>        role: hello-world-job<br>    spec:<br>      securityContext:<br>        runAsGroup: 1000<br>        runAsUser: 1000<br>      restartPolicy: OnFailure<br>      containers:<br>        - name: python-demo-app-hello-world-job<br>          image: python-demo-app:init<br>          command:<br>            - python3<br>          args:<br>            - cli.py<br>          resources:<br>            requests:<br>              memory: 128Mi<br>              cpu: 100m<br>            limits:<br>              memory: 256Mi<br>              cpu: 200m</pre><h3>Deploying to Kubernetes</h3><p>It is time to deploy the application to Kubernetes.</p><p>First things first, create aminikube cluster. I am going to provision my Kubernetes cluster with virtualbox driver and kubernetes-version <strong>v1.20.5</strong>. Using the same command as mine is strongly advised, otherwise, some parts might not produce the result we expect. Proceed with different configurations only when you know what you are doing.</p><pre>minikube start --driver=virtualbox --kubernetes-version=1.20.5</pre><p>Enable ingress addon:</p><pre>minikube addons enable ingress</pre><p>Confirm that cluster is up and running:</p><pre>kubectl get nodes                                        <br>NAME       STATUS   ROLES                  AGE   VERSION<br>minikube   Ready    control-plane,master   81s   v1.20.5</pre><p>This guide will not cover how to build an image and push it to a private or public registry. Instead, for the sake of simplicity, we are going to build an image directly on minikube virtual machine. Make sure you are in the application directory in your terminal:</p><pre>eval $(minikube docker-env)<br>docker build -t python-demo-app:init .<br>&lt;...&gt;<br>Successfully built 22008520508b<br>Successfully tagged python-demo-app:init</pre><p>Confirm:</p><pre>minikube ssh docker images | grep python-demo-app<br>python-demo-app                           init         22008520508b   About a minute ago   125MB</pre><p>Everything is ready. Proceed by creating a namespace and confirm it:</p><pre>kubectl apply -f k8s-manifests/namespace.yaml<br>kubectl get namespaces<br>NAME              STATUS   AGE<br>default           Active   11m<br>ingress-nginx     Active   10m<br>kube-node-lease   Active   11m<br>kube-public       Active   11m<br>kube-system       Active   11m<br>python-demo-app   Active   12s # &lt;-- Here is our namespace</pre><p>Now deploy the rest of the application:</p><pre>kubectl apply -f k8s-manifests/deployment.yaml \<br>  -f k8s-manifests/service.yaml \<br>  -f k8s-manifests/ingress.yaml \<br>  -f k8s-manifests/job.yaml</pre><p>Kubectl will return an output:</p><pre>deployment.apps/python-demo-app-web created<br>service/python-demo-app-web created<br>Warning: networking.k8s.io/v1beta1 Ingress is deprecated in v1.19+, unavailable in v1.22+; use networking.k8s.io/v1 Ingress<br>ingress.networking.k8s.io/python-demo-app-web created<br>job.batch/hello-world-job created</pre><p>I have already mentioned why we are using networking.k8s.io/v1beta1 instead of networking.k8s.io/v1</p><p>Let’s check if all resources deployed and running:</p><pre>kubectl get pods,jobs,service,ingress -n python-demo-app<br>NAME                                      READY   STATUS      RESTARTS   AGE<br>pod/hello-world-job-9l9w9                 0/1     Completed   0          10s<br>pod/python-demo-app-web-5f756fbcc-628cd   0/1     Running     0          10s<br>pod/python-demo-app-web-5f756fbcc-cz5kl   0/1     Running     0          10s</pre><pre>NAME                        COMPLETIONS   DURATION   AGE<br>job.batch/hello-world-job   1/1           3s         10s</pre><pre>NAME                          TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE<br>service/python-demo-app-web   ClusterIP   10.100.245.172   &lt;none&gt;        80/TCP    10s</pre><pre>NAME                                            CLASS   HOSTS                 ADDRESS   PORTS   AGE<br>ingress.networking.k8s.io/python-demo-app-web   nginx   python-app.demo.com             80      10s</pre><p>Web pods are still booting up. Let’s give it few more seconds. While we are waiting, we can check job pod pod/hello-world-job-9l9w9 as the job is marked as completed:</p><pre>kubectl logs hello-world-job-9l9w9 -n python-demo-app                         <br>Hello, world from CLI!</pre><p>Perfect! The one-off job ran and completed successfully. Getting back to web pods:</p><pre>kubectl get deployment,replicaset,pods -n python-demo-app<br>NAME                                  READY   UP-TO-DATE   AVAILABLE   AGE<br>deployment.apps/python-demo-app-web   0/2     2            0           6m9s</pre><pre>NAME                                            DESIRED   CURRENT   READY   AGE<br>replicaset.apps/python-demo-app-web-5f756fbcc   2         2         0       6m9s</pre><pre>NAME                                      READY   STATUS      RESTARTS   AGE<br>pod/hello-world-job-9l9w9                 0/1     Completed   0          6m9s<br>pod/python-demo-app-web-5f756fbcc-628cd   0/1     Running     0          6m9s<br>pod/python-demo-app-web-5f756fbcc-cz5kl   0/1     Running     0          6m9s</pre><p>Pods are running, but they are not marked as ready. Something is wrong. We need to inspect one of the pods&#39; logs:</p><pre>kubectl logs python-demo-app-web-5f756fbcc-628cd -n python-demo-app<br>[2021-04-22 21:22:32 +0000] [1] [INFO] Starting gunicorn 20.0.4<br>[2021-04-22 21:22:32 +0000] [1] [INFO] Listening at: http://127.0.0.1:8000 (1)<br>[2021-04-22 21:22:32 +0000] [1] [INFO] Using worker: sync<br>[2021-04-22 21:22:32 +0000] [7] [INFO] Booting worker with pid: 7</pre><p>Nothing strange. How about describing that pod:</p><pre>kubectl describe pod python-demo-app-web-5f756fbcc-628cd -n python-demo-app<br>&lt;...&gt;<br>Events:<br>  Type     Reason     Age                     From               Message<br>  ----     ------     ----                    ----               -------<br>  Normal   Scheduled  9m5s                    default-scheduler  Successfully assigned python-demo-app/python-demo-app-web-5f756fbcc-628cd to minikube<br>  Normal   Pulled     9m3s                    kubelet            Container image &quot;python-demo-app:init&quot; already present on machine<br>  Normal   Created    9m3s                    kubelet            Created container python-demo-app-web<br>  Normal   Started    9m3s                    kubelet            Started container python-demo-app-web<br>  Warning  Unhealthy  3m55s (x30 over 8m45s)  kubelet            Readiness probe failed: Get &quot;http://172.17.0.3:8000/&quot;: dial tcp 172.17.0.3:8000: connect: connection refused</pre><p>By checking both of the outputs, we can see a problem. gunicorn clearly shows that it listens at localhost while Readiness tries to make an HTTP request to container IP. The solution is to bind gunicorn to all interfaces. This can be solved by adding args section to a container with --bind 0.0.0.0 flag. Of course, there are more ways to solve this problem, but I will leave that to you, in case this is too easy.</p><p>As we know from Dockerfile, arguments, provided to entrypoint are app:app. That means it must be added to args as well.</p><p>Head over to deployment manifest and add args below image key:</p><pre>&lt;...&gt;<br>          image: python-demo-app:init<br>          args:<br>            - &#39;--bind&#39;<br>            - &#39;0.0.0.0&#39;<br>            - &#39;app:app&#39;<br>          ports:<br>&lt;...&gt;</pre><p>Redeploy</p><pre>kubectl apply -f k8s-manifests/deployment.yaml<br>deployment.apps/python-demo-app-web configured</pre><p>After 30–60 seconds, pods should become running</p><pre>kubectl get pods -n python-demo-app                      <br>NAME                                   READY   STATUS      RESTARTS   AGE<br>hello-world-job-9l9w9                  0/1     Completed   0          22m<br>python-demo-app-web-6c4cc75ddc-tmxjl   1/1     Running     0          67s<br>python-demo-app-web-6c4cc75ddc-wb79r   1/1     Running     0          87s</pre><p>Indeed, it is. There we go. We identified and fixed a bug!</p><p>Can we reach our application from outside? Let’s check:</p><pre>curl -H &quot;Host: python-app.demo.com&quot; $(minikube ip)/<br>Hello, World!</pre><p>HTTP request was successful, and the answer was returned! There is nothing else to be done. We may now clean up everything from the cluster:</p><pre>kubectl delete -f k8s-manifests/deployment.yaml \<br>  -f k8s-manifests/service.yaml \<br>  -f k8s-manifests/ingress.yaml \<br>  -f k8s-manifests/job.yaml</pre><p>Also, remove namespace:</p><pre>kubectl delete -f k8s-manifests/namespace.yaml</pre><h3>Conclusion</h3><p>Congratulations on writing your own Kubernetes manifests. If this was too easy, and you want more, here’s a few tasks that can be done additionally:</p><ul><li>Modify CLI command to read environment variable called MESSAGE and pass the value using <a href="https://kubernetes.io/docs/concepts/configuration/configmap/">configmap</a></li><li>Create gunicorn config file using configmap and mount it to web pod. Make sure bind is passed via config file, not through args</li></ul><p>Manifests with the application can be found <a href="https://github.com/brnck/k8s-python-demo-app/tree/manifests">here</a>. Proceed to the next guide, where we will <a href="https://augustasberneckas.medium.com/write-helm-charts-for-python-flask-app-ee2777fb458c">wrap manifests to helm-charts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa9e3bee710b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/write-kubernetes-manifests-for-python-flask-app-aa9e3bee710b">Write Kubernetes manifests for python flask app</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting to know Minikube]]></title>
            <link>https://augustasberneckas.medium.com/getting-to-know-minikube-e93f9676dea7?source=rss-17b8ec428343------2</link>
            <guid isPermaLink="false">https://medium.com/p/e93f9676dea7</guid>
            <category><![CDATA[helm]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[minikube]]></category>
            <dc:creator><![CDATA[Augustas Berneckas]]></dc:creator>
            <pubDate>Tue, 27 Apr 2021 10:16:58 GMT</pubDate>
            <atom:updated>2021-04-27T10:26:53.339Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is part of the series <a href="https://augustasberneckas.medium.com/prepare-and-deploy-python-app-to-kubernetes-736b13fe4cef"><strong>Prepare and Deploy python app to Kubernetes</strong></a></p><p><a href="https://augustasberneckas.medium.com/containerizing-python-flask-application-19faa9db031c">👈 Previous post: Containerizing python flask application</a></p><p>At the end of this series, we will have a fully working flask app in Kubernetes. The app itself that we are using, can be found here: <a href="https://github.com/brnck/k8s-python-demo-app/tree/manifests">https://github.com/brnck/k8s-python-demo-app</a></p><p>Minikube is a local Kubernetes, focusing on making it easy to learn and develop for Kubernetes. In this guide, we are not going to deploy anything to Minikube yet. We are just going to get familiar with the tool itself</p><p>Install Minikube by using one of the provided procedure in the official documentation <a href="https://minikube.sigs.k8s.io/docs/start/#what-youll-need">here</a></p><h3>Initial start</h3><p>Make sure the <strong>docker</strong> daemon is running on your machine. When starting Minikube for the first time, give it some time to download all the dependencies.</p><pre>minikube start<br>😄  minikube v1.19.0 on Darwin 11.2.3<br>✨  Automatically selected the docker driver. Other choices: hyperkit, virtualbox, ssh<br>&lt;...&gt;<br>🏄  Done! kubectl is now configured to use &quot;minikube&quot; cluster and &quot;default&quot; namespace by default</pre><p>And there it is. You have Kubernetes up and running in your own machine.</p><p>Right now you have started Kubernetes using <strong>docker</strong> as a driver. However, I always prefer using <strong>VirtualBox</strong> as a driver over a <strong>docker. </strong>Basically what it does is that Minikube spins up a new virtual machine on your machine and provisions Kubernetes cluster in it. If you want to be on the same side as me, you can reprovision cluster on <strong>VirtualBox</strong> as well</p><h3>Recreating the cluster</h3><p>Let’s destroy the previously created cluster:</p><pre>minikube delete<br>🔥  Deleting &quot;minikube&quot; in docker ...<br>&lt;...&gt;<br>💀  Removed all traces of the &quot;minikube&quot; cluster.</pre><p>Create a new one. It’ll take a while as well since it needs to download <strong>VirtualBox </strong>box:</p><pre>minikube start --driver=virtualbox<br>😄  minikube v1.19.0 on Darwin 11.2.3<br>✨  Using the virtualbox driver based on user configuration<br>&lt;...&gt;<br>👍  Starting control plane node minikube in cluster minikube<br>🔥  Creating virtualbox VM (CPUs=2, Memory=4000MB, Disk=20000MB) ...<br>&lt;...&gt;<br>🏄  Done! kubectl is now configured to use &quot;minikube&quot; cluster and &quot;default&quot; namespace by default</pre><h3>Basic commands</h3><h4>Check status</h4><pre>minikube status                   <br>minikube<br>type: Control Plane<br>host: Running<br>kubelet: Running<br>apiserver: Running<br>kubeconfig: Configured</pre><h4>Stop the cluster</h4><p>Stop command stops the cluster, but it does not destroy it completely. This is very useful when you’re switching from some tasks related to Minikube and you want to free up the resources that it took.</p><pre>minikube stop       <br>✋  Stopping node &quot;minikube&quot;  ...<br>🛑  1 nodes stopped.</pre><p>Let’s check the status after the stop:</p><pre>minikube status<br>minikube<br>type: Control Plane<br>host: Stopped<br>kubelet: Stopped<br>apiserver: Stopped<br>kubeconfig: Stopped</pre><p>Let’s start the cluster again:</p><pre>minikube start<br>😄  minikube v1.19.0 on Darwin 11.2.3<br>✨  Using the virtualbox driver based on existing profile<br>👍  Starting control plane node minikube in cluster minikube<br>🔄  Restarting existing virtualbox VM for &quot;minikube&quot; ...<br>🐳  Preparing Kubernetes v1.20.2 on Docker 20.10.4 ...<br>🔎  Verifying Kubernetes components...<br>▪ Using image gcr.io/k8s-minikube/storage-provisioner:v5<br>🌟  Enabled addons: storage-provisioner, default-storageclass<br>🏄  Done! kubectl is now configured to use &quot;minikube&quot; cluster and &quot;default&quot; namespace by default</pre><p>When starting stopped cluster, flags like<strong> — driver</strong>, <strong>— memory,</strong> and so on are not needed anymore. Initial flags are only needed when you create a cluster from scratch</p><h4>Delete the cluster</h4><p>Usually, it’s good to destroy the cluster once in a while. Also, you might need a bigger cluster with more CPU or RAM or a different k8s version. That’s when delete command kicks in. It completely destroys VM (and k8s cluster with it) so you could recreate the cluster from scratch</p><pre>minikube delete<br>🔥  Deleting &quot;minikube&quot; in virtualbox ...<br>💀  Removed all traces of the &quot;minikube&quot; cluster.</pre><h3>Advanced commands</h3><p>Let’s say we need a cluster with more resources or we need to reach it through <a href="https://kubernetes.io/docs/concepts/services-networking/ingress/">ingress controller</a> or we want to see a nice dashboard that Kubernetes provide or we even want a different k8s cluster version. It’s all possible with just extra flags or additional commands</p><h4>Provision cluster with additional resources</h4><p>As you have probably noticed above, Minikube by default provision VM with CPUs=2, Memory=4000MB, Disk=20000MB. We can tweak resources on the initial minikube start<strong>. </strong>Also, let’s run older k8s version</p><pre>minikube start --driver=virtualbox --cpus=3 --memory=6g --disk-size=40g --kubernetes-version=1.19.0<br>😄  minikube v1.19.0 on Darwin 11.2.3<br>✨  Using the virtualbox driver based on user configuration<br>👍  Starting control plane node minikube in cluster minikube<br>🔥  Creating virtualbox VM (CPUs=3, Memory=6144MB, Disk=40000MB) ...<br>&lt;...&gt;<br><br>❗  /usr/local/bin/kubectl is version 1.21.0, which may have incompatibilites with Kubernetes 1.19.0.<br>▪ Want kubectl v1.19.0? Try &#39;minikube kubectl -- get pods -A&#39;<br>🏄  Done! kubectl is now configured to use &quot;minikube&quot; cluster and &quot;default&quot; namespace by default</pre><p>And that’s it. You now have a cluster with increased resources</p><h4>Addons list</h4><p>Addons are like extra functionality which can be deployed with only one command. Usually, you would need to configure them manually, but luckily <strong>Minikube</strong> does that for you</p><p>Let’s check available addons:</p><pre>minikube addons list                                                               <br>|-----------------------------|----------|--------------|<br>|         ADDON NAME          | PROFILE  |    STATUS    |<br>|-----------------------------|----------|--------------|<br>| ambassador                  | minikube | disabled     |<br>| auto-pause                  | minikube | disabled     |<br>| csi-hostpath-driver         | minikube | disabled     |<br>| dashboard                   | minikube | disabled     |<br>| default-storageclass        | minikube | enabled ✅   |<br>| efk                         | minikube | disabled     |<br>| freshpod                    | minikube | disabled     |<br>| gcp-auth                    | minikube | disabled     |<br>| gvisor                      | minikube | disabled     |<br>| helm-tiller                 | minikube | disabled     |<br>| ingress                     | minikube | disabled     |<br>| ingress-dns                 | minikube | disabled     |<br>| istio                       | minikube | disabled     |<br>| istio-provisioner           | minikube | disabled     |<br>| kubevirt                    | minikube | disabled     |<br>| logviewer                   | minikube | disabled     |<br>| metallb                     | minikube | disabled     |<br>| metrics-server              | minikube | disabled     |<br>| nvidia-driver-installer     | minikube | disabled     |<br>| nvidia-gpu-device-plugin    | minikube | disabled     |<br>| olm                         | minikube | disabled     |<br>| pod-security-policy         | minikube | disabled     |<br>| registry                    | minikube | disabled     |<br>| registry-aliases            | minikube | disabled     |<br>| registry-creds              | minikube | disabled     |<br>| storage-provisioner         | minikube | enabled ✅   |<br>| storage-provisioner-gluster | minikube | disabled     |<br>| volumesnapshots             | minikube | disabled     |<br>|-----------------------------|----------|--------------|</pre><p>The most used addons that you are probably going to deal with will be <strong>metrics-server</strong> (to check pods resources consumption) and <strong>ingress</strong> (to be able to simulate ingress traffic from outside the cluster)</p><h4>Enable addons</h4><p>Let’s enable <strong>metrics-server:</strong></p><pre>minikube addons enable metrics-server<br>    ▪ Using image k8s.gcr.io/metrics-server/metrics-server:v0.4.2<br>🌟  The &#39;metrics-server&#39; addon is enabled</pre><p>Let’s enable <strong>ingress:</strong></p><pre>minikube addons enable ingress       <br>    ▪ Using image k8s.gcr.io/ingress-nginx/controller:v0.44.0<br>    ▪ Using image docker.io/jettech/kube-webhook-certgen:v1.5.1<br>    ▪ Using image docker.io/jettech/kube-webhook-certgen:v1.5.1<br>🔎  Verifying ingress addon...<br>🌟  The &#39;ingress&#39; addon is enabled</pre><p>Let’s check addons again:</p><pre>minikube addons list                 <br>|-----------------------------|----------|--------------|<br>|         ADDON NAME          | PROFILE  |    STATUS    |<br>|-----------------------------|----------|--------------|<br>| ambassador                  | minikube | disabled     |<br>| auto-pause                  | minikube | disabled     |<br>| csi-hostpath-driver         | minikube | disabled     |<br>| dashboard                   | minikube | disabled     |<br>| default-storageclass        | minikube | enabled ✅   |<br>| efk                         | minikube | disabled     |<br>| freshpod                    | minikube | disabled     |<br>| gcp-auth                    | minikube | disabled     |<br>| gvisor                      | minikube | disabled     |<br>| helm-tiller                 | minikube | disabled     |<br>| ingress                     | minikube | enabled ✅   |<br>| ingress-dns                 | minikube | disabled     |<br>| istio                       | minikube | disabled     |<br>| istio-provisioner           | minikube | disabled     |<br>| kubevirt                    | minikube | disabled     |<br>| logviewer                   | minikube | disabled     |<br>| metallb                     | minikube | disabled     |<br>| metrics-server              | minikube | enabled ✅   |<br>| nvidia-driver-installer     | minikube | disabled     |<br>| nvidia-gpu-device-plugin    | minikube | disabled     |<br>| olm                         | minikube | disabled     |<br>| pod-security-policy         | minikube | disabled     |<br>| registry                    | minikube | disabled     |<br>| registry-aliases            | minikube | disabled     |<br>| registry-creds              | minikube | disabled     |<br>| storage-provisioner         | minikube | enabled ✅   |<br>| storage-provisioner-gluster | minikube | disabled     |<br>| volumesnapshots             | minikube | disabled     |<br>|-----------------------------|----------|--------------|</pre><h4>Kubernetes dashboard</h4><p>K8s has a very nice dashboard that can provide useful information without consuming its <strong>CLI</strong> tool kubectl<strong>.</strong> To enable it, execute this command:</p><pre>minikube dashboard  <br>🔌  Enabling dashboard ...<br>    ▪ Using image kubernetesui/dashboard:v2.1.0<br>    ▪ Using image kubernetesui/metrics-scraper:v1.0.4<br>🤔  Verifying dashboard health ...<br>🚀  Launching proxy ...<br>🤔  Verifying proxy health ...<br>🎉  Opening http://127.0.0.1:53197/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/ in your default browser...</pre><p>It will open a web page in your browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ekrqzzHyXDENIzY77SxxbQ.png" /><figcaption>Kubernetes dashboard</figcaption></figure><p>The dashboard will be accessible until the command will be stopped.</p><h3>Conclusion</h3><p>We have covered the basic usage of Minikube. If you want, you can spend more time with it by trying to interact with the cluster using kubectl and deploy applications. Otherwise, let’s proceed to the next guide where we are going to <a href="https://augustasberneckas.medium.com/write-kubernetes-manifests-for-python-flask-app-aa9e3bee710b">write Kubernetes manifests for the application and deploy it to the Minikube cluster</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e93f9676dea7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Containerizing python flask application]]></title>
            <link>https://medium.com/analytics-vidhya/containerizing-python-flask-application-19faa9db031c?source=rss-17b8ec428343------2</link>
            <guid isPermaLink="false">https://medium.com/p/19faa9db031c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[minikube]]></category>
            <category><![CDATA[helm]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Augustas Berneckas]]></dc:creator>
            <pubDate>Mon, 26 Apr 2021 19:32:29 GMT</pubDate>
            <atom:updated>2021-04-30T15:49:08.371Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is part of the series <a href="https://medium.com/@augustasberneckas/prepare-and-deploy-python-app-to-kubernetes-736b13fe4cef"><strong>Prepare and Deploy python app to Kubernetes</strong></a></p><p>At the end of this series, we will have a fully working flask app in Kubernetes. The app itself that we are using, can be found here: <a href="https://github.com/brnck/k8s-python-demo-app">https://github.com/brnck/k8s-python-demo-app</a></p><h3>Creating dockerfile</h3><p>Before we even start writing Kubernetes manifests, we need to have containerized application. This guide assumes that you have general knowledge of <a href="https://docs.docker.com/">docker</a> and how to <a href="https://docs.docker.com/engine/reference/builder">build images</a></p><p>Let’s start by creating dockerfile:</p><pre>touch Dockerfile</pre><p>Our application supports python 3.x so let’s start building from the newest stable python (3.9.4 as of writing this guide):</p><pre>FROM python:3.9.4-slim</pre><p>Now you might be wondering what’s that word <strong>slim</strong> doing at the end of the tag. You might have also seen other keywords like <strong>alpine</strong></p><p>There is a very good explanation post by <a href="https://medium.com/@geekgirl907">Julie Perilla Garcia</a>.</p><p>You can check it here: <a href="https://medium.com/swlh/alpine-slim-stretch-buster-jessie-bullseye-bookworm-what-are-the-differences-in-docker-62171ed4531d">Alpine, Slim, Stretch, Buster, Jessie, Bullseye — What are the Differences in Docker Images?</a></p><p>For security purposes we don’t want to run our app as root, so let’s create app user:</p><pre>RUN groupadd --gid 1000 app &amp;&amp; \<br>    useradd --create-home --gid 1000 --uid 1000 app</pre><p>Now let’s create a directory where we are going to put our application. Some people like to put an application in /app or /appname. However, I like to put applications to /home/app/src not even in containers, but also hardware or virtual machines. This gives some sort of standardization across environments. So let&#39;s create a directory and make it as a workdir:</p><pre>RUN mkdir -p /home/app/src</pre><pre>WORKDIR /home/app/src</pre><p>Almost over, the environment is ready. Let’s move on by copying our source code and installing dependencies:</p><pre>COPY ./ /home/app/src<br>RUN pip3 install -r requirements.txt</pre><p>Finally, we want our app to run as user <strong>app</strong>, use <strong>flask</strong> <a href="https://docs.docker.com/engine/reference/builder/#entrypoint">entrypoint</a>, and <strong>run</strong> as a <a href="https://docs.docker.com/engine/reference/builder/#cmd">command</a></p><pre>USER app</pre><pre>ENTRYPOINT [&quot;flask&quot;]</pre><pre>CMD [&quot;run&quot;]</pre><p>Our Full dockerfile should look like this:</p><pre>FROM python:3.9.4-slim</pre><pre>RUN groupadd --gid 1000 app &amp;&amp; \<br>    useradd --create-home --gid 1000 --uid 1000 app</pre><pre>RUN mkdir -p /home/app/src</pre><pre>WORKDIR /home/app/src</pre><pre>COPY ./ /home/app/src<br>RUN pip3 install -r requirements.txt</pre><pre>USER app</pre><pre>ENTRYPOINT [&quot;flask&quot;]</pre><pre>CMD [&quot;run&quot;]</pre><h3>Adding .dockerignore</h3><p>We also want to prevent adding unnecessary files to our docker image. That’s where <a href="https://docs.docker.com/engine/reference/builder/#dockerignore-file">.dockerignore</a> comes in. It works similarly to .gitignore by ignoring files or folders that would be built into an image. This helps to reduce image size by avoiding unnecessarily sending large or sensitive files and directories to the daemon and potentially adding them to images using ADD or COPY</p><p>Let’s create .dockerignore file and ignore unnecessary files:</p><pre>.idea/<br>.vscode/<br>.git/<br>.venv/<br>__pycache__/<br>.gitignore<br>Dockerfile</pre><h3>Building&amp;Running docker file</h3><pre>docker build -t python-demo-app:init .<br>&lt;...&gt;<br> =&gt; =&gt; naming to docker.io/library/python-demo-app:init</pre><p>Let’s run our container</p><pre>docker run --rm python-demo-app:init run --host 0.0.0.0 --port 5000<br> * Environment: production<br>   WARNING: This is a development server. Do not use it in a production deployment.<br>   Use a production WSGI server instead.<br> * Debug mode: off<br> * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)</pre><p>Open another terminal session and curl localhost</p><pre>curl localhost:5000<br>curl: (7) Failed to connect to localhost port 5000: Connection refused</pre><p>Oopsie... Port is not exposed to the host machine. Let’s rerun the container with the exposed port:</p><pre>docker run --rm --publish 5000:5000 python-demo-app:init run --host 0.0.0.0 --port 5000<br>curl 127.0.0.1:5000<br>Hello, World!</pre><h3>Switching to production server</h3><p>You have probably noticed that even flask itself prints a warning:</p><pre>* Environment: production<br>   WARNING: This is a development server. Do not use it in a production deployment.<br>   Use a production WSGI server instead.</pre><p>Since we are preparing our application for production, let’s switch to the WSGI server. In this case, we are going to use <a href="https://gunicorn.org/">gunicorn</a></p><p>Let’s edit our <strong>requirements.txt</strong> file by adding <strong>gunicorn</strong>:</p><pre>gunicorn==20.0.4</pre><p>Proceed by editing Dockerfile and switching from <strong>flask</strong> to <strong>gunicorn</strong>:</p><p>Switch</p><pre>ENTRYPOINT [&quot;flask&quot;]</pre><p>To</p><pre>ENTRYPOINT [&quot;gunicorn&quot;]</pre><p>Also, switch</p><pre>CMD [&quot;run&quot;]</pre><p>To</p><pre>CMD [&quot;app:app&quot;]</pre><p>Our dockerfile should now look like this:</p><pre>FROM python:3.9.4-slim</pre><pre>RUN groupadd --gid 1000 app &amp;&amp; \<br>    useradd --create-home --gid 1000 --uid 1000 app</pre><pre>RUN mkdir -p /home/app/src</pre><pre>WORKDIR /home/app/src</pre><pre>COPY ./ /home/app/src<br>RUN pip3 install -r requirements.txt</pre><pre>USER app</pre><pre>ENTRYPOINT [&quot;gunicorn&quot;]</pre><pre>CMD [&quot;app:app&quot;]</pre><p>Let’s rebuild our container and run it again:</p><pre>docker build -t python-demo-app:init .</pre><p>Since gunicorn by default runs on port 8000, let&#39;s switch to it instead of 5000 port</p><pre>docker run --rm --publish 8000:8000 python-demo-app:init --bind 0.0.0.0 app:app<br>[2021-04-21 13:11:24 +0000] [1] [INFO] Starting gunicorn 20.0.4<br>[2021-04-21 13:11:24 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1)<br>[2021-04-21 13:11:24 +0000] [1] [INFO] Using worker: sync<br>[2021-04-21 13:11:24 +0000] [7] [INFO] Booting worker with pid: 7</pre><pre>curl 127.0.0.1:8000<br>Hello, World!</pre><h3>Running CLI scripts instead of the webserver</h3><p>We can choose either build a separate image only for python CLI scripts or reuse our current image just by changing <strong>Entrypoint</strong> and <strong>cmd</strong>. Let’s switch <strong>entrypoint</strong> to <strong>python3</strong> instead of <strong>gunicorn</strong> and execute <strong>cli.py</strong> script</p><pre>docker run --rm --entrypoint python3 python-demo-app:init cli.py<br>Hello, world from CLI!</pre><h3>Conclusion</h3><p>In this guide, we have created dockerfile which we will use to deploy and serve our application from Kubernetes.</p><p>The final solution can be found here: <a href="https://github.com/brnck/k8s-python-demo-app/tree/docker">https://github.com/brnck/k8s-python-demo-app/tree/docker</a></p><p>Let’s move over to the next guide and <a href="https://augustasberneckas.medium.com/write-kubernetes-manifests-for-python-flask-app-aa9e3bee710b">create Kubernetes manifests for our application</a>. Or if you are not familiar with minikube , check <a href="https://augustasberneckas.medium.com/getting-to-know-minikube-e93f9676dea7">this</a> post before moving to the manifests part</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19faa9db031c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/containerizing-python-flask-application-19faa9db031c">Containerizing python flask application</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prepare and Deploy python app to Kubernetes]]></title>
            <link>https://augustasberneckas.medium.com/prepare-and-deploy-python-app-to-kubernetes-736b13fe4cef?source=rss-17b8ec428343------2</link>
            <guid isPermaLink="false">https://medium.com/p/736b13fe4cef</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[minikube]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[helm]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Augustas Berneckas]]></dc:creator>
            <pubDate>Mon, 26 Apr 2021 19:22:51 GMT</pubDate>
            <atom:updated>2021-04-27T10:35:51.034Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://kubernetes.io/">Kubernetes</a> usage is growing rapidly. According to <a href="https://www.cncf.io/about/who-we-are/">Cloud Native Computing Foundation</a> survey report which was released in 2020:</p><blockquote><em>Kubernetes use in production has increased to 83%, up from 78% last year.</em></blockquote><p>Containers, in general, usage have also increased:</p><blockquote><em>The use of containers in production has increased to 92%, up from 84% last year, and up 300% from our first survey in 2016.</em></blockquote><p>The full report can be found here: <a href="https://www.cncf.io/wp-content/uploads/2020/11/CNCF_Survey_Report_2020.pdf">https://www.cncf.io/wp-content/uploads/2020/11/CNCF_Survey_Report_2020.pdf</a></p><p>It seems that more and more companies (even small ones) are shifting their ecosystem to containers, and some of them to Kubernetes as well. If you are still thinking about moving to Kubernetes or to containers in general, evaluating concepts, doing PoCs I strongly recommend weighing up the pros and cons carefully. Because “Your team might not need Kubernetes” as <a href="https://alexellisuk.medium.com/">Alex Ellis</a> says. You can read his post here: <a href="https://faun.pub/your-team-might-not-need-kubernetes-57240e8d554a">https://faun.pub/your-team-might-not-need-kubernetes-57240e8d554a</a></p><p>Now do not get me wrong. I like Kubernetes and while it comes with great benefits it also has its own cons like complexity, small teams can find it difficult to manage. However, once you become familiar with Kubernetes and its concepts, you will more likely start to think that it is not so complex at all.</p><p>Enough about statistics and comparison. Let’s dive into our topic. I decided to write small series of posts on how to prepare and deploy a python application (flask, CLI) to Kubernetes and even make it deployable across different environments.</p><p>Applications/Tools that will be used in this guide:</p><ul><li><a href="https://minikube.sigs.k8s.io/docs/start/">minikube</a> with <strong>Kubernetes v1.20.xx</strong></li><li><a href="https://kubernetes.io/docs/tasks/tools/">kubectl</a></li><li><a href="https://helm.sh/">Helm</a></li><li><a href="https://github.com/brnck/k8s-python-demo-app">k8s-python-demo-app</a></li><li><a href="https://curl.se/">curl</a></li><li>Text editor of your choice</li></ul><p>This guide will cover topics such as:</p><ul><li><a href="https://augustasberneckas.medium.com/containerizing-python-flask-application-19faa9db031c">Containerizing python flask application</a></li><li><a href="https://augustasberneckas.medium.com/getting-to-know-minikube-e93f9676dea7">Getting to know </a><a href="https://augustasberneckas.medium.com/getting-to-know-minikube-e93f9676dea7">minikube (if you are not familiar with it already)</a></li><li><a href="https://augustasberneckas.medium.com/write-kubernetes-manifests-for-python-flask-app-aa9e3bee710b">Write Kubernetes manifests for python flask app</a></li><li><a href="https://augustasberneckas.medium.com/write-helm-charts-for-python-flask-app-ee2777fb458c">Write Helm charts for python flask app</a></li></ul><p>At the end of this series, we will have a fully working flask app in Kubernetes.</p><p>This guide assumes that you have general knowledge about Docker, Kubernetes concepts. If not, it might be hard to keep track of everything we are doing here. However, here are some reference links to Kubernetes documentation of the things, we will cover in this series:</p><ul><li><a href="https://kubernetes.io/docs/concepts/overview/what-is-kubernetes/">https://kubernetes.io/docs/concepts/overview/what-is-kubernetes/</a></li><li><a href="https://kubernetes.io/docs/concepts/containers/">https://kubernetes.io/docs/concepts/containers/</a></li><li><a href="https://kubernetes.io/docs/concepts/workloads/">https://kubernetes.io/docs/concepts/workloads/</a></li><li><a href="https://kubernetes.io/docs/concepts/workloads/pods/">https://kubernetes.io/docs/concepts/workloads/pods/</a></li><li><a href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/">https://kubernetes.io/docs/concepts/workloads/controllers/deployment/</a></li><li><a href="https://kubernetes.io/docs/concepts/services-networking/service/">https://kubernetes.io/docs/concepts/services-networking/service/</a></li><li><a href="https://kubernetes.io/docs/concepts/services-networking/ingress/">https://kubernetes.io/docs/concepts/services-networking/ingress/</a></li><li><a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/kubernetes-objects/">https://kubernetes.io/docs/concepts/overview/working-with-objects/kubernetes-objects/</a></li></ul><p><a href="https://augustasberneckas.medium.com/containerizing-python-flask-application-19faa9db031c">Containerizing python flask application 👉</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=736b13fe4cef" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>