<?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 Ankit Wal on Medium]]></title>
        <description><![CDATA[Stories by Ankit Wal on Medium]]></description>
        <link>https://medium.com/@ankit.wal?source=rss-afa4fb7c7881------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7UmwBOhPDM0HLOrvmXAZcQ.png</url>
            <title>Stories by Ankit Wal on Medium</title>
            <link>https://medium.com/@ankit.wal?source=rss-afa4fb7c7881------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 20:46:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ankit.wal/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[The why of whys of Platform Engineering]]></title>
            <link>https://medium.com/@ankit.wal/the-why-of-whys-of-platform-engineering-451582fdf0f6?source=rss-afa4fb7c7881------2</link>
            <guid isPermaLink="false">https://medium.com/p/451582fdf0f6</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[continous-delivery]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[first-principles]]></category>
            <dc:creator><![CDATA[Ankit Wal]]></dc:creator>
            <pubDate>Tue, 07 Mar 2023 05:50:53 GMT</pubDate>
            <atom:updated>2023-03-14T03:06:34.170Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Why of Platform Engineering, Part 1.</h3><p><em>This article is the first in a series of articles intended to cover the ‘why’, ‘what’ and ‘how’ of Platform Engineering.</em></p><p>Platform engineering, like all other major efforts to improve outcomes in the field of software delivery, is about creating <strong>quality</strong> software at <strong>speed</strong> and <strong>scale</strong>.</p><p>In the spirit of first principles, let’s briefly examine why we care about these ‘whys’.</p><h3>Speed</h3><p>Teams and organisations want to be able to move fast, at least faster than their competitors. The benefit of speed to an organisation can be fairly intuitive from a business lens. “First mover advantage”, “time to market” and other common business parlance encapsulate the value of moving at speed. In the specific context of software engineering, arguably the greatest benefit of speed is when it is paired with agile software delivery. Being ‘agile’ implies starting with an assumption, acknowledging that what we think is probably wrong, making small bets, validating with real world feedback, and iterating towards desired state. These cycles of hypothesis, experimentation and adjustment lead to solutions that work. To arrive at a winning product, an engineering organisation needs to out-experiment their competitors. Teams and organisations that create faster, measure faster, iterate faster are more likely to create the winning product. The same can be applied to arriving at what architecture, design and tools work best. <strong>Speed of experimentation</strong> determines an engineering organisations success.</p><h3>Quality</h3><p>A lack of quality implies higher costs. For example, failures in customer facing environments are usually associated with a monetary amount — an e-commerce web platform that is unavailable for 10 minutes may lose thousands if not millions in revenue. However even more importantly, <a href="https://martinfowler.com/bliki/TradableQualityHypothesis.html"><strong>quality enables speed</strong></a><strong>!</strong> It’s almost intuitive to think that to achieve quality we must take a slow, careful and deliberate approach or that we can sacrifice quality to go fast, release more features. In software engineering, this is a false choice. There is no speed without quality, and organisations with high quality always work at high speed. We know from data driven <a href="https://cloud.google.com/resources/state-of-devops">surveys done by the State of Dev Ops Report</a> and their findings that elite organisations combine both high ‘deployment frequency’ and low ‘lead time’ with low ‘change failure rate’ and low ‘mean time to recovery’.</p><h3>Scale</h3><p>Scale, unlike the others factors here, sets the context in which we want to achieve the above outcomes as opposed to a desired outcome itself. The methodologies that determine success at a scale of individuals doing side projects may be very different from practices that enable large engineering organisations to succeed. Organisational constraints and context matter, and perhaps that’s why the only answer consultants can give clients that always applies is “It depends”.</p><p>Scale is about both <strong>people and</strong> <strong>technology</strong>.</p><h4>People</h4><p>For now at least, writing software is a creative process still within the domain of humans. And while that remains the case to be able to produce quality software at speed and scale, we need to think about the people and teams creating that software. Factors like <strong>autonomy, motivation and cognitive load need to be taken into account</strong> along with competencies when creating an engineering team, even more importantly when structuring and engineering organisations. A high performing engineering organisation could be brought to a grinding halt from their own growth and success. As the complexities and scale of their organisations grow, the ability of their teams to function autonomously and at sustainable cognitive load determines if the organisation can keep producing quality software at speed.</p><h4>Tech</h4><p>Platform products, or what we better know as PaaS (Platform as a Service) like <a href="https://www.heroku.com/">heroku</a> and <a href="https://fly.io/">fly.io</a> can be wonderful enablers at a certain scale, <strong>but large enough organisations need to vertically integrate their resources so that they can own cost, security, compliance and other governance concerns. Large enough organisations cannot afford to be held captive by product limitations and constraints while their competitors innovate</strong>.<br>Platform engineering practices often require initial investment, and the return on this investment often scales with the engineering organisation up to a point where these practices become a must-have to produce quality software at speed and scale. Without it, organisations risk either a free for all chaos or a over centralised bureaucracy.</p><p>Hence large organisations need to adopt practices, patterns and processes that allow multiple teams, across multiple complex subsystems, across multiple business domains, to operate with manageable cognitive load and autonomy to produce high quality software at speed.</p><p><em>Part 2 will look, in detail, at the levers that platform engineering applies to enable speed and quality.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=451582fdf0f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The How of IAM Roles for Service Accounts, IRSA, on AWS EKS]]></title>
            <link>https://medium.com/@ankit.wal/the-how-of-iam-roles-for-service-accounts-irsa-on-aws-eks-3d76badb8942?source=rss-afa4fb7c7881------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d76badb8942</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws-eks]]></category>
            <category><![CDATA[aws-iam]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[simple]]></category>
            <dc:creator><![CDATA[Ankit Wal]]></dc:creator>
            <pubDate>Sat, 09 Jul 2022 11:55:04 GMT</pubDate>
            <atom:updated>2023-03-18T08:15:44.124Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding IAM roles for service accounts, IRSA, on AWS EKS.</h3><p><em>Ankit is a Lead Platform Engineer at Thoughtworks, you can follow him on </em><a href="https://www.linkedin.com/in/ankitwal/"><em>Linkedin</em></a><em> and </em><a href="https://medium.com/@ankit.wal"><em>Medium</em></a><em>. Views expressed are personal and do not represent those of his employer.</em></p><p>A simple visual explanation of how IRSA works to help you understand and remember.</p><h3>The What and and Why</h3><p>IRSA is the AWS EKS native way to allow applications running in EKS pods to access AWS API, using permissions configured in AWS IAM roles. It’s an improvement over the previous architecture of applications running in pods to use the IAM roles of the underlying EKS nodes. Being able to configure access to AWS API per service account tends towards the principle of least privilege, and more secure architecture.</p><h3>The How</h3><p>IRSA ties together elements from AWS IAM, OpenID Connect, K8s Service Accounts and Pods. Naturally it has a few moving parts that cut across the above concepts. Below is a <strong><em>simplified explanation</em></strong> of how various parts and configuration come together to allow applications running in a pod to use an IAM role.</p><h4>The Setup</h4><p>Below is a <em>highly abstracted</em> EKS cluster, inside which we have a</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rukAylLLMRWSQIQ9bBBaQA.png" /><figcaption>Pod ‘A’ and Service Account ‘SA’ with annotation pointing to a IAM Role ‘X’</figcaption></figure><ul><li><strong>Pod ‘A’</strong>, where our application is running,</li><li><strong>Service Account ‘SA’</strong>, which describes via an <strong>annotation</strong> that it wants to use <strong>IAM Role ‘X’</strong></li></ul><p>In turn, shown below, the IAM Role ‘X’ has a <strong>trust relationship</strong> that points to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Le6fuq_kmXV2u56hR1ooCA.png" /><figcaption>AWS IAM Trust Relationship pointing to the K8s OIDC Provider and Service Account</figcaption></figure><ul><li>the K8s Service Account ‘SA’ that can assume that role.</li><li>the K8s OIDC Provider of the EKS Cluster</li></ul><blockquote>We want to configure Pod ‘A’ to use IAM Role ‘X’</blockquote><h4><strong>Service Accounts and Service Accounts Tokens</strong></h4><p>When we create a Service Account in EKS, it also creates a <strong>Service Account Token,</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_p03jLidsgMtFWc6aGgcag.png" /><figcaption>Service account ‘SA’ comes withs a JWT service account token, stored in secret ‘SA’.</figcaption></figure><ul><li>this <strong>Service Account Token</strong> is stored as a <strong>K8s Secret </strong>in the same namespace,</li><li>the token itself a is <strong>JWT</strong>, a Json Web Token.</li></ul><h4><strong>Attaching the Service Account to the Pod</strong></h4><p>When we configure the Pod to use a Service Account, or in other words, attach a Service Account to a Pod, EKS does a couple of things-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Vt3PjXUd4aC3mpiEIpL6w.png" /><figcaption>ENV Vars and Token ‘SA-T’ injected into Pod ‘A’</figcaption></figure><ul><li>the service account JWT, stored in the secret, is volume mounted into the Pod,</li><li>the following ENV VARs are injected into Pod</li></ul><pre>AWS_ROLE_ARN=&lt;IAM ROLE ARN&gt;<br>AWS_WEB_IDENTITY_TOKEN_FILE=&lt;PATH TO SERVICE ACCOUNT TOKEN&gt;</pre><p>This is important, as now our application running inside the Pod has (via env vars, and volume mounts) access to</p><ul><li>AWS_ROLE_ARN, the IAM Role ‘X’ ARN it should use, and</li><li>AWS_WEB_IDENTITY_TOKEN_FILE, the token it should use to try to assume the above role.</li></ul><h4>The assume role request</h4><p>The AWS SDK, that runs with your application inside the pod knows to look at these ENV VARS for config.</p><p>It will send a request to AWS STS, requesting to assume the IAM Role ‘X’, and send the service account ‘SA’ JWT in that request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VlS8OLzCZNgAP8ZfD4HMHw.png" /><figcaption>The application in Pod ‘A’ requests AWS STS to allow it to assume IAM Role ‘X’</figcaption></figure><p>The request will contain</p><ul><li>the ARN of IAM Role ‘X’</li><li>the JWT of Service Account ‘SA’</li></ul><p>AWS STS will use the config in the Trust Relationship of IAM Role ‘X’ such that,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VGkR6UssoZX5rbMvbwOAEA.png" /><figcaption>AWS STS validates the JWT</figcaption></figure><ul><li>Get required keys and config form the <strong>trusted OIDC Discovery</strong> endpoint to <strong>ensure the presented service account JWT is valid and issued by the trusted cluster’s OIDC Provider</strong></li><li>Ensure that the <strong>Service Account ‘SA’ is trusted to assume</strong> the IAM Role ‘X’.</li></ul><blockquote>This is possible because the K8s uses JWT standards for service account tokens and exposes an OIDC Discovery endpoints that allows third parties, like STS, to validate the JWTs.</blockquote><h4>On Success</h4><p>STS will issue security credentials for IAM Role ‘X’ to the application in Pod ‘A’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5j4Oe3ysKugybUuOn0vztw.png" /><figcaption>STS issues credentials for IAM Role ‘X’ to application in Pod ‘A’</figcaption></figure><p>Effectively ‘attaching’ IAM Role ‘X’ to Pod ‘A’ that is configured to use Service Account ‘SA’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FhEQO3AuC0kGyDhvuHB-SQ.png" /></figure><p>Fin. Thank you for reading.</p><blockquote>Note: The terms EKS and K8s are used interchangeably, and the various sub-components/controllers are abstracted.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d76badb8942" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authenticate requests to apps on kubernetes using Nginx-Ingress and an AuthService.]]></title>
            <link>https://medium.com/@ankit.wal/authenticate-requests-to-apps-on-kubernetes-using-nginx-ingress-and-an-authservice-37bf189670ee?source=rss-afa4fb7c7881------2</link>
            <guid isPermaLink="false">https://medium.com/p/37bf189670ee</guid>
            <category><![CDATA[ingress]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[authorization]]></category>
            <dc:creator><![CDATA[Ankit Wal]]></dc:creator>
            <pubDate>Mon, 01 Jul 2019 14:31:53 GMT</pubDate>
            <atom:updated>2019-07-01T14:31:53.344Z</atom:updated>
            <content:encoded><![CDATA[<p>A common pattern for deploying micro-services deployed on cluster, like kubernetes, is to delegate authentication to another external service or extract it out to its own micro-service on the cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qz0_BzIJVtYVBYAb3NZFdg.png" /><figcaption>Micro-services Deployment on a K8s Cluster.</figcaption></figure><p>Delegating authentication for all API calls can be a powerful way of avoiding the need to implement some authentication plumbing at each micro-service. This frees development teams to focus more on domain logic and avoids repeat work. This article introduces nginx-ingress annotations that can help configure the required routing for such an authentication/authorisation flow.</p><h3>Authentication Annotations</h3><h4>1. auth-url</h4><p><strong>Nginx-Ingress</strong> is a fairly mature ingress solution for deployments on kubernetes and comes with a lot of out-of-box features. Most of them can be used by simply supplying <a href="https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/#external-authentication">annotations</a> to the respective ingress yamls. For our purpose we can look at the <em>external-auth</em> annotations ‘auth-url’.</p><pre>nginx.ingress.kubernetes.io/auth-url: &quot;url to auth service&quot;</pre><p>This annotation tells the nginx-ingress controller to forward the incoming request first to the auth-service, and then if the auth-service responds with an 200 Ok then on to the downstream route. For example:</p><pre>apiVersion: extensions/v1beta1 <br>kind: Ingress<br>metadata:<br>  annotations:<br>    nginx.ingress.kubernetes.io/auth-url: http://auth-service.prod.svc.cluster.local/authenticate<br>  namespace: prod <br>  name: ingress-with-auth<br>spec: <br>  rules:<br>   - host: api.microservice-1.myapp.com<br>      http:<br>        paths:<br>        - path: /secure/<br>          backend:<br>            serviceName: microservice-1<br>            servicePort: 8080</pre><p>The above ingress config would instruct the nginx-ingress to forward any incoming requests on api.microservice-1.myapp.com/secure/ to the /authenticate endpoint of an auth-service deployed internally to the cluster.</p><ol><li>User/client makes an api request to api.microservice-1.myapp.com/secure/*</li><li>At the Ingress controller, the same request is routed to /authenticate endpoint of the auth service</li><li>If the auth-service responds with an 200 Ok the request is passed through to microservice-1</li></ol><h4>2. auth-response-headers</h4><p>We can even extend this pattern and have the authentication service pass some information to the downstream applications using the <strong>auth-response-headers </strong>annotation. For example, the AuthService can, as part of the authentication, resolve the userName or userId for the incoming request and return them to the microservice-1:</p><pre>apiVersion: extensions/v1beta1 <br>kind: Ingress<br>metadata:<br>  annotations:<br>    nginx.ingress.kubernetes.io/auth-url: <a href="http://auth-service.prod.svc.cluster.local/authenticate">http://auth-service.prod.svc.cluster.local/authenticate</a><br>    nginx.ingress.kubernetes.io/auth-response-headers: UserID<br>  namespace: prod <br>  name: ingress-with-auth<br>spec: <br>  rules:<br>   - host: api.microservice-1.myapp.com<br>      http:<br>        paths:<br>        - path: /secure/<br>          backend:<br>            serviceName: microservice-1<br>            servicePort: 8080</pre><ol><li>User/client makes an api request to api.microservice-1.myapp.com/secure/*</li><li>At the Ingress controller, the same request is routed to /authenticate endpoint of the auth service</li><li>Authentication service resolves UserID as part of the authentication, and appends it to the <strong>response headers</strong></li><li>Nginx-Ingress appends the UserID response header from AuthService to the request headers of the original request, and passes it through to microservice-1</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nsDhrYdqecEyNpDJzgZqAg.png" /><figcaption>Forwarding Response Headers From AuthService</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37bf189670ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Why and How of Multi-Stage Docker Build with Typescript Example]]></title>
            <link>https://medium.com/@ankit.wal/the-why-and-how-of-multi-stage-docker-build-with-typescript-example-bcadbce2686c?source=rss-afa4fb7c7881------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcadbce2686c</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[multi-stage-builds]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Ankit Wal]]></dc:creator>
            <pubDate>Wed, 15 May 2019 16:03:15 GMT</pubDate>
            <atom:updated>2019-05-16T14:59:23.963Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Why and How to use Multi-Stage Docker Builds for Lean Production Images</h3><p>A simple introduction to Docker multi-stage builds and the builder pattern, why it helps reduce image size and build complexity, and how to create lean production worthy image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ReM2ZPoRFLoKhU48E0dasw.jpeg" /><figcaption>Containers, containers everywhere</figcaption></figure><h3>Introduction</h3><p>This article is for people who have some experience with writing docker files, and want to understand and leverage multi-stage build to create lean, production-worthy container images. It has two main sections.</p><ol><li>The Why — <em>An introduction to the challenge of creating lean docker images and docker’s layered filesystem.</em></li><li>The How —<em> What were the solution to create lean images before multi-stage and how to implement the builder-pattern using multi-stage builds.</em></li></ol><p>If you like you can skip to <strong>The How</strong> section to jump straight into the meat of multi-stage builds. However <strong>The Why</strong> helps appreciate the problem that the builder-pattern and multi-stage builds try to solve in the first place.</p><h3>The Why</h3><p>When we containerise our application for a production environment, we typically want to ensure that our docker image:</p><ol><li>Doesn’t have <strong>unnecessary packages.</strong> <em>Unused packages increase complexity and the attack surface for vulnerabilities in production.</em></li><li>Is <strong>lean. </strong><em>Smaller images are more performant.</em></li></ol><p>With these in mind, let’s make our first attempt at creating a docker image for a sample<strong><em> Typescript NodeJs App</em></strong>, <a href="https://github.com/ankitwal/ts-express-sample">https://github.com/ankitwal/ts-express-sample</a></p><p>First, our simple package.json looks like this:</p><pre>{<br>  &quot;name&quot;: &quot;ts-docker-sample&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;jest&quot;,<br>    &quot;clean&quot;: &quot;rm -rf ./dist/* &quot;,<br>    &quot;build&quot;: &quot;tsc &quot;,<br>    &quot;start&quot;: &quot;node ./dist/index.js&quot;<br>  },<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;devDependencies&quot;: {<br>    &quot;<a href="http://twitter.com/types/express">@types/express</a>&quot;: &quot;^4.16.1&quot;,<br>    &quot;typescript&quot;: &quot;^3.4.5&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;express&quot;: &quot;^4.16.4&quot;<br>  }<br>}</pre><p>The things to note from the above are:</p><ol><li>We have devDependencies, for example, typescript that we need to build our project, but don’t need and want at run-time</li><li>The npm scripts to build the project at npm clean and npm build</li></ol><p>So let’s now try to write a very simple Dockerfile that does the basic steps to create an image.</p><pre>FROM node:8-alpine<br>WORKDIR app<br>COPY . .<br>RUN npm install<br>RUN npm run clean<br>RUN npm run build<br>CMD npm start</pre><p>In this Dockerfile we copy over all the contents in our source directory into the docker image, then RUN npm install and then npm clean and npm build . Let’s build this docker file with docker build -t ts-sample:0.1 ./ and then list our build image with docker images | grep ts-sample, we can now see our new image with a total size of 121MB:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xv3dD9EXPFJZjr7m3SoeJA.png" /><figcaption>Size of our docker image</figcaption></figure><p>While this image will start up in a container and run our server, it is neither <strong>lean</strong> nor does is comply with <strong>no unnecessary packages</strong>. Let’s look at the size of all our dependencies installed via npm installversus just what we need to run our app in production via npm install --production:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3UdoKKrRk3h8ND-5PsEuSw.png" /><figcaption>All Dependencies (Left) and only Production Dependencies (Right)</figcaption></figure><p>Highlighted above, we can see that the size of all dependencies (dev and prod) is 45MB, while we <strong>only need 2.3MB</strong> of packages to run the app in production. So there are about <strong>~42MB of unnecessary packages</strong> in this bloated docker image. Let’s try to fix that in our second attempt at this docker file:</p><pre> FROM node:8-alpine<br> WORKDIR app<br> COPY . .<br> RUN npm install<br> RUN npm run build<br>+RUN rm -rf node_modules<br>+RUN npm install --production<br> CMD npm start</pre><p>This simple approach adds a step to delete all node_modules RUN rm -rf node_modules and installs only the ones needed for production RUN npm install --production. This would mean we don’t have the unnecessary typescript and types/express dependencies in our production build. But does this make a leaner, more performant image? Let’s build docker build -t ts-sample:0.2 ./ with a 0.2 tag and list our image again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*10YtGTNDWyS9S-x8EJQAow.png" /><figcaption>Our first docker image ts-sample:0.1 vs. our second ts-sample:0.2</figcaption></figure><p>Instead of being ~42MB smaller our new image, ts-sample:0.2 is 122MB, even larger than our first, ts-sample:0.1 at 121MB. Here is our first valuable lesson to always remember when writing dockerfiles:</p><blockquote>Docker file system is layered and every RUN, COPY and ADD command in our dockerfile adds another layer.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vuYssqoskvmdQCd6lY0xDw.png" /><figcaption>Layers in our first image vs. our second image</figcaption></figure><p>So by attempting to clean up our image, we have actually added 2 more layers on top, and the layers below are still bloated. NOW, we can finally talk about docker multi-stage builds.</p><h3>The How</h3><h4><em>Before Docker Multi-stage</em></h4><p>Before docker released the multi-stage build feature, there were 2 main options of getting around our problem of wanting to create the leanest, most performant production image. We could have:</p><p>Option 1: Use Dockerfile tricks like chaining all the RUN commands with &amp;&amp;</p><pre>RUN npm run build \<br>&amp;&amp; rm -rf node_modules <br>&amp;&amp; npm install --production</pre><p>This ensures that all the commands are run as part of the same single layer. While this is effective, it can make our Dockerfile less readable, and <strong><em>prone to errors</em></strong>. In fact I’ve left out the \ required to escape the new line in the second statement, as an example of a mistake that can easily creep into our Dockerfile.</p><p>OR</p><p>Option 2: Use the Builder Pattern with Bash Scripts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rwJAwY722Lz7tWsgV79PNw.png" /><figcaption>BuilderPatter with Script</figcaption></figure><p>A builder-pattern in our simple case could look like the above, where we would have 3 total files, 2 Dockerfiles and 1 Script.</p><ul><li>Dockerfile.builder to build an image that had all our devDependencies and would generate compiled artefacts (compiled javascript),</li><li>a bash script, build-script.sh to copy out our compiled artefact out of the builder image using a docker cp command.</li><li>and lastly a Dockerfile where such a compiled artefact will run with <em>only the packages it needs</em> i.e our production dependencies. This is the image we would use in production.</li></ul><p>This pattern is a good solution, as it uses a builder image to create a very lean production image. However it also <strong><em>adds considerable build complexity </em></strong><em>as </em>we have to maintain at-least 3 files, and there would be an extra builder image to store on the host machine.</p><h4>Multi-stage Docker Builds</h4><p>The Current Best Solution</p><blockquote>Multi-stage is a more elegant solution that allows us to leverage the builder pattern but without the added complexity of multiples dockerfiles, and other bash scripts.</blockquote><p>With a multi-stage build, the builder Dockerfile.builder and the Dockerfile from our builder-patter above, can be <strong>Stages </strong>in one single dockerfile. And multi-stage gives us the capability to copy build artefacts (compiled javascript) from one stage to the next eliminating our need for the external build-script.sh. Hence instead of 3 files, we have just the one. We need to learn two concepts for writing our multi-stage dockerfile:</p><ul><li>Creating a <strong>Stage </strong>in a dockerfile, and optionally naming it using the AS command.</li><li>Copying files from a previous stage using the --from flag: COPY --from:&lt;stage-name&gt;</li></ul><ol><li><strong>Writing a Stage in our docker file:</strong>FROM node:8-alpine AS ts-sample-builder</li></ol><p>Let’s write our first stage of the dockerfile that will be responsible for creating compiled javascript artefacts, and we won’t worry about minimising layers and cleaning up any devDependencies. This stage will perform the role of a builder, we can name this stage as ts-sample-builder. Naming this stage will make our dockerfile more readable when later stages refer to a previous stage by name, as seen later.</p><pre># Our First stage, that is the Builder<br>FROM node:8-alpine AS ts-sample-builder<br>WORKDIR app<br>COPY . .<br>RUN npm install<br>RUN npm run clean<br>RUN npm run build</pre><p>This gives a first stage, the builder stage, which can compile our typescript source code to javascript. We installed, it has all our dependencies, dev and production. It is not suitable for production, but we <em>only care about </em>creating our compiled javascript in this stage. At this point, we want to add lean production stage where this compiled artefact can run. This brings us to the second concept of multi-stage builds that we need to learn.</p><p>2. <strong>Copying from a previous stage: </strong>COPY --from:&lt;stage-name&gt;</p><p>This allows us to copy out exactly the files or directories we need, without worrying about optimising the number of layers and cleaning up our devDependencies. Let’s add a ‘prod’ stage to our above docker file.</p><pre># Our first stage, that is the Builder<br>FROM node:8-alpine AS ts-sample-builder<br>WORKDIR /app<br>COPY . .<br>RUN npm install<br>RUN npm run clean<br>RUN npm run build<br></pre><pre># Our Second stage, that creates an image for production<br>FROM node:8-alpine AS ts-sample-prod<br>WORKDIR /app<br>COPY --from=ts-sample-builder ./app/dist ./dist<br>COPY package* ./<br>RUN npm install --production<br>CMD npm start</pre><p>In the above, we add a new stage called ts-sample-prod. In this stage,</p><ul><li>COPY --from=ts-sample-builder ./app/dist ./dist we copy in our compiled javascript from our previous stage into our new one</li><li>COPY package* ./ copy only package.json, and package-lock.json from our source directory</li><li>RUN npm install --production only install the dependencies we need for running our app in production</li></ul><p>The --from allows us to point our COPY command to a previous stage in our build. Its important to note, that our first stage will not produce a docker image, only our final stage. Hence <strong><em>all the layers and complexity in our builder stage do not impact our final image</em></strong>. Let’s now build our final image with docker build -t ts-sample:multi-stage ./ and list out the images with docker images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibNgrg7Gu4XmvWIQP3WVag.png" /><figcaption>Multi-stage image file is almost half the size</figcaption></figure><p>Finally we have a more production-worthy image, that’s <strong>almost half the size</strong> of our previous attempt — 67.9MB as opposed to 121MB. With multi-stage we could write our builder stage ts-sample-builder in a clean, readable way without worrying about size and layers. This <strong>reduces our build complexity</strong>. Subsequently we can copy our complied javascript into a second stage called ts-sample-prod, where we only install the dependencies needed for production, creating a much <strong>leaner image</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*353MaNZmBjQtD1_gL65XcA.png" /><figcaption>Our final image with 3 thin layers</figcaption></figure><h3>Summary</h3><ol><li>We want a lean image with no unnecessary packages.</li><li>Docker file system is layered, and RUN, COPY and ADD create new layers.</li><li>Multi-stage provides an elegant way to implement the builder pattern to create lean docker images without needing other files or scripts.</li><li>AS allows us to name a stage, and the COPY --from allows us to copy artefacts from previous stages without adding any unnecessary layers.</li></ol><p>The best way to find better quality articles is to leave feedback for authors. Was this article helpful? Was the explanation clear? Leave your feedback below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcadbce2686c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>