<?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 Sebastian Scotti on Medium]]></title>
        <description><![CDATA[Stories by Sebastian Scotti on Medium]]></description>
        <link>https://medium.com/@sebastianscotti?source=rss-8c8e233e4ade------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9-s-i0wGMSSIG_kJrpp4VQ@2x.jpeg</url>
            <title>Stories by Sebastian Scotti on Medium</title>
            <link>https://medium.com/@sebastianscotti?source=rss-8c8e233e4ade------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 01:53:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sebastianscotti/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[A Kubernetes Tale: Part II — Gotta Kubernetise ’em all]]></title>
            <link>https://sebastianscotti.medium.com/a-kubernetes-tale-part-ii-gotta-kubernetise-em-all-61d30dc45a3d?source=rss-8c8e233e4ade------2</link>
            <guid isPermaLink="false">https://medium.com/p/61d30dc45a3d</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Sebastian Scotti]]></dc:creator>
            <pubDate>Wed, 25 Nov 2020 12:18:37 GMT</pubDate>
            <atom:updated>2020-11-25T12:18:37.360Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Kubernetes Tale: Part II — Gotta Kubernetise ’em all</h3><h4>Make your application join the grown-ups table</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GH6WZ80Vo3K7ZYae" /><figcaption>Photo by <a href="https://unsplash.com/@andrewtneel?utm_source=medium&amp;utm_medium=referral">Andrew Neel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You got your Docker image ready. Now how do you run it? Pods? ReplicaSets? Services? Fear no more, here comes the cavalry.</p><p>This is a series of 5 articles. If you want to check Part I, follow the following link:</p><p><a href="https://medium.com/@scotti.sebastian/a-kubernetes-tale-part-i-building-your-java-project-2ee884ea06b4">A Kubernetes Tale: Part I — Building your Java project</a></p><p>I’ll try to make this as clear as possible because there are a few steps to follow that might seem a lot the first time. There are three big steps as listed below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XNf0pUdLM9udx4duPdi90g.png" /></figure><p>Throughout this article, I consider that you have a basic knowledge of how Kubernetes works and the different components that are involved. If you don’t know enough about it, some time ago I wrote an article where I describe it all. Feel free to check it out too 👇</p><p><a href="https://sebastianscotti.medium.com/11-minutes-away-from-kubernetes-36f355c6c506">11 minutes away from Kubernetes</a></p><h3>Before starting</h3><h4>The code 👾</h4><p>You can find all the code used throughout this article in this repository:</p><p><a href="https://github.com/sescotti/dockeriser/tree/part-2">sescotti/dockeriser</a></p><h4><strong>The costs 💸</strong></h4><p>To give you a rough idea, while writing this article, I “spent” £0.30, and I forgot to turn off the Nodes at night. I “<em>spent”</em> because as I’m also using GCP’s free trial, I didn’t really pay anymoney.</p><h3>Setting up the environment</h3><p>If you come from Part I, all you have is a Docker image in your local repository you can run with a simple command. But to run that same image in your Kubernetes cluster requires some extra configuration, more concretely:</p><ol><li>A Kubernetes cluster — because, duh</li><li>A Container Registry — a place to push your Docker images so they’re accessible from your cluster (unless you want your clusters to pull the images from your computer, which I don’t know what about you, but doesn’t sound like a good idea to me)</li><li>A credit card — because knowledge is free, but the servers where you’ll run you code aren’t (don’t panic, you’ll still have for your Christmas presents)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rw04kBAfQzmBe0-FEIFAxQ.png" /></figure><h4>Create the cluster</h4><p>First, sign-up on GCP and follow the steps to start your free trial (if you choose AWS/Azure you’re on your own today, mate). No instructions for this part, you Google “<em>gcp”</em> and literally the first result that comes back is “GCP — Get started for free”. There you go, point number 3 already done. Easy, right?(something that requires your money always is).</p><p>In the <a href="https://console.cloud.google.com/kubernetes/add">Kubernetes Engine cluster creation page</a> (enable the service API if necessary) you can tweak multiple aspects of the cluster configuration. If you don’t want to think just click the <em>My first cluster</em> quick configuration which seems quite quirky if you’re a bit lost with all the buttons and knobs. Now, if you want to work for like 3 mins, to keep costs down for the test I suggest you use this config:</p><ul><li><strong>Zonal</strong> cluster on <strong>us-central1 </strong>region— one of the cheapest regions where the VMs (Nodes) will be created. Within that region, pick whichever zone you like. This means you’ll have your cluster in only one zone from that region.</li></ul><blockquote>While choosing any region might be fine for an initial test, a production cluster might require that you deploy it in specific areas (i.e.: in Europe, after GDPR was introduced, companies are required to process their users data in datacenters located in the continent). Here you can find the full list of GCP <a href="https://cloud.google.com/compute/docs/regions-zones">regions and zones</a>.</blockquote><ul><li><strong>Stable</strong> release channel — v1.16.13 at the time of writing this article. This option here is entirely up to you: <strong>auto-upgrades</strong> could break your releases without your knowledge and you could realise at the worst time possible (been there, done that). The alternative option is to select a master <strong>static version</strong> and you’ll be responsible of doing the upgrade. Here you have the latest <a href="https://cloud.google.com/kubernetes-engine/docs/release-notes">release notes</a>.</li><li><strong>Preemptible</strong> <strong>e2-small</strong> <a href="https://cloud.google.com/compute/docs/machine-types#e2_shared-core_machine_types">machine type</a> — you get a fraction (25%) of 2 vCPUs and it might get bursts of up to 2 full vCPUs for short periods; also as they’re preemptible, they live up to 24hs and offer no availability guarantee. So using it for testing…good. Using it for production…bad.</li><li>Single NodePool with <strong>1</strong> <strong>node</strong> with a <strong>10GB</strong> (minimum allowed) boot disk — you can resize the NodePool and add/remove nodes later.</li></ul><p>Hit <strong>Create</strong> and you’re golden! Wait for a few minutes until it’s fully provisioned. In the meantime, there are some other things to do. Point number 2 done!</p><p>If you’re a terminal person, just run this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/daac53d6a878dae8e0237c7a5da1a6f5/href">https://medium.com/media/daac53d6a878dae8e0237c7a5da1a6f5/href</a></iframe><h4>Link your terminal with your GCP account</h4><p><em>Optional, but recommended</em></p><p>There are three ways to communicate with Kubernetes API:</p><ul><li>CLI</li><li>REST API or</li><li>GCP’s web console</li></ul><p>Anyway, we’re going to use…yes, you guessed right, the <strong>CLI</strong>.</p><p>To do this, we first need to link our terminal with our GCP account. Download <a href="https://cloud.google.com/sdk">gcloud SDK</a> and follow the instructions to set it up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*aPuSkzvHnMdOSKeX3JWSgg.png" /></figure><p>Just so you know, GCP also offers something called <a href="https://cloud.google.com/shell">Cloud Shell</a>, which gives you a shortcut to all your Cloud resources. If you feel like it, just go to the top menu bar and click on the terminal-like icon. I prefer my local terminal because it’s faster and it’s handy if I need to use files from my computer.</p><h4>Connect to your brand new cluster</h4><p>Once your cluster is created, you’ll have a <em>Connect</em> button that will open a pop-up with a command to link your terminal to it: copy and paste it in your terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OT5_jxl5KliPud8x8iwDHw.png" /><figcaption>This is how your cluster should look like on the list.</figcaption></figure><blockquote><strong>Pro tip</strong>: when you have a long list of clusters, it’s good to create aliases for all of them, so you don’t need to go back and forth to this page again.</blockquote><figure><img alt="Once you run the connect to the cluster, you’ll see a message saying that kubeconfig was correctly configured" src="https://cdn-images-1.medium.com/max/1024/1*nNBENwkgGxcY3d1Ex2JKYw.png" /><figcaption>Once you run the command, you’ll see something like this, meaning that the connection was successful</figcaption></figure><h4>Setting up a container registry access</h4><p>Originally I started writing this part here but finally decided to write its own article. Follow this link below to find out all about it 👇</p><p><a href="https://sebastianscotti.medium.com/understanding-google-container-registry-in-gke-312eae6f6ce7">Integrating Google Container Registry with GKE</a></p><h3>Creating the deployment</h3><p>Everything in the previous sections was a one-off thing. Now, what follows, is a configuration that you’ll have to do each time you want to deploy a new application to your cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YDvsdUWQJkt5QBs2093eeg.png" /><figcaption>The dotted lines are optional and will depend on the needs of the deployment</figcaption></figure><h4>Pushing to the Container Registry</h4><p>If you’re doing this for the first time, you will first require to authenticate Docker against GCR. Remember that we gave our cluster access to it to pull images? Well, in this case we need to do the same, using our User Account to push said images. Luckily, <strong>gcloud</strong> provides a helper to do this in no time, just by running:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a5b56f35954979762861bd1b1a7e027/href">https://medium.com/media/9a5b56f35954979762861bd1b1a7e027/href</a></iframe><p>If you try to push without running the command above first, you’ll get an error message like:</p><pre>unauthorized: You don&#39;t have the needed permissions to perform this operation, and you may have invalid credentials. To authenticate your request, follow the steps in: <a href="https://cloud.google.com/container-registry/docs/advanced-authentication">https://cloud.google.com/container-registry/docs/advanced-authentication</a></pre><p>Once Docker is configured, you’ll need to tag and push your Docker image with a GCR URL. How? Like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d24cf53544e4eb43eeff22d89b2a97db/href">https://medium.com/media/d24cf53544e4eb43eeff22d89b2a97db/href</a></iframe><blockquote><strong>One important point here</strong>: it’s quite obvious, but you need to use the same GCR region domain you set up the Image Pull Secret in the cluster. Otherwise, you’ll be able to push, but the cluster won’t be able to pull as it won’t have the credentials configured for that domain (in the example in <a href="https://sebastianscotti.medium.com/understanding-google-container-registry-in-gke-312eae6f6ce7"><em>Setting up the container registry</em></a>, I used <strong>us.gcr.io</strong>).</blockquote><p>The first time you run this it’ll have to push all the layers so it’ll take longer, depending on your Internet connection, your location and the location of the GCR region you chose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OFY8fw_F3ldu6vZycu3hNg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iF_gYeHORQ6Nr6Jh-Xnsmw.png" /><figcaption>On the left, you can observe how the <strong>image</strong> will appear under the <a href="https://console.cloud.google.com/gcr/images/"><strong>Container Registry</strong></a>. On the right, it’ll show how it’s actually stored in <a href="https://console.cloud.google.com/storage/browser"><strong>Cloud Storage</strong></a>: the many files there are the different <strong>layers</strong> of your image.</figcaption></figure><h4>Create a Service</h4><p>This is the part that can vary, because the type of Service that you create depends entirely on how you’re planning to use it. If you’re unsure, check <a href="https://sebastianscotti.medium.com/11-minutes-away-from-kubernetes-36f355c6c506">my article</a> where I explain the differences between the different types. In this case, I’m going to create a headless service.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acb7b63724b23f4ab2729bc41e1b4168/href">https://medium.com/media/acb7b63724b23f4ab2729bc41e1b4168/href</a></iframe><p>The definition is quite straightforward: listen on the port 8080 and redirect to the Pods that have a label with key <strong>app</strong> and value <strong>dockeriser</strong>, and target their 8080 ports.</p><p>To apply it, run <strong>kubectl apply -f service.yaml</strong></p><h4>Create ConfigMap and Secrets</h4><p><em>Optional</em></p><p>There could be the rare occasion where you don’t need either of these (hence the <em>Optional</em> sign above) but it’s quite standard configuration management practice to have them. These two resources are almost the same, except that, as you can imagine, one will be in charge of holding sensitive information (guess which!).</p><p>We can create a simple <strong>ConfigMap</strong> to store, let’s say, the environment name, which could later be used to tweak the internal configuration of the app. Add this to your cluster by running <strong>kubectl apply -f configmap.yaml</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30a5c43e5965794849d2fd9ff623fde4/href">https://medium.com/media/30a5c43e5965794849d2fd9ff623fde4/href</a></iframe><p><strong>Secrets</strong> have a special treatment though, as its information needs to be encoded in base 64. Let’s say we had to handle our credentials to connect to a database with username and password, here it’s what it’d look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4085f06eeb078f99f93bb39c2304eb27/href">https://medium.com/media/4085f06eeb078f99f93bb39c2304eb27/href</a></iframe><p>Again, simply add it to your cluster by running <strong>kubectl apply -f secret.yaml</strong></p><p>Now, if you’re wondering: <em>“OK, this looks fine, but this means that I’ll have my username and password exposed in my source code”,</em> you’re right. This is a topic for the third part of this series using Helm Secrets (which in turns delegates the encryption at rest to Sops). Stay tuned.</p><p><a href="https://github.com/mozilla/sops">GitHub - getsops/sops: Simple and flexible tool for managing secrets</a></p><h4>Putting it all together: Creating the Deployment</h4><p>I’m going to deploy the same application I created in <a href="https://sebastianscotti.medium.com/a-kubernetes-tale-part-i-building-your-java-project-2ee884ea06b4">Part I</a>, only that I tweaked it slightly to show how <strong>ConfigMaps</strong> and <strong>Secrets</strong> can be consumed from within the app.</p><p>Also, Kubernetes needs to know when it can start sending traffic to our new Pods; and then, over time, keep checking the the Pods health to understand if they can receive traffic and ultimately, if they need to be restarted.</p><p>So far we know that:</p><ul><li>(1) The Pods need to labeled with <strong>app=dockeriser</strong> so they’re reachable through the <strong>Service</strong></li><li>(2) The Pod will need a <strong>private key Secret </strong>to gain access and pull the images from our private Container Registry</li><li>(3) The image will be stored in <strong>us.grc.io/my-awesome-project/dockeriser</strong></li><li>(4) The application needs to listen on the <strong>8080 port</strong></li><li>(5) We need to read the DB’s credentials from the <strong>Secret</strong></li><li>(6) We need to read the environment name from the <strong>ConfigMap</strong></li><li>(7) The container needs to provide an endpoint to determine if it’s ready to receive traffic</li><li>(8) The container needs to provide an endpoint to determine if it’s still alive</li></ul><p>You can see below how each point is expressed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40132eca613e30236c9efb7eaada1f60/href">https://medium.com/media/40132eca613e30236c9efb7eaada1f60/href</a></iframe><p>Just like before, run <strong>kubectl apply -f deployment.yaml </strong>. Wait a few seconds, and if you did it right, you should see two Pods with a name starting with <strong>dockeriser </strong>, when you run <strong>kubectl get po </strong>.</p><blockquote>The random characters in the Pod name? They’re simply <br>[deploy-name]-[replicaset-id]-[pod-id]</blockquote><p>A few clarifications on the spec above:</p><ul><li>If you check out <em>line 8</em>, I configured this deployment to have two replicas — you can use the number that makes sense for you.</li><li>The label <strong>app=dockeriser</strong> in <em>line 5</em> is added to the Deployment — simply to earmark it; whilst the one in <em>line 11</em> tells the Deployment which Pods to overlook.</li><li>The numbers (timeouts, delays, etc) for both <em>liveness</em> and <em>readiness</em> probe depend exclusively on the application and the hardware where it’s running — play with it until you hit the spot.</li><li>The environment name, DB user and password are passed onto the container as environment variables, ready to be used by your application.</li></ul><p>Now, I modified slightly the launcher of my application to demonstrate how to grab these from your application (as framework/language-agnostic as possible). In case you want to see how to grab this in a more Spring-able fashion, check out <a href="https://github.com/sescotti/dockeriser/blob/part-2/src/main/resources/application.yaml">applications.yaml</a> file, consumed from <a href="https://github.com/sescotti/dockeriser/blob/part-2/src/main/kotlin/com/example/dockeriser/EnvironmentProperties.kt">EnvironmentProperties</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c3190f4b8d287c14209ea0c3e5b8b91/href">https://medium.com/media/5c3190f4b8d287c14209ea0c3e5b8b91/href</a></iframe><p>Capturing the logs, you can see that it prints the following line:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_DQDZfl99_-taJMpV1EQwg.png" /></figure><blockquote><strong>A bit of homework</strong>: it’s recommended that you specify the resources your application will need (and the limits), because Kubernetes’ scheduler will probably evict these Pods if your Nodes are running low on CPU/RAM. Setting the right values can avoid this situation. Check out <a href="https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#requests-and-limits">this page</a> to find out more.</blockquote><h3>Wrapping up</h3><p>Now, let’s verify that everything works correctly. First let’s list our running Pods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m_eb4CFWB1uBTccjE4zB-A.png" /><figcaption>Run <strong>kubectl get pods -o wide</strong> to get a nice overview of your running Pods</figcaption></figure><p>From the screenshot above, you can see that our Pods are available (inside the cluster) on the IPs <strong>10.56.0.52 </strong>and <strong>10.56.0.53</strong>. These are the IPs the Service should use to redirect the traffic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*7rfs4tpU-aT3PRqsb3c7aw.png" /><figcaption>We can see that when requesting the state of our Service, it contains our two Pods with their corresponding ports.</figcaption></figure><h4>Testing the deployment</h4><p>First of all, let’s <a href="https://gc-taylor.com/blog/2016/10/31/fire-up-an-interactive-bash-pod-within-a-kubernetes-cluster">start a simple Pod</a> to test the service and verify that it’s working correctly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c901f4615b8a3e8ae9501c7e92925836/href">https://medium.com/media/c901f4615b8a3e8ae9501c7e92925836/href</a></iframe><p>This will spin up a Pod running an Ubuntu image and will link your terminal to that running instance (if you exit it, the Pod will be destroyed). Once you’re connected, install <strong>curl</strong> by running <strong>apt-get update &amp;&amp; apt-get install -y curl </strong>. The headless Service we created uses its name (<em>dockeriser-headless-service</em>) as hostname, so we can use it like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*8OuT5ox5m5tZgf8DCHYqEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7p9u9h6czRsCoAl7wqiGbg.png" /><figcaption>If you hit it multiple times, you should see that the responding IP changes</figcaption></figure><p>And that’s it! Now you have your application running on your Kubernetes cluster. Just remember to delete the cluster to avoid getting unnecessary charges!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28c4900157c9c572035f9b120c331dfc/href">https://medium.com/media/28c4900157c9c572035f9b120c331dfc/href</a></iframe><p>Or if you only have one cluster (you’ll not be charged for it) in your billing account, just resize it to 0 nodes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0113f7b311ba34a21a67879505a19f6/href">https://medium.com/media/b0113f7b311ba34a21a67879505a19f6/href</a></iframe><h3>One last word</h3><p>If you liked this article, follow me to get notified when I publish the next parts! Next stop: Helm.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61d30dc45a3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Google Container Registry with GKE]]></title>
            <link>https://sebastianscotti.medium.com/understanding-google-container-registry-in-gke-312eae6f6ce7?source=rss-8c8e233e4ade------2</link>
            <guid isPermaLink="false">https://medium.com/p/312eae6f6ce7</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Sebastian Scotti]]></dc:creator>
            <pubDate>Sat, 21 Nov 2020 18:50:47 GMT</pubDate>
            <atom:updated>2020-11-23T19:29:45.847Z</atom:updated>
            <content:encoded><![CDATA[<h4>Dissecting how to securely store your images and configure access from your cluster</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FjmssjzmRHPx9_6R" /><figcaption>Photo by <a href="https://unsplash.com/@chuttersnap?utm_source=medium&amp;utm_medium=referral">CHUTTERSNAP</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>So you managed to push your Docker images to the Container Registry, but you’re getting a dreaded <strong>ImagePullBackoff</strong> error when your Pods are trying to start. Even though there are several reasons that could make this happen (i.e.: a typo in your YAML files), it could simply be that your cluster is lacking the permissions to fetch them. On GCP, by default, <a href="https://cloud.google.com/container-registry/docs/using-with-google-cloud-platform#gke-permissions">clusters have access to the Container Registry automatically</a> <strong>if both are in the same GCP project. </strong>But if you have to access images from other projects or you chose another provider, that’s another story. Enter <strong>imagePullSecrets </strong>.</p><h3>Setting up a container registry access</h3><p>Before getting to any specifics, you must know that a Kubernetes cluster has two ways of choosing how to authenticate with a private Container Registry:</p><ul><li>By using a service account</li><li>By using the key specified by the Pod</li></ul><p>Both of these methods require that we first add them to the cluster, using a <strong>Secret</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ihmzTpcnOdbx5v-iMmWe-Q.png" /></figure><p>We’re going to use GCP’s Container Registry (from now on, simply GCR), so we only need to give our cluster permission to access it. This step is three-folded, since we need to:</p><ol><li>Generate a <strong>service key</strong>, that will allow the cluster to pull the images from this repository;</li><li>Store that key in the cluster — using a <strong><em>Secret</em></strong>;</li><li><a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/#add-imagepullsecrets-to-a-service-account">Tell the default S<em>erviceAccount</em> where’s the secret</a> so it uses it when pulling an image from GCR; or <a href="https://kubernetes.io/docs/concepts/containers/images/#referring-to-an-imagepullsecrets-on-a-pod">configure your Pod to do the same</a>.</li></ol><h4>Generate a service key</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MvLOLl0c_gts5B6GC_TnRQ.png" /></figure><p>In your GCP web console, Go to <a href="https://console.cloud.google.com/iam-admin/serviceaccounts">IAM &gt;&gt; Service Accounts</a> and create a new one with a name that’s clear. On the Roles selection page, select <strong>Storage Object viewer</strong><em>. </em>Why? Because Google Cloud Storage is the underlying backend used to store the images, and that role enables the user to read the files from those buckets. <strong>Remember: this service account will only be used for this and you want to limit the access as much as you can.</strong> This is known as <a href="https://en.wikipedia.org/wiki/Principle_of_least_privilege">Principle of Least Privilege</a>. So don’t reuse this service account for anything else and don’t modify its privileges. Step 1 done.</p><blockquote><strong>Pro tip</strong>: if you want to make it even more restrictive, you can go further and limit this Service Account to only access the images specific bucket. In order to use this option, the bucket needs to enable <a href="https://cloud.google.com/storage/docs/using-uniform-bucket-level-access">Uniform bucket-level access</a> (which overrides the default ACLs). When you’re creating the service account, click “Add Condition” and type:</blockquote><pre>resource.type == &quot;storage.googleapis.com/Bucket&quot; &amp;&amp;<br>resource.name.startsWith(&quot;projects/_/buckets/&lt;docker-images-bucket-name&quot;)</pre><p><a href="https://cloud.google.com/iam/docs/conditions-resource-attributes">Resource attributes for IAM Conditions | Cloud IAM Documentation</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hGtMRWSH9r8CKMryNzgt7g.png" /></figure><p>Once it’s created, select <strong>Create Key</strong> and pick <strong>JSON</strong> as format, which will be downloaded to your computer. <strong>This file is literally the key to all the Docker images you upload, so store it safely! </strong>Before moving forward, open it with a text editor and take your time to familiarise yourself with its content.</p><h4>Storing the key in the cluster</h4><p>For the next stop simply run:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd540d03fc6def0d31686ee9538fa102/href">https://medium.com/media/bd540d03fc6def0d31686ee9538fa102/href</a></iframe><p>This will create a Secret with all the necessary information. If you want the full list of available Docker servers, <a href="https://cloud.google.com/container-registry/docs/pushing-and-pulling">check this page</a>. Step 2 done.</p><blockquote><strong>Pro tip</strong>: I chose a US Docker server because the cluster I created is also in the US, so there are <a href="https://cloud.google.com/storage/pricing#network-buckets">no cross-region network Egress costs</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yb8jNgegwC2Id6WzdZmpKQ.png" /><figcaption>With the <strong>kubectl get secrets</strong> command you can see it was correctly created.</figcaption></figure><p>Now that it’s registered, remember there are two ways of consuming it:</p><ul><li>Configuring the default ServiceAccount</li><li>Configuring the Pod spec</li></ul><p>To me (and according to the <a href="https://kubernetes.io/docs/concepts/containers/images/#specifying-imagepullsecrets-on-a-pod">official Kubernetes docs</a>), the second option is the preferred way when dealing with private registries. In my opinion, mainly because it allows you to have a more granular control over how each Deployment should pull the images. Bear in mind that this will require that each new Deployment will need to define the name of the secret to use.</p><h4>Configuring the default ServiceAccount</h4><p>If you execute the describe command on the default Service Account (sa is a shortcut for serviceaccount), you’ll see that the <strong>Image pull secrets</strong> field is empty. This is the field the Service Account will use to know where to grab the key from when it creates the Pods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*nl0vaxjLUcVrRJlVCREBkw.png" /><figcaption><strong>kubectl describe serviceaccount default </strong>will print</figcaption></figure><p>Now it’s just a matter of telling the default Service account to use the content of the <strong>gcr-json-key</strong> secret when pulling Docker images, simply by doing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/550ac504571bf2edc427e8e101e73eac/href">https://medium.com/media/550ac504571bf2edc427e8e101e73eac/href</a></iframe><p><a href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/#add-imagepullsecrets-to-a-service-account">Configure Service Accounts for Pods</a></p><h4>Configuring the Pod spec</h4><p>If you take a look at line 18 and 19 in the file below, you’ll see that I just modified my <strong>deployment.yaml</strong> file to specify what secret it should use to pull images. The other advantage of this method is that it allows you to specify multiple secrets (i.e.: if you have a multiple container Pod, and each image is located in a different registry)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8918b631c031a28ef6c8960e65a2b0e3/href">https://medium.com/media/8918b631c031a28ef6c8960e65a2b0e3/href</a></iframe><p>If you want to know a bit more about multi-container Pods, you can check out the following article:</p><p><a href="https://medium.com/better-programming/understanding-kubernetes-multi-container-pod-patterns-577f74690aee">Understanding Kubernetes Multi-Container Pod Patterns</a></p><h3>Going the extra mile</h3><p>By default, Kubernetes doesn’t provide an encryption layer for Secrets so it relies on the provider for this. GCP provides by default <a href="https://cloud.google.com/security/encryption-at-rest/default-encryption">encryption at rest</a> in the Infrastructure layer, and also (optionally) in the application layer, using <a href="https://cloud.google.com/security-key-management">KMS</a>.</p><p>To enable this in your cluster, you just have to specify an encryption key. To do this, in your terminal, run:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0dbb40b62b84bd40c3aa3830ea70895/href">https://medium.com/media/b0dbb40b62b84bd40c3aa3830ea70895/href</a></iframe><p>This will create a KeyRing, it’s just a logical grouping of multiple keys to facilitate its management. Next step is to add a key to it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d07646565a4f5a0df1d045459aa4f24c/href">https://medium.com/media/d07646565a4f5a0df1d045459aa4f24c/href</a></iframe><p>Once this is done, you’ll have to give allow the default service account to access this key to encrypt/decrypt the secrets</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10385ba77503a1e98f989bfb34d861e4/href">https://medium.com/media/10385ba77503a1e98f989bfb34d861e4/href</a></iframe><p>Finally, just tell the cluster to start using it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce2bcfd413996d855eb2c87ddca2dbff/href">https://medium.com/media/ce2bcfd413996d855eb2c87ddca2dbff/href</a></iframe><p>This last step might take a while, so sit back and relax until it’s complete.</p><p>One last word on this topic: this key is now critical for the operation of your cluster. If you delete the key, your cluster will become virtually useless — you won’t be able to access your encrypted information again, so no upgrades, no rollacks, no nothing. You know what <a href="https://youtu.be/_5d6rTQcU2U?t=87">Uncle Ben said</a> for a situation like this.</p><p><a href="https://cloud.google.com/kubernetes-engine/docs/how-to/encrypting-secrets">Encrypting secrets at the application layer</a></p><h3>Bonus track</h3><p>We pretty much covered everything but I thought I’d leave you with an extra, that’s not really necessary, but can save you from trouble.</p><p>Recently I had to migrate a whole lot of projects running on Kubernetes to use a private container registry in <strong>eu.gcr.io</strong> instead of <strong>gcr.io</strong> (again, because of cross-region egress costs), and I didn’t want to create another secret for this new domain because it’d mean that I had to also update all the <strong>deployment.yaml</strong> files. Inspecting the contents of the <strong>gcr-json-key</strong> Secret, I noticed this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d1e16f874f8a106555de6fbebf6543b/href">https://medium.com/media/7d1e16f874f8a106555de6fbebf6543b/href</a></iframe><p>As you can see, the command we run when we created the Secret, contains a base64 encoded version of a JSON file with a map, which key is the domain of the container registry. This means that I should be able to add the same credentials, only for a different domain. <a href="https://stackoverflow.com/a/62461927/2049282">With a little help of StackOverflow</a>, I found a simple way to do this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b682fd871072900ff8f8252a54ce628c/href">https://medium.com/media/b682fd871072900ff8f8252a54ce628c/href</a></iframe><p>That’s it! Hope you enjoyed the article and, most importantly, that it helps you understand a little bit better how to integrate these two platforms.</p><p>If you enjoyed this article, take a look at my others!</p><ul><li><a href="https://sebastianscotti.medium.com/11-minutes-away-from-kubernetes-36f355c6c506">11 minutes away from Kubernetes</a></li><li><a href="https://sebastianscotti.medium.com/a-kubernetes-tale-part-i-building-your-java-project-2ee884ea06b4">A Kubernetes Tale: Part I — Building your Java project</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=312eae6f6ce7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[11 minutes away from Kubernetes]]></title>
            <link>https://sebastianscotti.medium.com/11-minutes-away-from-kubernetes-36f355c6c506?source=rss-8c8e233e4ade------2</link>
            <guid isPermaLink="false">https://medium.com/p/36f355c6c506</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[container-orchestration]]></category>
            <dc:creator><![CDATA[Sebastian Scotti]]></dc:creator>
            <pubDate>Mon, 10 Aug 2020 11:41:03 GMT</pubDate>
            <atom:updated>2020-08-10T11:41:03.921Z</atom:updated>
            <content:encoded><![CDATA[<h4>A hyper-condensed 101 of the container orchestration platform in plain(ish) English to hit the ground running</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NsDAB2N4WQSnYWJO" /><figcaption>Photo by <a href="https://unsplash.com/@gwundrig?utm_source=medium&amp;utm_medium=referral">Manuel Nägeli</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>So you’ve heard about Kubernetes, you know it’s something about clusters, high availability and…deployments?. But every time you hear about a new technology you say to yourself <em>“Oh, here we go again. Another whole pack of documentation pages that will take me ages to read until I can have </em><strong><em>something</em></strong><em> working and I don’t even know if it’s worth the effort”</em>. I said that. A million times. And I’ll surely keep doing it. So this should be a super-packed doc that will give you a slightly more than basic understanding of the platform, and hopefully give you an idea if it’s the thing for you. You’re just 11 minutes away from it. Here we go.</p><p>According to their official website, they say:</p><blockquote><a href="https://kubernetes.io/docs/concepts/overview/what-is-kubernetes/">Kubernetes (K8s)</a> is an open-source system for automating deployment, scaling, and management of containerized applications.</blockquote><p>I think it’s a short yet simple definition. The most common containerisation platform used in Kubernetes is <a href="https://docs.docker.com/get-started/">Docker</a>. So this article will start with a simple Docker image, and explain the different moving parts on a Kubernetes cluster that will allow you to deploy and run your application, scale it and manage it.</p><p><em>Never used Docker? Check out below the first part of an article series I wrote to run a project on Kubernetes, where I give a brief practical explanation of Docker and how it can be used. The example is using a Java Spring Boot application, but a lot of the principles/practices dictated in the article can be extrapolated to other languages/frameworks.</em></p><p><a href="https://medium.com/@scotti.sebastian/a-kubernetes-tale-part-i-building-your-java-project-2ee884ea06b4">A Kubernetes Tale: Part I — Building your Java project</a></p><h3>The basics</h3><p>For starters, if you’ve never heard of the term <strong>cluster</strong>, just think about it as a group of computers working as a unit, with some processes that coordinate the communication and actions between all these computers, or <strong>nodes</strong>. The process of managing this and the workloads operating in the cluster is called <strong>orchestration </strong>(as in <em>Kubernetes is an open-source container-orchestration system for…</em>).</p><p>To understand the basics of the architecture, think of it as a <a href="https://en.wikipedia.org/wiki/Matryoshka_doll"><em>matryoshka</em></a><em> </em>(at least it helped me, I’m kind of a visual type of person).</p><h4>Orchestrating the workload</h4><figure><img alt="The application container is wrapped in a Pod, that smallest computing unit managed by Kubernetes" src="https://cdn-images-1.medium.com/max/300/1*D9H4UPrfrqwyDbdSHA0C5Q@2x.png" /></figure><p>First of all, your container (the one that hosts and runs your Docker image) will run on a <strong>Pod</strong>. This is the smallest unit of your workload managed by Kubernetes — think of it as the logical units, the <em>instances</em>, of your application. Each Pod can have one or more containers. The idea is that Pods are disposable and you don’t manage them directly: instead you manage a controller that will be in charge of maintaining a given number of these. These Pods contain an ephemeral storage drive attached to it, that will be destroyed when the Pod is destroyed. How can they be disposable? Because you will have a specification (simply called <strong>spec</strong>) that will tell Kubernetes exactly how its containers should start, so if one dies, there will be another one just like it ready to be fired up.</p><p><a href="https://kubernetes.io/docs/concepts/workloads/pods/">Pods</a></p><figure><img alt="To avoid managing individual Pods, workloads are organised in ReplicaSets and Deployments" src="https://cdn-images-1.medium.com/max/1024/1*d2Y-xkCrDAfWultC6pZU2w.png" /><figcaption>Containers are run in Pods, a ReplicaSet is in charge of ensuring a given number of them are running at any point in time. The Deployment orchestrates all the necessary steps to start and have running the Pods.</figcaption></figure><p>Now it’s the part where you say “<em>What the…? Where did all those boxes come from? This was supposed to be simple!”. </em>You may say it to yourself. Or even out loud. And your dog may stare at you not really understanding what’s going on. The <strong>Deployment</strong>: this is the place where you tell Kubernetes how to run your Pods (what containers they’ll have, which Docker image to use, how many resources to allocate, which configuration variables to pick), how many instances you want to spawn (and how to assess their health), etc. <strong>In other words, where you’ll define the spec</strong>. On the other hand, the <a href="https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/"><strong>ReplicaSet</strong></a> is the responsible of ensuring that the desired number of Pods (“<em>replicas</em>”) are running at any point in time and restarting/replacing them if necessary. It’ll also have for instance the strategy with which the Pods should be replaced when rolling out a new version (i.e.: at least 50% of the new version should be deployed before terminating the Pods of the old version).</p><blockquote>When creating a Deployment, a ReplicaSet is automatically generated to satisfy the replication requirements. It’s also possible to manually create a ReplicaSet, although it’s not recommended.</blockquote><p><a href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/">Deployments</a></p><figure><img alt="The service is the method by which the requests from outside of your workload are routed to your Pods" src="https://cdn-images-1.medium.com/max/1024/1*bhbMZyWnQqUlkM1x6wcGVA.png" /></figure><p>Yes, I know, now you’re going something like: <em>“Seb, this is so far the most beautiful yet simple explanation of Deployments in Kubernetes I’ve ever seen in my life…but I got lost already, how the **** am I supposed to access my API with all these layers? I just want to run a simple curl like in the ol’ days”.</em> <a href="https://kubernetes.io/docs/concepts/services-networking/service/">Enter the <strong>Service</strong></a>. This little fella will be the one exposing your Pods to the “outside”. Why the quotes? Because the “outside” can vary depending if the requests come from within or outside the cluster, and so will the type of Service you’ll use:</p><ul><li><strong>ClusterIP </strong>— your service will only be accessible from within the cluster. It will have an allocated IP which you can use to contact your application.</li><li><strong>NodePort </strong>— your service will be exposed on a static port on each Node port, accessible outside the cluster.</li><li><strong>LoadBalancer</strong> — the cluster requests a Load Balancer to the cloud provider, in the form of a static IP (extra charges might apply here). This means it’s accessible outside the cluster too.</li><li><strong>ExternalName </strong>—<strong> </strong>creates a <a href="https://en.wikipedia.org/wiki/CNAME_record">CNAME record</a> in Kubernetes’ internal DNS (for example subdomain.domain.com) that will “override” the real DNS record (only within the cluster). For instance, let’s say you’re migrating your workload from your own datacenter and you normally access your DB on db-01.example.com, and before migrating all of it to Kubernetes, you want to migrate only the test environment so you deploy the DB in your cluster. You don’t need to change your application code: just by creating an ExternalName service all the requests will be properly re-routed to the new instance.</li></ul><figure><img alt="Example of how an ExternalName service overrides DNS resolution within the cluster" src="https://cdn-images-1.medium.com/max/1024/1*VstjSwMfXeuG026XWAJHwg.png" /><figcaption>In the cluster on the left there’s no <strong>ExternalName</strong> service created, hence, the requests to <strong>db-01.example.com</strong> will resolve normally. In the cluster on the right, the Service is created so the same domain will resolve internally.</figcaption></figure><ul><li><strong>None</strong> — this is called a “<em>headless</em>” service: it’s actually a <strong>ClusterIP</strong> service type with no clusterIP (if that makes sense?). It’s used in cases where you might need explicitly all the Pod IPs (one classic example is MongoDB, where the connection URLs on the client side requires all the instances IPs).</li></ul><figure><img alt="A headless Service will generate A records for all the Pod IPs it’s serving, under a domain name matching the Service name" src="https://cdn-images-1.medium.com/max/944/1*xTRYpoXwpuu6AsDZTQdn0Q.png" /><figcaption>An example of <em>A records</em> automatically configured by the <strong>Service</strong>, pointing to the Pod IPs</figcaption></figure><p>It creates <em>type A</em> DNS records that will resolve under the service name (if you name your service headless, when doing ping headless from any Pod in the cluster, it will resolve one of the Pod IPs).</p><p><a href="https://medium.com/swlh/discovering-running-pods-by-using-dns-and-headless-services-in-kubernetes-7002a50747f4">Discovering Running Pods By Using DNS and Headless Services in Kubernetes</a></p><p>Just one small detail that for the purpose of simplicity I deliberately omitted because of a hard truth: <strong>Services don’t give a crap about your Deployments or ReplicaSets.</strong> They just want to know which Pods to route the incoming traffic to. So in reality, from the point of view of a Service, your cluster looks something like this:</p><figure><img alt="Pods are labeled and Services use these to determine how/where to route the incoming requests." src="https://cdn-images-1.medium.com/max/1024/1*vilPz1GcHTyuDOlV9NQbeQ.png" /><figcaption>A Service uses Pods labels to determine where to route the requests (Yes, the third colour is <strong>indigo</strong>. To me it was just purple, but as it turns out, it’s not)</figcaption></figure><p>So for example, the green service will go: <em>“OK, I received this request, who’s got a label </em><em>app=green? You Pod number 1? There you go buddy. Next!”.</em></p><p>Ok, to summarise what we have so far:</p><ul><li>Pods — the smallest computing unit on Kubernetes. These are the instances of your application.</li><li>ReplicaSet — the controller responsible of ensuring a certain number of Pods running at any point in time.</li><li>Deployment — the orchestra director, organises all the resources so your Pods can run the way you want them to. This will be what you’re going to mainly be working on.</li><li>Service — a bridge to the “outside world”</li></ul><h4>Bonus track: Autoscalers</h4><p>There’s another component called <a href="https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/">HorizonalPodAutoscaler (HPA)</a> that, based on some configurable metrics, can adjust the number of running Pods on a ReplicaSet to serve the incoming requests properly, and this number can fluctuate between previously defined upper and lower bounds. CPU, network packets per second, HTTP requests are just some examples of the metrics you can mix and match. This autoscaling will just affect Pods, so it needs to be complemented by a Node autoscaling, otherwise, depending on the bounds configured, there might not be enough resources to host them properly and some of them might not be scheduled.</p><h4>Configuration objects</h4><p>In order to tell Kubernetes how to run our workloads, there are two main configuration objects that allow us to do that:</p><ul><li><strong>ConfigMaps</strong> — for general configuration</li><li><strong>Secrets</strong> — for sensitive information</li></ul><p><a href="https://kubernetes.io/docs/concepts/configuration/">Configuration</a></p><p>There’s not much more to say about this, both are <em>key-value</em> objects that will keep the data you throw at it. The main difference is that a <em>Secret</em> object will have some further considerations (because we’re talking about sensitive information), for example how you can consume it, when these values will be injected in the Pod lifecycle, etc. By default, Kubernetes doesn’t provide an encryption layer for Secrets so it relies on the provider for this (in exchange, for example, GCP provides by default <a href="https://cloud.google.com/security/encryption-at-rest/default-encryption">encryption at rest</a> in the Infrastructure layer, and also optionally in the <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/encrypting-secrets?_ga=2.260363085.-1376820346.1596014133">application layer</a>).</p><h4>Security</h4><p>Kubernetes has something called <strong>ServiceAccount</strong>, and it’s a way to represent a (machine) user that will be allowed to execute certain operations in the cluster. You can define as many as you want, but usually the <em>default</em> is enough. This Service account can be modified and, for example, be given permissions to read a private Container Registry (the repository where the Docker images that the Pods need will be pulled from) that requires authentication.</p><h4>Kubernetes internal architecture considerations</h4><ul><li>What I described aboved are some of what I call <em>logical</em> components of the cluster. Kubernetes has also the concept of <strong>Nodes</strong> — these in contrast I call them the <em>physical</em> part, which can be bare metal servers, VMs, etc where the Pods will be actually allocated to and consume resources from.</li></ul><figure><img alt="Nodes are organised in NodePools and workloads can be configured to have higher affinity with a NodePool than others" src="https://cdn-images-1.medium.com/max/1024/1*y-nnr6ZFVRPHZEsHtQ9jDA.png" /></figure><ul><li>These Nodes are organised in <strong>NodePools</strong> — they allow you to manage different groups of Nodes that might differ in size, resources, etc within the same cluster. So if you wanted to assign certain workloads to a specific set of Nodes (because for instance, they require more memory than the rest), you could do it with these. Here the concepts of <strong><em>Taints</em></strong> and <strong>Tolerations</strong> apply, to establish <em>Node affinity</em>, but I won’t cover these at this time (tell me in the comments if you want to have an article about this).</li><li><strong>Kubernetes has its own administrative workload,</strong> and that needs to run in your Nodes, so take this into account when sizing the Node pools. The cloud provider you use might add its own services, so that’s another</li><li>Kubernetes organises the objects deployed in the cluster in <strong>namespaces</strong>. These provide another layer of isolation and security, so for instance, it’s possible to restrict access to certain namespaces to some users. By default, all user-generated workload will go to the <em>default</em> namespace, whilst Kubernetes workload belongs to the <em>kube-system</em> namespace.</li></ul><p>Perhaps there are a few things that you’ll not be regularly involved with but that are good to know (useful for an interview when they ask you if you know Kubernetes, you might go like <em>“Oh yeah, I regularly call my cluster’s control pane through its API to optimise the size of my NodePools” </em>because <em>“I replaced that 2 for a 3 in that textbox” </em>doesn’t sound as fancy).</p><p><a href="https://kubernetes.io/docs/concepts/overview/components/">Kubernetes Components</a></p><h3>Stateless vs stateful</h3><p>It’s one of the main differentiators in workloads, and it basically responds to this question: <em>Do I need to keep track of the data stored in this particular Pod?</em>.</p><p>If the answer is no, then you have a <strong>stateless</strong> deployment. Usually this is the case of most APIs, where the only data you could be saving in the storage is temporary/can be replicated from a spec (like logs, environment variables, config files, etc).</p><p>If the answer is yes, well then you guessed right, it’s <strong>stateful</strong>. This means that each Pod will have a sticky ID and besides its ephemeral storage, will have attached a persistent storage that will belong to that Pod in particular. Even if Pods can eventually die and be restarted, the new Pod will take the identity of the deceased Pod (and will reuse the same persistent storage).</p><blockquote>Actually, in Kubernetes a stateless deployment is called <strong>Deployment</strong>; while a stateful deployment is called <a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/"><strong>StatefulSet</strong></a></blockquote><h3>The API</h3><h4>Why an API?</h4><p>The Kubernetes API is a REST API, and as any other API, lets you query and modify the components of your cluster. Every operation executed by a user or a process, whether internal or external, will go through this API.</p><p>The API receives objects to create/update/delete (yes, Deployments, Pods, Nodes, Secrets, etc are represented as objects) and then communicates with the corresponding actor of the control plane to execute the necessary actions.</p><p>As with any other type of objects, these are versioned, allowing evolution in the capabilities of both the API and cluster. These objects are extensible, meaning if you had to, you could create new types on demand.</p><p>You can contact the API as with any other REST API (curl, Postman?) or through the CLI, with a tool called kubectl. It operates mainly in two ways: for example, to create a Deployment you could simply run:</p><pre>kubectl create deploy my-deployment --image=my-app</pre><p>or in an IaC fashion (Infrastructure as Code):</p><pre>kubectl create apply -f my-deployment.yaml</pre><p>The advantage of the latter is that it can be versioned in your source control versioning repository, so it’s easier to track changes as of when who and why they were done. In this case, your Deployment spec will look something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/703e4a0c611a80c5a0c4a15c3a4e2f70/href">https://medium.com/media/703e4a0c611a80c5a0c4a15c3a4e2f70/href</a></iframe><p>It might look like more verbose than the first option, but in the long run you don’t need to remember what commands you executed and it’s easily portable to other applications you might have. <strong>Said in a different way: favour this method.</strong></p><h4>Some other commands examples</h4><p>You can find these on Kubernetes official docs pages, the only reason I’m putting them here is to show how clear they tend to be, so the learning curve here is relatively flat.</p><p><em>Get current running pods</em></p><pre>kubectl get pods</pre><p><em>Get a Deployment details</em></p><pre>kubectl describe deploy my-deployment</pre><p><em>Delete a ReplicaSet</em></p><pre>kubectl delete rs my-replicaset</pre><blockquote>The reason why I use the full name of the object and sometimes a shortened is because Kubernetes has shortcuts for most of the objects. Want to know all of them? Just run kubectl api-resources</blockquote><p><a href="https://kubernetes.io/docs/reference/kubectl/overview/">Command line tool (kubectl)</a></p><p>Intrigued enough to give it a shot? In a few days I’ll release the second part of the series on how to deploy an application with Kubernetes and Helm! If you liked this article, follow me so you can get notified when I release it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36f355c6c506" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Kubernetes Tale: Part I — Building your Java project]]></title>
            <link>https://sebastianscotti.medium.com/a-kubernetes-tale-part-i-building-your-java-project-2ee884ea06b4?source=rss-8c8e233e4ade------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ee884ea06b4</guid>
            <category><![CDATA[circleci]]></category>
            <category><![CDATA[helm]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Sebastian Scotti]]></dc:creator>
            <pubDate>Thu, 30 Jul 2020 22:12:52 GMT</pubDate>
            <atom:updated>2020-07-30T22:12:52.018Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Kubernetes Tale: Part I — Building your Java project</h3><h4>A practical (and somewhat opinionated) guide to kick-off your project with Docker and Helm</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h0f8KMt_FIrW4Z7L" /><figcaption>Photo by <a href="https://unsplash.com/@loik_marras?utm_source=medium&amp;utm_medium=referral">Loik Marras</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Around three years ago while I was working at <a href="https://debut.careers/">Debut</a>, we started using Kubernetes. We made the decision after realising we needed a flexible space to deploy services that were critical for the platform to grow. It was a whole new world of containerisation on top of the already widely famous Docker. From the very beginning I’ve been learning how to tackle many aspects of running a production-ready cluster — this is a little bit of my experience so far that I wanted to share.</p><p>Besides any specific technology, the main points that you can draw out of this series are:</p><ul><li>Building — wrapping a Spring boot application as a Docker-ready image, with a scalable environment-based configuration.</li><li>Running and orchestration — on a Kubernetes cluster</li><li>Configuration management — using Helm to manage releases and secrets</li><li>CI/CD pipelines — using CircleCI</li><li>[Appendix] Monitoring — using New Relic</li></ul><p>The tech stack used for these examples is:</p><ul><li>Spring Boot 2.3 + JDK 11+ Kotlin 1.3* + Gradle 6.4</li><li>Kubernetes 1.15 (on GCP)</li><li>Helm 3.2.4</li><li>New Relic agent 5.9.0</li></ul><p>If in your project you’re using the same stack with different versions, it’s possible that the steps described here will not necessarily work as expected.</p><p>* No real reason to use Kotlin here. You could simply use good ol’ Java. Or you could <a href="https://kotlinlang.org/">try Kotlin</a>. (but only after reading this guide)</p><blockquote>Disclaimer: I actually started this article a year and a half ago, so there might be things that were true back then that are not anymore (like going to the pub for a pint). I doubled-tripled-10xed checked everything but something might have fallen through the cracks.</blockquote><h3>Generating our application</h3><p>Our first step is to create an executable version of our application. In this case, we’ll be creating a Spring Boot application exposed through a REST API. To create an application, you can use <a href="https://start.spring.io/">Spring initializr</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FkN-72Hgsv_ICxXLD_fJdQ.png" /></figure><p>For the purpose of this example, we’ll simply add two dependencies:</p><ul><li>Spring Web: Enabling the application to generate the necessary REST controllers</li><li><a href="https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-features.html">Spring Actuator</a>: Includes a set of production-ready features. We’ll use the health functionality later on.</li></ul><p>Download and open your fresh new project in a terminal. First thing is to check that it runs correctly. To do this go to the directory where you unzipped it and run:</p><pre>./gradlew bootRun</pre><blockquote>Gradlew stands for Gradle wrapper — it allows you to port your project without requiring any Gradle installation in your local environment.</blockquote><p>Once your application starts run a <strong>curl</strong> to check it’s responding correctly. You should see something like this 👇</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8022e28aadda1001cc6b80c0bad86edf/href">https://medium.com/media/8022e28aadda1001cc6b80c0bad86edf/href</a></iframe><p>This endpoint is automatically exposed by Spring actuator. It analyses different the resources the application depends on to provide an easy way of assessing its health: DB access, free disk space, Hystrix circuit breakers, etc. [<em>Spoiler alert: This endpoint will come quite handy for Part II]</em></p><p>Whilst in your local environment you can run Gradle for simplicity, in a Docker image you want to include as few dependencies as possible, so that’s why we’ll have to run it in a different way.</p><h3>Running the application</h3><h4>Running the application standalone</h4><p>To run this application in a Docker container we’ll have to use a fat jar (also known as <em>uber-jar</em>). This is a jar file that contains all our project classes and resources <strong>plus</strong> all its dependencies.</p><figure><img alt="A full list of the subtasks run by the build task: assemble, bootBuildImage, bootJar, build, buildDependents, buildNeeded…" src="https://cdn-images-1.medium.com/max/938/1*awL0wZHdmWNExJmSWcnGrw.png" /><figcaption>A full list of the subtasks run by the <strong>build</strong> task</figcaption></figure><p>When you run the ./gradlew build task it will trigger the <em>build + test + jar</em> subtasks. It actually runs a few more subtasks but you get the gist of it. You can get a full description of these under the little Gradle elephant tab in IntelliJ IDEA.</p><p>If then you check under <strong>build/libs/ </strong>you should see something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf324294624f5b20c6b02f3ff9c96998/href">https://medium.com/media/bf324294624f5b20c6b02f3ff9c96998/href</a></iframe><p>Now check line 9. This is the jar we’ll use to execute in a Docker container — to run it simply execute:</p><pre>java -jar build/libs/dockeriser-0.0.1-SNAPSHOT.jar</pre><p>As you can see, this will fire the same startup we used before, this time without invoking Gradle.</p><h4>Running the application with different flavours</h4><p>We’ll leverage Spring profiles to have the flexibility of configuring the application in different ways, depending on the environment. So for this we’ll create 4 profiles:</p><ul><li>Local — for our local environment</li><li>Dev — for development environments</li><li>Prod — for production environments</li><li>Container — to execute the application in a container</li></ul><p>How are these profiles materialised in the app? By creating 4 additional application-*.yaml (or application-*.properties) files:</p><ul><li>application-local.yaml</li><li>application-dev.yaml</li><li>application-prod.yaml</li><li>application-container.yaml</li></ul><p>To tell Spring Boot to start using any of these profiles, we need to set the spring.profiles.active property to the given name we chose (multiple profiles can be used). So for example, to run our application with dev and container profiles, we need to run it as:</p><pre>java -Dspring.profiles.active=dev,container -jar build/libs/dockeriser-0.0.1-SNAPSHOT.jar</pre><h4>Why a “<em>container”</em> profile?</h4><p>A good use case for profiles is obviously environment-based configuration. Depending on this, you might need different DB access URLs, storage bucket IDs or simply a specific <em>configuration</em> you want to apply to an environment without affecting the rest (i.e.: logging verbosity). However, there might be cases where you don’t need to do this because you can either externalise that configuration or multiple environments share the same set of parameters. I’ll use an example in one of the next articles of the series and it’ll all make sense, I promise.</p><p>Perhaps you noticed I said configuration but I didn’t say <em>credentials</em>, and there’s a good reason for that. Besides this particular implementation, a good piece of advice: <strong>never, ever write sensitive information like usernames or passwords in your code, </strong>every time you do this there’s an infosec folk suffering somewhere in the world and the god of bad developers deletes all your semicolons from your code (OK, you’d be saved if you used Kotlin, but you still get the point).</p><p>If you’re lost, don’t panic: it’ll make more sense in Part IV using Helm.</p><h3>The main course: creating a Dockerfile</h3><p>Docker is a tool to build and run applications in containers — in case you’ve never heard of Docker, think of these containers as super-lightweight VMs, and of the Dockerfiles as the specs that define how they should run. By default these containers are stateless: meaning they can be destroyed and started from scratch based solely on their specs. Think of it as the shopping list of the container.</p><p>Another good feature they have (which took some time to get my head around) is that they enforce the Single Responsibility Principle: this means that each container runs only one application. The applications must run in foreground so Docker can detect it’s still running correctly. Each Dockerfile can depend on a parent Dockerfile, with usually defines a set of already predefined OS, tools, etc.</p><p>This is the Dockerfile we’ll be using (and as you can see, it just contains the bare minimum required to run), with some tweaks for Production already in there:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf029f8ff4fb5b645528793a4bd8e873/href">https://medium.com/media/bf029f8ff4fb5b645528793a4bd8e873/href</a></iframe><p><a href="https://docs.docker.com/develop/develop-images/dockerfile_best-practices/"></a></p><h4>The JVM flags</h4><p>The details of the flags used to run the application have some good practices I collected for this type of applications:</p><ul><li><strong>-server</strong> tweaks some aspects of the VM to support the type of traffic a server-side application handles.</li><li><strong>-XX:MaxRAMPercentage</strong> is a new flag introduced in Java 11 (then backported to Java 8) that will limit the RAM used by the JVM as a fraction of the overall available memory (if you’re using older versions of Java, you might need to use <em>MaxRAMFraction</em> instead, which is not as flexible as this one but it should do the trick). Take into account that, while the heap is the part of the JVM that will take most of the RAM, there are some other parts, such as thread allocation and code cache that will require memory.</li></ul><blockquote>In a lot of documentation, you’ll probably see that -Xmx and -Xms are used (which set limits for the heap that’s going to be used), and usually that’s the case for older versions of Java. With the introduction of MaxRAMPercentage, it can be avoided, at least initially. MaxHeapSize that complement it in that case.</blockquote><ul><li><strong>-XX:+UseParallelGC</strong> replaces the default JDK11 garbage collector (GC1) with an improved version for smaller, high-throughput applications. You might want to check out GC1 if this is not the case for you. For the full list of available GCs, you can refer to <a href="https://docs.oracle.com/en/java/javase/11/gctuning/available-collectors.html#GUID-9E4A6B11-BB94-424F-90EF-401287A1C333">Oracle’s documentation</a>.</li><li><strong>-Dspring.profiles.active=container</strong> as I mentioned before, the container profile will allow us to have the same configuration that will be required when running our application in a container environment, so it makes sense to anchor it independently of dev/staging/prod. If you noticed, I’m not including the environment yet, so we can deploy the same Docker image in multiple clusters across envs. This configuration will be later externalised and managed by a setting in Kubernetes.</li><li><strong>-Duser.timezone=Europe/London</strong><em> </em>sets a default timezone regardless of the VMs locale. This can be useful when deploying the same application in different regions, without causing differences in the way your application interprets timezone when rendering/storing datetime fields. This on its own it might not be enough (i.e.: JDBC requires an extra setting to recognise this) but I’ll leave the long explanation for another article. Just keep this in mind! Below a really comprehensive article around this topic, just take the time to read it! (pun intended)</li></ul><p><a href="https://zachholman.com/talk/utc-is-enough-for-everyone-right">UTC is Enough for Everyone, Right?</a></p><p>Special mention to properties that are not required but I think are important to point out:</p><ul><li><strong>-XX:+UseContainerSupport</strong> (enabled by default). Before the introduction of this flag, it was really tricky to limit the available memory available to the JVM when running on a container, so in older versions, you might need to activate it.</li></ul><p><a href="https://blog.softwaremill.com/docker-support-in-new-java-8-finally-fd595df0ca54">Docker support in new Java 8 — finally!</a></p><ul><li><strong>-Dspring.devtools.restart.enabled=false</strong> tells Spring to disable <em>Livereload</em>, useful during development for faster compilations when changing code but detrimental for a production instance. According to <a href="https://docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/html/using-spring-boot.html#using-boot-devtools">the docs</a>, running the application the way we are means this is automatically applied (actually devtools is not even included as part of the dependencies)</li><li><strong>-Djava.security.egd=file:/dev/./urandom</strong> tells the VM to use a non-blocking stream of higher entropy to generate random values. Huh? Yeah, I know, it seems like a concatenation of random words but I swear it’s not. It’s a stream that uses signal noise from different parts of your computer to produce strings that look “more random”. Want to see what it looks like? Just run cat /dev/urandom. If you’re on Windows, sorry mate, cannot help you there. There’s been a few fixes on this matter since JDK8, so you might want to check the SO post before just in case.</li></ul><p><a href="https://stackoverflow.com/questions/58991966/what-java-security-egd-option-is-for">What java.security.egd option is for?</a></p><blockquote>Important note: these values are <strong>never</strong> a silver bullet. The parameters you use need to be tweaked to the very specifics of your application: throughput, amount of exchanged data and concurrency patterns. The idea is that you know what aspects to take into account — put differently, pay more attention to the variable names that are being tweaked rather than the actual values. For a comprehensive list of the available variables, check <a href="https://docs.oracle.com/en/java/javase/11/tools/java.html">this page</a> out.</blockquote><p><a href="https://medium.com/adorsys/jvm-memory-settings-in-a-container-environment-64b0840e1d9e">JVM Memory Settings in a Container Environment</a></p><h4>Building and running your Docker image</h4><p>Once this Dockerfile is generated, it needs to be built (<em>-t</em> specifies a tag) into an image:</p><pre>docker build -t dockeriser .</pre><p>The first time it will take longer than all the following builds. Docker works with layers, where each instruction is treated and cached independently, making it particularly useful to speed up build times. In the Dockerfile above, there are 4 instructions: FROM, EXPOSE, ADD and ENTRYPOINT, so this image will have 4 layers. The next time you build your application the only layer that will have to be rebuilt is the one with ADD since your build generated a new jar file. All the rest will be reused.</p><p>If you want to see the available images in your local Docker repository, just execute docker images .</p><p>Once the Docker image is built, it can be run by executing:</p><pre>docker run -P dockeriser:latest</pre><figure><img alt="A detailed list of the active running containers: image name, container id and age, bound ports, etc" src="https://cdn-images-1.medium.com/max/1024/1*UD_N_it7Mm2XYe7CDfX4pA.png" /><figcaption>If you run <strong>docker ps</strong> you’ll see a list of the running containers.</figcaption></figure><p>The <strong>-P</strong> flag tells the Docker daemon to publish any exposed container port. This will allow us to connect from our computer to the container. As you can see under <em>PORTS</em>, our local port 32768 is bound to the container’s 8080 port. You can try executing the same curl (pointing to the local port) we used before against it and you’ll be able to access it. If you don’t publish the container ports, they will be inaccessible from outside of that instance.</p><blockquote>If you want to expose the port using a specific port of your local machine, use -p&lt;local-port&gt;:&lt;container-port&gt;, such as -p8000:8080.</blockquote><p>In the example above, if you run the build command again, all the subsequent images that you generate will be tagged as latest. If you want to generate a new version with a new release, here’s a quirky way of doing that automatically.</p><pre>docker build -t dockeriser:`date +%Y%m%d_%H%M` .</pre><h3>Automate, automate, automate</h3><p>Lastly, one piece of advice: <strong>automate, automate, automate</strong>. It can seem like an obvious thing to say, but it’s not uncommon to see projects where there’s documentation (or sometimes not even that) with the detailed explanation of all the steps to follow to build and deploy an application. Don’t be that person. Please. I’m serious.</p><p>So as you can see, there are a few steps that we could easily automate with a bash script so far: building the Spring boot app, and building the Docker image.</p><pre>./gradlew build<br>docker build -t dockeriser:`date +%Y%m%d_%H%M` .</pre><p>You can find the full version of the shell file below. Even if these are the only two things you actually need to do, if you’re going to automate the process you want it to be fail-safe. What can go wrong in the example above? For starters, Java code build can fail if code doesn’t compile. Or if tests fail. So if you can’t generate a correct jar, your Dockerfile will fail (or worse, it could use a previous version of the one you might have already generated) But then a few other things can go wrong: what if the person that’s running this doesn’t have Docker installed? Or what if it’s installed and the daemon is not running? In neither case will this script work correctly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05d0b5e72c13a873ff404c56d6bae20d/href">https://medium.com/media/05d0b5e72c13a873ff404c56d6bae20d/href</a></iframe><p>You could argue <em>“hey, DUDE, mr. automation, you forgot to include a script to actually </em><strong><em>run</em></strong><em> the project”</em>. And you’d be right. I just don’t care about that step in particular, because I rarely ran an application like this with Docker. I ran them, as you’ll see in Part II, on a Kubernetes cluster (or <a href="https://kubernetes.io/docs/tasks/tools/install-minikube/">minikube</a> if you do it locally) for a couple of reasons.</p><p>Here’s the full project in case you want to clone it and play around with it (where you can also find a _helpers.sh file which contains the auxiliary functions used in the script above). You can check the commits section to see the different steps I described previously.</p><p><a href="https://github.com/sescotti/dockeriser">sescotti/dockeriser</a></p><p>And <em>voilà</em>! There you go, a Docker image ready to be deployed and run in a container. Hope you’ve found this article interesting. Do you have a question? Feedback? You implemented this and you do it differently? You found an error? Don’t hesitate to leave a comment!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ee884ea06b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>