<?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 Mark Birbeck on Medium]]></title>
        <description><![CDATA[Stories by Mark Birbeck on Medium]]></description>
        <link>https://medium.com/@mark.birbeck?source=rss-3576792052c1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*FEaRhDaZ41CG-ZbN</url>
            <title>Stories by Mark Birbeck on Medium</title>
            <link>https://medium.com/@mark.birbeck?source=rss-3576792052c1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 09:43:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mark.birbeck/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[What I Learnt From Reviewing 22 CVs]]></title>
            <link>https://medium.com/@mark.birbeck/what-i-learnt-from-reviewing-22-cvs-54ec1b84b772?source=rss-3576792052c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/54ec1b84b772</guid>
            <category><![CDATA[job-hunting]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[cv-writing]]></category>
            <dc:creator><![CDATA[Mark Birbeck]]></dc:creator>
            <pubDate>Sat, 04 Jul 2020 14:08:00 GMT</pubDate>
            <atom:updated>2020-07-05T16:42:07.273Z</atom:updated>
            <content:encoded><![CDATA[<h3>What I Learnt From Reviewing 22 React CVs</h3><p>I was recently asked to look over some CVs. It’s a while since I’ve done this, so I thought that noting down my immediate reactions as I went through the CVs might help anyone having to circulate their own CV at the moment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wNAM3H2e3JwdUgza.jpg" /></figure><p>I’m not for a moment saying I’m right or wrong in the following views, and this is definitely not one of those posts about ‘how to write your CV to land your dream job’. I’m merely laying out the responses I had and more importantly what I felt these reponses told me about the person behind the CV. My ‘gut reaction’ may well be similar to others’ and if they are, it might be worth bearing them in mind when you share your CV.</p><h3>Looks Count More Than I Thought</h3><p>First, it wasn’t until I reached the ninth CV that I realised how much a CV’s appearance makes a difference. When viewing numbers one to eight I hadn’t been thinking ‘these look terrible’, but when I reached the ninth, a part of my brain said: ‘Finally! A CV that looks good.’</p><p>I think if the role was for a C++ programmer then I probably would have simply smiled to myself, ignored my response, and moved on. That’s not to say that appearance doesn’t matter-or that C++ programmers don’t worry about their appearance-but if I was trying to decide between two C++ programmers it wouldn’t be the look of their CV that was the deciding factor.</p><p>But the role for which I was reviewing this batch of CVs was a React developer and there are lots of very talented React developers out there. And when lots of people have worked with GraphQL and Docker and cloud services and D3 then it may well come down to whether or not you have made an effort to convey that you like things to ‘look nice’.</p><p>It’s worth saying too that the CVs that looked good didn’t go overboard; all they did was have a pleasing font, perhaps two columns instead of one for the layout, maybe a couple of icons and some colour, and probably didn’t span more than a couple of pages. But that was enough to convince me that these were people who would ensure that a bad-looking product didn’t get deployed.</p><h3>Attention to Detail</h3><p>Probably in the same vein, typos really jump out at you when you are looking at a lot of CVs. Again I’m not saying I’m right or wrong on whether this should be an important criteria, but the fact that my subconscious reaction was to be turned off if I saw a spelling mistake-or a technology name that had been capitalised incorrectly-shows that somewhere in our psyches this stuff counts for something.</p><p>As with the previous point about looks, I’d probably see this as more relevant for front-end people.</p><p>And it might be worth saying that it’s usually not difficult to differentiate between those who have just not bothered to check their CV and those that have difficulty with spelling. I’ve worked with people in the latter camp, both senior managers and junior programmers, and it’s not a big deal-you can work with it and it would not stop me from hiring someone.</p><p>But to keep with the theme of my ‘initial reaction’, I can’t help that when I see someone write ‘Graphql’ I’m going to doubt whether the applicant really has that much experience with ‘GraphQL’; maybe it’s worth just double-checking the website of the technologies you use one last time, before sending off that CV.</p><h3>Approaches v. Technologies</h3><p>One other thing that I hadn’t expected was that I was drawn to mark people more highly if they gave some indication of the <em>approach</em> they took to their coding and development. For example, a few people mentioned having experience with TDD, which I thought was good. That doesn’t mean I’d rule out someone who didn’t have TDD experience, but it’s an approach that people need to be aware of.</p><p>However, more importantly than TDD, only a handful indicated that they liked to get involved in code reviews and saw them as a good way to share knowledge and build a consistent and high quality codebase. Again, I would not rule out someone who didn’t mention code reviews, mentoring, and so on, provided they were relatively inexperienced; but I probably <em>would</em> rule out someone who clearly has experience, but hasn’t thought to mention these things.</p><h3>Approach From Technologies</h3><p>What I was also surprised by was how the list of technologies on a person’s CV led to me forming an impression of the kind of coder that person was. If I saw GraphQL in the mix then I found myself thinking ‘modern tech stack’. It may be unfair, especially since GraphQL wasn’t mentioned in the job description that was circulated; but after reviewing all of the CVs I found that it was a pretty accurate indicator of the types of projects someone had been involved in.</p><p>There were other technologies that were similarly indicative, such as mention of ‘microservices’, or use of MongoDB, Elasticsearch, Redis, RabbitMQ, and so on. But there were very few CVs where these technologies appeared without GraphQL.</p><p>There is probably no general rule here, since the technologies that differentiate will be different in each cohort of CVs; if every CV included GraphQL then it may have been the presence of something like Docker and/or Kubernetes that told you something about the kind of people you were looking at.</p><h3>Public Profile</h3><p>This last point may also be controversial, but I’m going to describe it so that you can do whatever you like with the information; if someone was not on LinkedIn or didn’t have a public Git account, I found myself thinking ‘well, what exactly do they do?’</p><p>From this batch of 22 CVs, only one had answered any questions on Stack Overflow, and only one-a different person-had done any talks at Meetups. A couple had GitHub accounts, a couple were on LinkedIn and a couple had blogs.</p><p>This is no doubt unfair, so again, blame my subconscious. But I can’t help think that if I’m going to work with some people day after day, I want to be with people that are sharing links to things they’ve read, people who are trying out new technologies and languages, people who have weekend projects, or who are contributing bug fixes back to open source projects.</p><p>And although I’m not particularly a big fan of LinkedIn, I always quite like it when I see people who are at the early stages of their career making connections with everyone they met at last night’s Meetup.</p><p>None of this is to ignore the current discussion about work/life balance-to demand that people do their own education in their own time, spend all waking hours coding, attend Meetups every night of the week. But it is to recognise that we are in a fast-moving industry, and if you want your CV to be picked from amongst that batch of 22, then it’s going to be important to think about how you come across.</p><h3>Qualifications</h3><p>One final thing has just occurred to me…I didn’t consider the qualifications of <em>anyone</em>, which I imagine is down to the role that the CVs were for. You’d certainly be interested in degrees and PhDs if you were hiring a data scientist or someone to write an operating system; in these spaces theory is a major element. But for fast-moving technologies like front-end development, you can probably tell everything about a person from their experience.</p><h3>Conclusion</h3><p>I haven’t had to look at CVs for quite a while, so it was interesting to examine my own responses to reviewing this batch. What became clear is that I quickly ‘merged’ the CV and the person in my mind. If there were mistakes in the CV I couldn’t help but imagine someone who lacked attention to detail. If there was a little bit of colour in the CV or the person had spoken at a Meetup then I couldn’t help but think that this was a person who was prepared to go the extra mile. And if the person had a public Git account then my spontaneous reaction was that this was someone who wanted to keep learning, and really enjoyed the work they do.</p><p>I may be wrong in my judgements or harsh in my conclusions, but if you’re about to send your CV out, at least you now have a couple more insights that might help you decide how your CV is representing you.</p><p><em>Originally published at </em><a href="https://youknowfordevs.com/2020/07/04/what-i-learnt-from-reviewing-22-cvs.html"><em>https://youknowfordevs.com</em></a><em> on July 4, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54ec1b84b772" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let TypeScript Inference Take The Strain]]></title>
            <link>https://medium.com/@mark.birbeck/let-typescript-inference-take-the-strain-1063fd8b8b1c?source=rss-3576792052c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1063fd8b8b1c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mark Birbeck]]></dc:creator>
            <pubDate>Sat, 27 Jun 2020 15:13:00 GMT</pubDate>
            <atom:updated>2020-06-27T18:02:20.259Z</atom:updated>
            <content:encoded><![CDATA[<p>I was doing a code review recently and saw something like this:</p><pre><strong>const</strong> mapEventName <strong>=</strong> (eventName: string): string <strong>=&gt;</strong> {<br>  <strong>switch</strong> (eventName) {<br>    <strong>case</strong> &#39;UPDATE_ABC&#39;:<br>      <strong>return</strong> &#39;ABC Updated&#39;<br>    <strong>case</strong> &#39;UPDATE_DEF&#39;:<br>      <strong>return</strong> &#39;DEF Updated&#39;<br>    default:<br>      <strong>return</strong> eventName<br>  }<br>}</pre><p>Putting aside whether this should use a Map or some other technique instead of switch, I was interested specifically in the type information that was provided for the return value.</p><p>Something I see a lot when people adopt TypeScript is to type <em>everything</em>. I think it’s a good idea to add types to structures and interfaces that are passing between layers of our code. But to add extra code to indicate that a function returns a string, <em>when it so obviously returns a string</em> is overkill.</p><p>So what’s the alternative?</p><p>Well in this example there is no need for the return type to be specified. TypeScript has impressive powers of inference and in this function it will have no trouble deducing that the type of the return value will be a string literal. If we look at the function there are three places where a return value is specified; two of them stipulate a string constant to return, and the third says to return the parameter that was passed in-which is itself defined as a string.</p><p>Together these conditions combine such that there is <em>no possibility</em> that this function will return anything other than a string. TypeScript will therefore act accordingly. To verify this, take a look at the IntelliSense provided by your favourite editor. Here is the IntelliSense with the return type specified explicitly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/0*eD5UXj5oxGxrEJbM.png" /></figure><p>and here is exactly the same IntelliSense when the return type is omitted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/0*bJlrABvua7wOtUGZ.png" /></figure><p>And if we want to reassure ourselves that TypeScript is still doing the same checking, let’s try to use the function in a position where a number is required:</p><pre><strong>const</strong> a <strong>=</strong> Math.max(mapEventName(&#39;UPDATE_ABC&#39;), 4);</pre><p>Put this in a TypeScript-enabled editor and you’ll see there is a type error, regardless of the fact that the return type is not explicitly specified:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/0*5-wwuA_Lu5Lu4fY3.png" /></figure><p>You might ask whether missing off one declaration gains us much, but I would suggest it’s a mindset. Rather than approaching TypeScript as this rigid straightjacket that must be wrapped around all of our code, we instead see it as a flexible combination of two things:</p><ul><li>a supercharged linter that can infer types from our code and then check that we’re not doing anything dumb, and;</li><li>a type language that we can add as we need to, to help to resolve ambiguities.</li></ul><p>This gives us the option of a much ‘lighter touch’ approach to TypeScript.</p><p>For more on TypeScript’s type inference see <a href="https://www.typescriptlang.org/docs/handbook/type-inference.html">Type Inference</a>. And for a particularly clever scenario where types can be inferred from assert() statements, see <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions">&#39;asserts condition&#39;</a>.</p><p><em>Originally published at </em><a href="https://youknowfordevs.com/2020/06/27/typescript-inference.html"><em>https://youknowfordevs.com</em></a><em> on June 27, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1063fd8b8b1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why You Need a Pipeline Runner For Your Node Streams]]></title>
            <link>https://medium.com/@mark.birbeck/why-you-need-a-pipeline-runner-for-your-node-streams-1dfc2b06207d?source=rss-3576792052c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dfc2b06207d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mark Birbeck]]></dc:creator>
            <pubDate>Sat, 20 Apr 2019 09:12:00 GMT</pubDate>
            <atom:updated>2019-05-23T15:05:49.755Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T1UJsE8QuJQN_vRJ14HS6A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/xNdPWGJ6UCQ?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Rodion Kutsaev</a> on <a href="https://unsplash.com/search/photos/pipeline-runner?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Basic Node Streams</h3><p>A basic Node streams application would look like this:</p><pre><strong>const</strong> fs <strong>=</strong> require(&#39;fs&#39;)<br><strong>const</strong> zlib <strong>=</strong> require(&#39;zlib&#39;)<br><br>fs.createReadStream(inputPath)<br>.pipe(zlib.createGzip())<br>.pipe(fs.createWriteStream(outputPath))</pre><p>The key thing is that each stream provides a pipe() method, which is used to bolt on additional streams.</p><p>However, although this is correct, it doesn’t lend itself to easy manipulation; in particular, we have to start with one stream and bolt other streams on to it, which throws out the symmetry and makes the whole process difficult to reason about.</p><h3>A Better Model: A Pipeline of Streams</h3><p>A better metaphor is of a pipeline that comprises multiple steps, each of which is a stream. In this model, there is nothing ‘special’ about the first or last streams. Since version 10, Node has provided the module function <a href="https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback">stream.pipeline()</a> that does exactly this. This function can be promisified, which makes the code even easier to read. Our previous pipeline would now look like this:</p><pre><strong>const</strong> stream <strong>=</strong> require(&#39;stream&#39;)<br><strong>const</strong> util <strong>=</strong> require(&#39;util&#39;)<br><strong>const</strong> pipeline <strong>=</strong> util.promisify(stream.pipeline)<br><br><strong>const</strong> fs <strong>=</strong> require(&#39;fs&#39;)<br><strong>const</strong> zlib <strong>=</strong> require(&#39;zlib&#39;)<br><br><strong>await</strong> pipeline(<br>  fs.createReadStream(inputPath),<br>  zlib.createGzip(),<br>  fs.createWriteStream(outputPath)<br>)</pre><p>Now it’s much clearer that our streams are ‘steps’ in a pipeline, and they no longer play the role of <em>driving</em> the pipeline.</p><p>We’ll use this pattern as our canonical pipeline because it is much easier to augment.</p><h3>Separating Pipeline Creation From Running</h3><p>Now that we have the idea of a pipeline as our primary concept, we can start to play with it. In particular, we’ll find it extremely useful if we can separate the step of <em>creating</em> a pipeline from the step of <em>running</em> it.</p><p>We could then, for example, create a pipeline and check it for errors, even before it is run; we could check that the first step is a readable stream and the last step a writable one, for example, or ensure that all necessary resources such as databases or search engines are available before the pipeline starts.</p><p>We could also insert extra steps that wouldn’t need to be specified explicitly in the pipeline, such as pushing and popping items to and from a queue between each step or adding handlers for step-specific errors.</p><p>Another benefit of separating pipeline creation from execution is that we could optimise the pipeline before it’s run, perhaps by merging or reordering steps. We might even create the pipeline on one machine, and send the pipeline to be run on another machine…or multiple machines if we have a way to split the work.</p><p>And not only could we do interesting things with the full pipeline, but we could even manipulate <em>parts</em> of the pipeline; we could run half of the pipeline, then materialise the results, and later run the rest of the pipeline using the saved results (incidentally allowing a pipeline to be upgraded, even whilst running), or we could execute individual pipeline steps as serverless functions, with all of the advantages that that would bring.</p><p>To get ourselves to a situation where these kinds of things are possible our next step is to separate the pipeline itself from its runner.</p><h3>Creating a Runner</h3><p>The basic form of a runner is to first create some steps:</p><pre><strong>const</strong> steps <strong>=</strong> [<br>  fs.createReadStream(inputPath),<br>  zlib.createGzip(),<br>  fs.createWriteStream(outputPath)<br>]</pre><p>and then to run those steps:</p><pre><strong>await</strong> pipeline(...steps)</pre><p>If we wrap this functionality in a class then we have a foundation on which to add the other features we mentioned earlier. So let’s create a class that allows us to <em>register</em> a set of steps with one method, and to <em>run</em> those steps with another method:</p><pre><strong>class</strong> Runner {<br>  <strong>constructor</strong>() {<br>    <strong>const</strong> stream <strong>=</strong> require(&#39;stream&#39;)<br>    <strong>const</strong> util <strong>=</strong> require(&#39;util&#39;)<br>    <strong>this</strong>.pipeline <strong>=</strong> util.promisify(stream.pipeline)<br>  }<br><br>  register(steps) {<br>    <strong>this</strong>.steps <strong>=</strong> steps<br>    <strong>return</strong> <strong>this</strong><br>  }<br><br>  run() {<br>    <strong>return</strong> <strong>this</strong>.pipeline(...<strong>this</strong>.steps)<br>  }<br>}</pre><p>Now we can use our runner like this:</p><pre><strong>const</strong> runner <strong>=</strong> <strong>new</strong> Runner()<br><strong>const</strong> steps <strong>=</strong> [<br>  fs.createReadStream(inputPath),<br>  zlib.createGzip(),<br>  fs.createWriteStream(outputPath)<br>]<br><br><strong>await</strong> runner<br>.register(steps)<br>.run()</pre><p>It’s exactly the same as our previous pipeline but with this structure, we’ve got lots of points at which we can insert the new kinds of functionality that we mentioned earlier, by inheriting from the base class.</p><p>For example, we could add more features by way of the register() method, such as pipeline validation, step optimisation, insertion of additional steps, and so on. (And manipulation of the pipeline is as simple as manipulating an array.)</p><p>And we could modify the run() method to send the steps on to some other server, or launch more workers, sharing the work between them.</p><p>In future posts, we’ll start to flesh out how to achieve some of these more advanced features by building on this class.</p><h3>Conclusion</h3><p>Node streams are incredibly powerful and are a fundamental building-block of efficient and fast data-processing and transformation applications. However, the usual model of an input stream that pipes its output to another stream is quite difficult to manipulate and reason about. Node supports a better model by way of the pipeline() function, and this post shows how it can be used to construct pipelines that comprise multiple streams, and then to separately execute those pipelines.</p><p><em>Originally published at </em><a href="https://youknowfordevs.com/2019/04/20/why-you-need-a-pipeline-runner-for-your-node-streams.html"><em>https://youknowfordevs.com</em></a><em> on April 20, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dfc2b06207d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Control Of Your .dockerignore Files]]></title>
            <link>https://medium.com/@mark.birbeck/getting-control-of-your-dockerignore-files-b4543b04756c?source=rss-3576792052c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4543b04756c</guid>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Mark Birbeck]]></dc:creator>
            <pubDate>Fri, 07 Dec 2018 09:04:01 GMT</pubDate>
            <atom:updated>2018-12-08T14:04:36.667Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting Control Of Your .dockerignore Files</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uV-sj3rtqq8VbBAaVSFyOQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/3tAUxQfglbE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Daniel von Appen</a> on <a href="https://unsplash.com/search/photos/container?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Every now and then I’ll notice a file inside a Docker container that really shouldn’t be there. Thankfully it’s never been a .env file or an SSH key, but even so, any unused file or directory takes up space in the image and makes that image slower to build and pass around. Best practice suggests using the oft-neglected .dockerignore file to keep our secrets secret and make sure our Docker images are as lean as possible. But this file then usually becomes a maintenance nightmare as the list of exclusions grows.</p><p>This post shows how to control .dockerignore by indicating which files we want to <em>include</em> rather than those we want to <em>exclude</em>.</p><h3>The Goal</h3><p>For a while now I’ve been trying to come up with an easy way to exclude unecessary files from my Docker images. Obviously I want to keep secrets out, and I want to prevent any unused directories from being transferred to the Docker daemon when building–they slow down the build as well as increase the size of the resulting images.</p><p>But I also wanted to find a way to exclude files that relate to the build process itself, like Dockerfile and docker-compose.yml; it’s unnecessary clutter if they get transferred to an image and it would be better if they weren’t included at all. This is even more important should you want to share an image through public channels like Docker Hub while keeping the source that builds that image internal to your organisation; in this case there may be private information in these build files and you certainly won’t want them to be shared.</p><p>One last requirement is that when we make a mistake with our ignore rules we want to know about it. The way .dockerignore is normally used, if you mistakenly put something like ‘git’ into your file as a pattern, instead of ‘.git’, you won’t know anything about it unless you spot that a lot of data is being transferred to your build.</p><p>The rest of this post looks at how we might solve these problems.</p><h3>Approach #1: Build From A Single Directory</h3><p>Most of the approaches I have tried in the last year or so have revolved around different ways of organising the project directories. There are lots of ways a project could be organised, but in general, the approach is to try to keep the source, tests, documentation, generated files, and anything else that is part of the project, separate from each other.</p><p>As part of this separation, we also want to ensure that any directories that we don’t want to appear inside the Docker image get set as <em>peers</em> of the main directory that we want to include. This simply means that rather than having app &gt; docs or app &gt; test as our directories, we would instead have app, docs and test as top-level directories sitting alongside each other.</p><p>By having one directory that contains all of the files that will be needed in a build, and everything else kept safely apart in other directories, we at least start to lower the risk of mistakenly copying something important or unnecessary.</p><h3>Setting the Context</h3><p>Once our directories are organised then it’s a simple matter to set the Docker build context to refer to the single directory that should be included in the Docker image. By setting the context to a sub-directory we have ensured that all other directories are excluded, whether they are .git, node_modules, documentation and tests, and so on.</p><p>However, the weakness with this approach is that since the build context must contain <em>everything</em> that Docker will need to build the image, that, unfortunately, means we need to place Dockerfile in our source directory too.</p><h3>Ignoring With .dockerignore</h3><p>It’s easy enough to stop the Dockerfile from being copied into the image by creating a .dockerignore file and then adding ‘Dockerfile’ to it. The .dockerignore file is an ‘ignore file’ which tells the build process which files to leave out when transferring the context to the Docker daemon. For this situation it could be as simple as this:</p><pre># In .dockerignore<br>Dockerfile</pre><p>Don’t worry that this could prevent the whole build process from working. In the case of Dockerfile, Docker will still transfer it to the daemon to guide the build process, regardless of whether we exclude it or not. But by adding it to our ignore file we stop it going any further through the process; i.e., it won’t be available to be copied into the image.</p><p>Of course, if we add a .dockerignore file to our source directory then that will be available to the Docker daemon, so we now need to ignore that as well:</p><pre># In .dockerignore<br>.dockerignore<br>Dockerfile</pre><h3>Problems With Approach #1</h3><p>Although this is a nice simple solution, there’s still nothing to say that we might not accidentally copy something into the image that we didn’t want to. For example, when developing code on our laptop we’ll probably have a .env file full of database passwords and server names in the source directory. If we forget to exclude the .env file as well then it will most likely be copied into our image.</p><p>I also prefer not to leave the Docker-related files in the same directory as the source code since it is mixing layers–the source file of our application is now sat alongside the instructions to <em>build</em> our application. It’s all a bit ‘meta’.</p><h3>Approach #2: A Richer .dockerignore File</h3><p>So the next step would be to keep the build files out of the main directory, moving them to the root of the project. If we do that then we must make the root of the project the ‘build context’, and that means we’re now exposing all of our files to Docker. To exclude the peer directories we mentioned earlier we would modify the ignore file further, like this:</p><pre># In .dockerignore<br>.dockerignore<br>Dockerfile<br>dist<br>docs<br>test</pre><p>If the code we want to put in our image is in the app directory then this .dockerignore file will allow that directory to be copied, but will exclude the dist, docs and test directories.</p><h3>Problems With Approach #2</h3><p>But whilst we’re excluding tests and documentation, we should also be excluding our .git directory (to keep the size down) and other build files, like docker-compose.yml and .gitlab-ci.yml (to keep things private). Now our ignore file looks like this:</p><pre># In .dockerignore<br>.git<br>.gitlab-ci.yml<br>.dockerignore<br>dist<br>Dockerfile<br>docker-compose.yml<br>docs<br>test</pre><p>This approach of continually growing the ignore file works and you’ll find many blog posts that describe exactly what we’re doing here. But it soon gets very, very tedious to keep excluding all of the files and directories that are <em>not</em> needed in the image, and after a while, you’ll find yourself turning a blind eye to any ‘harmless’ files that are exposed or that get inadvertently copied in.</p><p>But that means we’re back to square one again because we can <em>never really be sure</em> that we haven’t copied in something that shouldn’t be there, or that the image we’ve created couldn’t be smaller.</p><p>Luckily it turns out that there is a much easier way to maintain these exclusions, and it’s pretty much foolproof.</p><h3>Approach #3: Define Inclusions, Not Exclusions</h3><p>As we all know, the .dockerignore file contains a list of file patterns to exclude. But it doesn’t <em>just</em> contain that. The ignore file also contains a list of file patterns to <em>not</em> exclude.</p><p>Say we have a blog full of Markdown files that we want to exclude from our image because they will be converted to HTML beforehand and are therefore unnecessary at runtime. But let’s say also that we still want to include the README.md file from our project because it might help anyone looking inside a running container. We could achieve this goal with the following entries in a .dockerignore file:</p><pre># In .dockerignore<br># Exclude all Markdown files:<br>#<br>*.md</pre><pre># Now make an exception for one file:<br>#<br>!README.md</pre><p>With this file, when Docker starts the build process the only Markdown file that it will pass to the daemon is the README.md file.</p><h3>Exclude Everything</h3><p>So why don’t we use this feature to our advantage, and begin every .dockerignore file with a statement to <em>exclude everything</em>? If we start by saying that <em>nothing</em> will be sent to the Docker daemon when building an image, it will be almost impossible for us to accidentally include anything that’s secret or unecessary.</p><p>The pattern that we need in the .dockerignore file to ignore everything is simply an asterisk:</p><pre># In .dockerignore<br># Exclude everything:<br>#<br>*</pre><p>Now of course, if we exclude everything when we’re building the image then it won’t just be our secrets that don’t get copied in…nothing will! It’s like being certain of not losing a race by not entering at all.</p><p>So now we need to expand our .dockerignore file with information about the files that we <em>do</em> want to be included.</p><p>And those files should only be those that are mentioned in our Dockerfile.</p><h3>Only Include Those Files Referenced In Dockerfile</h3><p>Let’s assume that we’re building a Node app. And let’s also assume that we’re following best practice in our Dockerfile by installing all of the dependencies in one layer and our source code in another layer.</p><p>The ‘install dependencies’ step might look like this:</p><pre># In Dockerfile<br># Copy dependency definitions and then install:<br>#<br>COPY package.json .<br>ENV NODE_ENV=production<br>RUN npm install</pre><p>while the ‘copy source’ step could be as simple as this:</p><pre># In Dockerfile<br># Copy our app:<br>#<br>COPY app/ .</pre><p>When building the Docker image with this Dockerfile the Docker daemon must have access to both the package.json file and the app sub-directory. And since we’ve excluded everything at the top of the ignore file, every file or directory referred to in the build process must be explicitly allowed through.</p><p>We can easily add these files to our .dockerignore file with a ‘don’t exclude’ pattern:</p><pre># In .dockerignore<br># Exclude everything:<br>#<br>*</pre><pre># Now un-exclude package.json and the app folder:<br>#<br>!app<br>!package.json</pre><p>That’s it…we’re done. The Docker daemon won’t receive .git or test directories, or .env, or .gitlab-ci.yml, or Dockerfile, or docker-compose.yml or anything else.</p><p>Now all we have to do is keep the files .dockerignore and Dockerfile in sync–i.e., ensuring that they both refer to the same paths and files–and nothing else will accidentally get into our Docker images.</p><p>One of the many neat features of this approach is that if we forget to add a rule we’ll hear about it. If we indicate in our Dockerfile that we want to copy in the README or the LICENSE:</p><pre># In Dockerfile<br># Copy our app and the license:<br>#<br>COPY app/ .<br>COPY LICENSE .</pre><p>we’ll get an error at build time unless we add LICENSE to the .dockerignore file:</p><pre># In .dockerignore<br># Exclude everything:<br>#<br>*</pre><pre># Now un-exclude package.json and the app folder:<br>#<br>!app<br>!LICENSE<br>!package.json</pre><p>In fact, the patterns that we need in our .dockerignore file to specify what we want to <em>include</em> are simply the ADD and COPY entries in our Dockerfile, which is much simpler to manage than trying to keep track of what needs to be excluded.</p><h3>Problems With Approach #3</h3><p>Although this is my preferred solution and solves a lot of problems, there are still a couple of weaknesses. Although we’ll get notified by the build process if we are missing an important rule from our .dockerignore file, we <em>won’t</em> be notified if our rules are too liberal. So in our example above, if we later decide not to copy the LICENSE file when building, there is nothing to tell us that we can remove the pattern from .dockerignore.</p><p>And also, we still need to remember not to leave anything in the app directory that might get copied in. As it happens, the example I gave earlier of a .env file (in Approach #1) is now less of an issue since it is best kept in the root directory anyway.</p><h3>Conclusion</h3><p>I’ve tried a few different solutions to this problem over the years, but I think this ‘include file’ approach is about as minimal and easy to maintain as it gets. If the notion of ‘exclude everything and then un-exclude the files you want’ seems a bit quirky just flip things on their head and treat the .dockerignore file as if it was an ‘include’ file–in other words see it as ‘only the files listed will be included in the build’.</p><p>I think I’d prefer it if this was the default behaviour from Docker, because then we would get both security and minimal image size as the default behaviour, right out of the box. But unless a .dockerinclude feature is added to Docker any time soon, then the solution described here is about as good as it will get.</p><p><em>Originally published at </em><a href="https://youknowfordevs.com/2018/12/07/getting-control-of-your-dockerignore-files.html"><em>youknowfordevs.com</em></a><em> on December 7, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4543b04756c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using _writev() to Create a Fast, Writable Stream for ElasticSearch]]></title>
            <link>https://medium.com/@mark.birbeck/using-writev-to-create-a-fast-writable-stream-for-elasticsearch-ac69bd010802?source=rss-3576792052c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac69bd010802</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Mark Birbeck]]></dc:creator>
            <pubDate>Mon, 29 Oct 2018 00:00:00 GMT</pubDate>
            <atom:updated>2018-10-31T15:56:28.086Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*smUVxmA9corN7K72sCcLDg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/QZ0XBf7kVQ0?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Brian Botos</a> on <a href="https://unsplash.com/search/photos/streams-brian-botos-103838?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>We all know how great Node streams are. But it wasn’t until I recently needed to create (yet another) writable stream wrapper for ElasticSearch that I realised just how much work the streaming APIs can do for you. And in particular how powerful the _writev() method is.</p><p>I was looking to wrap the ElasticSearch client in a writable stream so that I could use it in a streaming pipeline. I’ve done this many times before, in many different contexts–such as creating ElasticSearch modules to be used with Gulp and Vinyl–so I was all set to follow the usual pattern:</p><ul><li>my first step would be to set up an ElasticSearch client, using the ElasticSearch API;</li><li>I’d then add a function that gets called with whatever entry should be written to the ElasticSearch server;</li><li>to speed writing up I wouldn’t write this entry straight to the server, but instead buffer each of the entries in an array (the size of which would of course be configurable). Then, once the buffer was full the entries would be written en masse to the ElasticSearch server using the <a href="https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-bulk">bulk update API</a> (which is much, much faster than writing records one at a time);</li><li>when the source of the data for the writable stream indicates that there is no more data to send I’d check whether there is any data still in the buffer, and if so call a ‘flush’ function;</li><li>and once all data is flushed, I’d delete the client.</li></ul><p>None of this will probably surprise you, and you’d no doubt write an interface to ElasticSearch in much the same way yourself.</p><p>But what might surprise you–especially if you haven’t looked at <a href="https://nodejs.org/api/stream.html#stream_writable_streams">Node’s Writable Streams</a> for a while–is how many of these steps could be done for you by the Node libraries.</p><p>To kick things off, let’s create a class that extends the <a href="https://nodejs.org/api/stream.html#stream_class_stream_writable">Node stream </a><a href="https://nodejs.org/api/stream.html#stream_class_stream_writable">Writable class</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/357cc30912568976e0c4e3f511a1083f/href">https://medium.com/media/357cc30912568976e0c4e3f511a1083f/href</a></iframe><p>Now we can start adding each of the features in our list.</p><h3>Creating an ElasticSearch Client</h3><p>The first step we described above was to create an ElasticSearch client, using the <a href="https://www.npmjs.com/package/elasticsearch">ElasticSearch API</a>, so let’s add that to the constructor of our class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c61e5e9f84c302d812a695093a7aed33/href">https://medium.com/media/c61e5e9f84c302d812a695093a7aed33/href</a></iframe><p>We can now call our class with some configuration, and we’ll have a writable stream with an ElasticSearch client:</p><pre>const sink = new ElasticSearchWriteStream({ host: &#39;es:9200&#39; })</pre><p>Of course, this stream doesn’t do anything yet, so let’s add the method that the streaming infrastructure will call whenever some other stream wants to write a record.</p><h3>Writing Records</h3><p>When implementing a writable stream class, the only method we need to provide is <a href="https://nodejs.org/api/stream.html#stream_writable_write_chunk_encoding_callback_1">_write()</a> which is called whenever new data is available from the stream that is providing that data. In the case of our ElasticSearch stream, to forward the record on we only need to call <a href="https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-index">index()</a> on the client that we created in the constructor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3942961d03485b5f01a837fcbcbf1343/href">https://medium.com/media/3942961d03485b5f01a837fcbcbf1343/href</a></iframe><p>Note that once we’ve successfully written our record we then call next() to indicate to the streaming infrastructure that we’re happy to receive more records, i.e., more calls to _write(). In fact, if we <em>don’t</em> call next() we won’t receive any more data.</p><h3>Index and Type</h3><p>When writing to ElasticSearch we need to provide the name of an index and a type for the document, so we’ve added those to the config that was provided to the constructor, and we can then pass these values on to the call to index(). We’ll now need to invoke our stream with something like this:</p><pre>const sink = new ElasticSearchWriteStream({<br>  host: &#39;es:9200&#39;,<br>  index: &#39;my-index&#39;,<br>  type: &#39;my-type&#39;<br>})</pre><h3>Buffering</h3><p>As things stand, we already have a working writable stream for ElasticSearch. However, if we’re planning to insert hundreds of thousands of records then it will be slow, and a simple optimisation would be to buffer the records and use the <a href="https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-bulk">bulk update API</a>.</p><p>The bulk update API allows us to perform many operations at the same time, perhaps inserting thousands of records in one go. Rather than defining each record to be inserted as we did with the index() call, we need to create <a href="https://www.elastic.co/guide/en/elasticsearch/reference/6.3/docs-bulk.html">a list that contains pairs of entries</a>; one that indicates the operation to carry out–such as an insert or update–and one that contains the data for the operation.</p><h3>Using an Array</h3><p>The usual ‘go to’ implementation here would be to create an array in the class constructor, and then push the rows of data into that array with each call to _write(). Then, when the array is full, construct a call to the bulk API, still within the _write() method.</p><p>The problem here though, is that in order to properly implement backpressure we need quite a sophisticated interaction with the next() function; we need to allow data to flow to our stream as long as the buffer is not full, and we need to prevent new data arriving until we’ve had a chance to write the records to ElasticSearch.</p><p>It turns out that the Node streaming API can manage the buffer <em>and</em> the backpressure for us.</p><h3>_writev()</h3><p>Although the bare minimum we need to provide in our writable stream class is a _write() method, there is another method we can create if we like, called <a href="https://nodejs.org/api/stream.html#stream_writable_writev_chunks_callback">_writev()</a>. Where the first function is called once per record, the second is called with a <em>list</em> of records. In a sense, the streaming API is doing the whole <em>create an array and store the items until the array is full and then send them on</em> bit for us.</p><p>Here’s what our _writev() method would look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dc1111d52d2e3da709461a2be7ad3b2/href">https://medium.com/media/5dc1111d52d2e3da709461a2be7ad3b2/href</a></iframe><p>The streaming API will buffer records and then at a certain point hand them all over to our _writev() function. This gives us the main benefit of buffering data–that we can then use the bulk update API–without actually having to create and manage a buffer, or look after backpressure.</p><h3>Buffer Size</h3><p>If we’d created the buffer ourselves we’d have had complete control over how big the buffer is, but can we still control the buffer size if the Node streaming API is managing the buffer for us?</p><p>It turns out we can, by using the <a href="https://nodejs.org/api/stream.html#stream_constructor_new_stream_writable_options">generic </a><a href="https://nodejs.org/api/stream.html#stream_constructor_new_stream_writable_options">highWaterMark feature</a>, which is used throughout the streams API to indicate how large buffers should be.</p><p>The best way to implement this in our writable stream is to have two parameters for our constructor:</p><ul><li>one which will provide configuration for the ElasticSearch connection, such as server address, timeout configuration, the name of the index and type, and so on;</li><li>another which provides settings for the writable stream itself, such as highWaterMark.</li></ul><p>This is easily added, like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe09eb6fdeeed937125a738c0b7006a9/href">https://medium.com/media/fe09eb6fdeeed937125a738c0b7006a9/href</a></iframe><p>And now we can control the size of the buffer–and hence, the number of records that are being written by each call to the bulk API–by setting options in the constructor:</p><pre>const esConfig = {<br>  host: &#39;es:9200&#39;,<br>  index: &#39;my-index&#39;,<br>  type: &#39;my-type&#39;<br>}</pre><pre>const sink = new ElasticSearchWriteStream(<br>  esConfig,<br>  { highWatermark: 1000 }<br>)</pre><h3>Closing the ElasticSearch Client</h3><p>All that remains from our original checklist is to close the client when there is no more data to receive. To implement this, all we need to do is to add another optional method, <a href="https://nodejs.org/api/stream.html#stream_writable_destroy_err_callback">_destroy()</a>. This is called by the streaming infrastructure when there is no more data, and would look something like this:</p><pre>_destroy() {<br>  return this.client.close()<br>}</pre><h3>Conclusion</h3><p>As you can see, the Node streaming API has done much of the work of buffering, for us, which means that we don’t get bogged down with trying to implement backpressure properly. By providing us with the methods _write(), _writev() and _destroy() our code ends up very clean, and focuses our attention on only the parts required to spin up and destroy a connection to ElasticSearch, and the functions required to write a single record, or a batch. The full implementation looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42bcf3ba5c1265f2ba7b81af38947193/href">https://medium.com/media/42bcf3ba5c1265f2ba7b81af38947193/href</a></iframe><p><em>Originally published at </em><a href="https://youknowfordevs.com/2018/10/29/using__writev-to-create-a-fast-writable-stream-for-elasticsearch.html"><em>youknowfordevs.com</em></a><em> on October 29, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac69bd010802" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t Install Node Until You’ve Read This (Or, How to Run Node the Docker Way)]]></title>
            <link>https://medium.com/@mark.birbeck/dont-install-node-until-you-ve-read-this-or-how-to-run-node-the-docker-way-21237f932841?source=rss-3576792052c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/21237f932841</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Mark Birbeck]]></dc:creator>
            <pubDate>Sat, 20 Oct 2018 15:09:23 GMT</pubDate>
            <atom:updated>2018-10-31T12:58:27.392Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This post first appeared </em><a href="https://youknowfordevs.com/2018/07/01/dont-install-node-until-youve-read-this.html"><em>here</em></a><em>, on </em><a href="https://youknowfordevs.com/"><em>You Know, For Devs</em></a><em>, my software development blog.</em></p><p>We need Node for some application or other — perhaps we’re creating a microservice or just want to follow along with a tutorial.</p><p>But most places you start with suggest that the first step is to install Node for your operating system. Perhaps you’re on a Mac so now you have to start thinking about whether you should also install Homebrew or MacPorts.</p><p>Or you’re on Ubuntu so you head in the apt-get direction…except before you know it, to get the latest version you find yourself using curl to pipe some script to your shell.</p><p>Windows? You could just use the Windows installer but as with macOS, you ponder whether it’s time to embrace the Chocalatey or Scoop package managers.</p><p>In this blog post, we’ll look at how skipping over all of this and heading straight to a Docker environment makes it much easier to manage your Node applications and development workflow, and what’s more, gets you going with best practices right from the start.</p><h3>Docker First</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*NqnapEy7R8xhConxjtjbBQ.png" /><figcaption>Docker Logo</figcaption></figure><p>Whichever route we go with installing Node the OS-specific way, we now have two problems; the first is that the way that we install Node is different on each platform, and damn, that’s annoying. And number two we now have Node installed <em>globally </em>on our laptop.</p><p>Why so sad?</p><p>Well now if we want to use different versions of Node for different projects we have to faff about with something like nvm. (And if you were planning on running a Python project it’s the same story, with virtualenv.)</p><p>So do yourself a favour and <a href="https://docs.docker.com/install/">get Docker installed</a>. True, how you install Docker will also be different for different platforms — Ubuntu is slightly different to Mac and Windows. But this initial effort will repay you later because now you’ll have a <em>standard </em>way to install Node, Ruby, Python, TensorFlow, R…whatever language you’re using for your projects — or perhaps more likely nowadays, <em>languages</em> — they all just got way easier to manage.</p><p>So assuming that you now have Docker, let’s get a development environment set up so that you can get back to that tutorial or project.</p><h3>Running Node</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*3hJxEgGNz7R9rAVg_1Dkaw.png" /><figcaption>Node Logo</figcaption></figure><p>First, create a new directory for your project:</p><pre>mkdir new-project &amp;&amp; cd new-project<br></pre><p>and then launch the latest version of Node:</p><pre>docker run -it --rm node:10.12.0-alpine</pre><p>If you haven’t run this version of Node before, Docker will download it for you. After a bit of toing and froing, you’ll be left with the usual Node command prompt. Type something like 5+6 and press return to check all is well, and then press [CTRL]+D to exit.</p><p>If you are reading this in the future you might want to find out what the most recent version number is; just head to the <a href="https://hub.docker.com/_/node/">Docker Hub page for the official Node Docker image</a>.</p><h4>Interactive Containers</h4><p>We executed the docker run command with a couple of options. The first — the -it part — is a combination of the two options, -i and -t. It’s these options together that mean we can interact with the running container as if it was our normal shell, accepting input from our keyboard and sending output to our display.</p><h4>Disposable Containers</h4><p>The --rm option causes the container to be deleted when we exit. It’s a good habit to get into to delete containers as we go along because it gets us into the mindset that our containers are <em>disposable</em>. This is particularly important when it comes to deployment because we don’t want our container to hold any state internally — any updates or processing should result in writes to external services such as a connected file system, cloud storage, queues, and so on. By taking this approach it’s really easy to upgrade our images to newer versions when necessary — we just throw away the old ones and launch completely new ones.</p><p>(It will also make it easier to scale since we can just launch a bunch more containers when we need to do more work, and provided that all state is maintained <em>outside </em>of the containers this becomes straightforward.)</p><h4>Bonus Points: No SSH</h4><p>If you really want to get into good habits with your Docker containers then also avoid the temptation to SSH into a running container to see what’s going on. There’s nothing worse than making a tweak to fix something, logging out, and then forgetting what was changed. The service may now be running again and your boss thinks you’re flavour of the month, but it’s fragile. Deploy again and you overwrite those changes. Far better to fix the problem in your deployment scripts, then simply tear down the faulty service and launch another. The changes are now clear to see in source control, and reproducible.</p><h4>Versions</h4><p>Beyond the command-line options to docker run, there are also a few things to note about the Node Docker image that we’ve used (the node:10.12.0-alpine part).</p><p>First, it’s worth being specific about the version number of Node that you are using, since it makes it easier to force updates and to know what is being deployed. If we were to only specify ‘version 10’:</p><pre>docker run -it --rm node:10-alpine</pre><p>or even ‘the latest version of node’:</p><pre>docker run -it --rm node:alpine</pre><p>then although on the first time through we’ll get 10.12.0, once the images are updated at some later point, we won’t pick up the same version on subsequent runs. At some point using node:10-alpine in the command will cause us to pick up version 10.13.0 or 10.14.0 of Node. And using node:alpine will at some point cause us to get version 11 and onwards.</p><p>However, if we choose a specific version like 10.12.0 then although we also won’t get updates automatically, it will be a simple case of updating to 10.12.1 in our build files, when we are ready to force a download of the latest changes.</p><p>This is particularly important when it comes to deploying applications later on (or sharing your code with other people) since you want to be able to control what version appears where. And perhaps more to the point, when you are troubleshooting you want to know for sure what version was used.</p><h4>Controlled Updates</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*CoTVIjFbzBDfY6V4MG9Nwg.jpeg" /><figcaption>Architecting for Scale, by Lee Atchison</figcaption></figure><p>It’s tempting, of course, to want to ‘always use the latest’; after all, the latest will be faster, won’t it? And won’t it have the latest security patches? This is true of course, but in the <a href="https://amzn.to/2NRAzNZ">quest for building a reliable infrastructure</a> (affiliate link), you should aim to <em>control </em>updates to the foundations. This means that if you have a bunch of code that is working fine on version 10.12.0, nicely passing all of its tests and performing well, then a move to another version of Node should be something that is planned and tested. The only <em>real </em>pressure to move versions comes with the point releases such as 10.12.1 or 10.12.2, since they will contain security patches and bug fixes; a move to 10.13 or higher is certainly a ‘nice to have’, but if your code is working and your service is running, then you will definitely want to consider whether your time is better spent elsewhere.</p><h4>Base OS</h4><p>The second thing to note about the Node Docker image selection, is that we’ve used the alpine version of the image which uses <a href="https://alpinelinux.org/about/">Alpine Linux</a> as the base operating system. This is the lightest of the Node images, and only provides the bare minimum of an operating system to get Node running — we’re most likely creating microservices or Lambda functions, after all.</p><p>You’ve probably come across the alpine project but if you haven’t, take a look; it’s being used right across the Docker ecosystem to keep Docker images light.</p><p>It should be said as well that ‘light’ doesn’t just mean small for the sake of size — that’s all good of course since it reduces the amount of data flying around your network. But in the case of a deployed service ‘light’ also means reducing the number of moving parts that can go wrong. If you start with something big like a Ubuntu base image you’re bringing in a bunch of unnecessary code and so increasing the possibility of something going wrong that wasn’t important in the first place. Imagine some nefarious outsider taking advantage of a security hole in Ubuntu, in a service that you didn’t even need!</p><p>(You may have come across the expression ‘reducing attack surface’; this is <em>exactly </em>what is being referred to.)</p><p>So keep it small, tight, and controlled…and most of all, <em>secure</em>.</p><h4>Building Your Own Base Images — Don’t!</h4><p>And it should probably go without saying that you don’t want to be building your own base images. The various Docker Node images, for example, are maintained by the Node project itself, so if anyone is going to know how to build a secure, fast and reliable image it’s them. What’s more, if anything does go wrong there is a whole community of people using the image and reporting issues; you’ll invariably find a solution very quickly.</p><h3>A Development Environment</h3><p>So we have chosen a Node image, and we have it running from the command line. Let’s press on with our development environment.</p><p>In order to be able to update files in our project directory, we need to give our Node application ‘access’ to that directory. This is achieved with the ‘volume’ option on the Docker command. Try this:</p><pre>docker run -it --rm \<br>  -v ${PWD}:/usr/src/app \<br>  node:10.12.0-alpine \<br>    /bin/sh -c &quot;touch /usr/src/app/README.md&quot;<br></pre><p>This will:</p><ul><li>create a directory <em>inside </em>your Docker container (at /usr/src/app), and make it refer to your current working directory <em>outside </em>your container (the ${PWD} part);</li><li>launch the Bash shell (rather than Node), to run the touch command which will create a README file.</li></ul><p>The command should exit cleanly. Check your current directory to ensure that the file has been created:</p><pre>$ ls -al<br>total 0<br>drwxr-xr-x 4 markbirbeck staff 136 1 Jul 13:26 .<br>drwxr-xr-x 10 markbirbeck staff 340 1 Jul 11:47 ..<br>-rw-r — r — 1 markbirbeck staff 0 1 Jul 12:58 README.md</pre><p>This is a laborious way to create a file, but we just wanted to check that our Docker container was able to ‘see’ our laptop project directory and that it could update files within it.</p><p>We now have <em>two </em>ways that we can work on our project: we can either fire up vi from <em>inside </em>the container and make edits which will immediately be mirrored to our working directory on our laptop; or we can use our familiar laptop tools — like Visual Studio Code, Sublime Text, and so on — to create and edit files <em>outside </em>the container, knowing that changes will be immediately mirrored to the /usr/src/app directory within the container.</p><p>Either way, we can now develop in pretty much the same way as we normally would on our laptop, but with an easy to manage Node environment, courtesy of Docker.</p><h3>Opening Ports</h3><p>One last thing. Let’s say we got started with Node by following <a href="https://nodejs.org/en/docs/guides/getting-started-guide/">the little intro on the Node site</a>. You’ll see that it sets up a ‘hello world’ web server and suggests that the page can be viewed at <a href="http://localhost:3000`">http://localhost:3000</a>. Go ahead and follow the intro, and create that app.js file in your current directory…but there’s no point in running it since as things stand with our <em>Docker </em>development environment approach, this server won’t work.</p><p>However, just as we saw earlier that we can map directories between the host and the container we can also map ports. The first step is to add the -p option to our command like this:</p><pre>docker run -it --rm \<br>  -v ${PWD}:/usr/src/app \<br>  -p 3000:3000 \<br>  node:10.12.0-alpine \<br>    /bin/sh</pre><p>We can now access port 3000 <em>inside </em>the container by making requests to port 3000 on our host machine, which satisfies the <a href="http://localhost:3000`">http://localhost:3000</a> part of the Node tutorial.</p><p>But there is one last minor tweak we’ll need to make; when the server launches it will listen on the IP address 127.0.0.1 which would be fine on our laptop, but is no good inside a container. We might use this address to prevent our server being reached from outside of our laptop, but in the case of a Docker container there is a network connection from our laptop to the container (think of them as separate machines), so keeping things ‘private’ <em>inside </em>the container will just mean that nothing is reachable.</p><p>All we need to do is change the file that was provided in the intro on the Node site, modifying the hostname variable from 127.0.0.1 to 0.0.0.0. This will tell the server to listen to <em>all </em>IP addresses within the container, not just localhost. We could still ensure that our server is not reachable from outside of our laptop if we wanted to, by modifying the port mapping part of the Docker command to this:</p><pre>docker run -it --rm \<br>  -v ${PWD}:/usr/src/app \<br>  -p 127.0.0.1:3000:3000 \<br>  node:10.12.0-alpine \<br>    /bin/sh</pre><p>I.e., the mapping from host port to container port should only take place on 127.0.0.1 rather than on 0.0.0.0 (which is the default for a port mapping).</p><p>Whether you modify the port setting when you run the command or not, once the app.js file has this minor change then the server can be launched from inside the container; from the command-line <em>inside </em>the container, change directory to where the app.js file is, and launch it:</p><pre>cd /usr/src/app<br>node app.js</pre><p>Now you should be able to reach the ‘hello world’ page from the host machine by visiting <a href="http://localhost:3000`">http://localhost:3000</a>.</p><h3>Next Steps</h3><p>Assuming all is well, we can now carry on with whatever project or tutorial we were following. Anywhere that the tutorial tells us to run something from the command-line we simply make sure to do it from <em>inside </em>the container by firing up the Bash shell. If the project requires that we expose a different port then just change the -p option (or add more mappings if necessary).</p><p>There are a lot more ways that we can improve our development environment; we can:</p><ul><li><a href="http://youknowfordevs.com/2018/07/02/your-development-workflow-just-got-better-with-docker-compose.html">bring in Docker Compose to shorten our command lines</a>;</li><li>add more directory mappings so that modules installed with npm install stay <em>inside </em>our container;</li><li>create test containers that include runners like Mocha or TAP;</li><li>launch local NGINX servers that will mirror our live deployments.</li></ul><p>But all of these will build on the basic setup we have here. We’ll drill into these techniques in future posts.</p><p>Good luck with your projects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21237f932841" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Development Workflow Just Got Better, With Docker Compose]]></title>
            <link>https://medium.com/@mark.birbeck/your-development-workflow-just-got-better-with-docker-compose-f71e50a2f3d7?source=rss-3576792052c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f71e50a2f3d7</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Mark Birbeck]]></dc:creator>
            <pubDate>Mon, 02 Jul 2018 00:00:00 GMT</pubDate>
            <atom:updated>2018-10-31T13:09:10.468Z</atom:updated>
            <content:encoded><![CDATA[<p>In a previous post we saw how to <a href="https://youknowfordevs.com/2018/07/01/dont-install-node-until-youve-read-this.html">set up our basic Node development environment using Docker</a>. Our next step is reduce the size of these unwieldy docker run commands. This is not just because of their unwieldiness but also because if we just type them from the command-line then we don’t have an easy way to share what we’re doing–not just with other people but with ourselves, tomorrow, when we’ve inevitably forgotten what we were doing today!</p><p>So before we forget the command we were running in the previous post, let’s lock it down in a file that we can use repeatedly.</p><p>But in what file, you ask?</p><p>The tool we’re going to use to capture these kinds of commands is Docker Compose. This app will have been installed for you when you installed Docker (assuming that you took the advice of our previous post to <a href="https://youknowfordevs.com/2018/07/01/dont-install-node-until-youve-read-this.html#docker-first">embrace Docker</a>). Docker Compose is an <em>incredibly</em> handy utility because it allows us to use a YAML file to create definitions for Docker commands, rather than having to use command-line options. This means we can easily share and version our commands.</p><p>The YAML file can also be used to manage a group of containers that we want to launch at the same time–perhaps our microservice needs a MySQL database or a RabbitMQ queue–and as if that wasn’t enough, the same file format can also be used to describe a Docker swarm stack–a collection of services that will all run together–when it comes time to deploy our application.</p><p>Just as in the previous post we suggested that applications should no longer be installed locally but instead run inside Docker containers, now we want to just as strongly argue that no activity that can be performed in the creation of your application–whether linting, testing, packaging, deploying–should be carried out without it being captured in a Docker Compose file.</p><p>But before we get too excited, let’s go back to the command we were running in the earlier post (which launches a development container in which we run Node) and let’s convert it to use Docker Compose.</p><h3>A Docker Compose Configuration File</h3><p>Recall that the command we were running was:</p><pre>docker run -it --rm -v ${PWD}:/usr/src/app -p 127.0.0.1:3000:3000 \<br>  node:10.5.0-alpine /bin/sh</pre><p>To turn this into a Docker Compose file, fire up your favourite editor and create a file called docker-compose.yml into which you’ve placed the following:</p><pre>version: &quot;3.2&quot;</pre><pre>services:<br>  dev:<br>    image: node:10.5.0-alpine<br>    ports:<br>    - &quot;127.0.0.1:3000:3000&quot;<br>    volumes:<br>    - .:/usr/src/app<br>    command: [&quot;/bin/sh&quot;]</pre><p>You can probably figure out which parts of the original command-line map to which entries in this Compose file, so we’ll just flag up a couple of things that might not be immediately obvious.</p><p>First, the entry dev is just the name of our <em>service</em>. It can be anything we like, and there can be more than one of these entries in a file. We’ll see in a moment how it’s used to indicate what we want to launch.</p><p>(A service is the term Docker Compose uses to describe running containers. The reason it doesn’t use the term <em>container</em> in the way that we would if we were using the docker run command is that a service has extra features such as being able to comprise more than one instance of a container.)</p><p>Next you probably noticed that the port mapping now has quotes around it; on the command line we had -p 127.0.0.1:3000:3000 whilst in the compose file we have &quot;127.0.0.1:3000:3000&quot;. This is a best practice due to the way that YAML files are processed. If a port lower than 60 is mapped and no IP address is specified (for example, 40:40) then the parser will not treat it as 40 followed by 40, but as a base 60 number. You <em>could</em> just remember that you need quotes when using ports below 60, but most Docker Compose files you’ll see will have quotes placed around <em>any</em> port number, which is a little easier to remember.</p><p>Finally, you will also have spotted that the ${PWD} part of our docker run command has now been replaced with ., i.e., the current directory. Docker Compose doesn’t need the environment variable when mapping volumes, which makes things a bit easier. Paths in the YAML file are always relative to the file itself (and relative paths are supported).</p><h3>Launching Our Development Container</h3><p>Now we have our configuration set up it’s a simple matter of running the Docker Compose command with the name of our service. Run the following command and you should have launched the development environment again:</p><pre>docker-compose run --rm --service-ports dev</pre><p>Ok…so it’s still not the shortest command on the block–we’ll see in a future post how we can get this down further. But it’s a lot easier to remember than the long docker run command we had before. And what’s more, it will <em>always be the same</em> no matter what changes you make to the configuration file; any additional options we want to add to our docker run will go in our Docker Compose file, clearly documented and under source control.</p><p>Just to wrap up this section, we’ll quickly explain the parameters that we need to pass to docker-compose run. The first is --rm which is exactly the same as the option we were using with docker run–when the command has finished running our container will be deleted.</p><p>The second is --service-ports which instructs Docker Compose to make available any port mappings we define in the Compose file. It’s a little annoying to have to add this parameter, and you’ll find many discussion threads that argue that this behaviour should be the default. But the logic is fair; if we are launching a number of connected services, such as a web server and a MySQL database, we don’t necessarily want every single port to be mapped to our host machine. In the example of a web server and MySQL server for example, there is no need to expose MySQL’s port 3306 on our laptop since it is only needed by the web server connection to the backend. Docker Compose will create a network that the web server and MySQL can use to communicate with each other.</p><p>So there we have it; run that command, and we will get a shell prompt, and then we can launch our web server in exactly the same way as we did in the previous post, when using docker run:</p><pre>cd /usr/src/app<br>node app.js</pre><h3>Working Directory</h3><p>We said a moment ago that one of the advantages of using Docker Compose is that we can add additional options without changing the way we run the command. An example would be to get Docker to change to the working directory for us, i.e, to remove the need for the cd /usr/src/app step in our sequence, above.</p><p>To do this we only need to add the working_dir option to the YAML file:</p><pre>version: &quot;3.2&quot;</pre><pre>services:<br>  dev:<br>    image: node:10.5.0-alpine<br>    working_dir: /usr/src/app<br>    ports:<br>    - &quot;3000:3000&quot;<br>    volumes:<br>    - .:/usr/src/app<br>    command: [&quot;/bin/sh&quot;]</pre><p>And to stress again, we still launch our development environment in exactly the same way as we did before–the only changes are to the configuration file:</p><pre>docker-compose run --rm --service-ports dev</pre><p>This time our command-line prompt will have us sitting in the correct directory, and we can launch the server directly:</p><h3>Changing Launch Commands</h3><p>But we can go a bit further here; we’ll rarely need to be ‘inside’ the container doing stuff, since we’ll be using our favourite editor running on our laptop (remember <a href="https://youknowfordevs.com/2018/07/01/dont-install-node-until-youve-read-this.html#a-development-environment">we’ve mapped our project directory into the container so that our laptop and the container both have access to our files</a>). So we’ll probably find ourselves more often than not invoking our container and then running the server. So we could change the command that is run inside the container from one that launches a Bash shell to one that launches the server:</p><pre>version: &quot;3.2&quot;</pre><pre>services:<br>  dev:<br>    image: node:10.5.0-alpine<br>    working_dir: /usr/src/app<br>    ports:<br>    - &quot;3000:3000&quot;<br>    volumes:<br>    - .:/usr/src/app<br>    command: [&quot;/bin/sh&quot;, &quot;-c&quot;, &quot;node app.js&quot;]</pre><h3>Making a Clean Exit</h3><p>You probably spotted that the command we added was not what we might have expected:</p><pre>    command: [&quot;node&quot;, &quot;app.js&quot;]</pre><p>but:</p><pre>    command: [&quot;/bin/sh&quot;, &quot;-c&quot;, &quot;node app.js&quot;]</pre><p>The background as to why is that if we use the first version of the command which simply runs node with app.js as the parameter, then when we try to exit the server with [CTRL]+C nothing will happen and we’ll have to find some other way to kill the server. This is because the Node app does not process a SIGTERM signal (a [CTRL]+C) correctly when Node is running as the primary, top-level application in a container (what you’ll often see described as <em>running as PID 1</em>).</p><p>However the Bash shell <em>does</em> handle the whole SIGTERM dance correctly, and will cleanly shut down our server when it receives [CTRL]+C. So all we need to do is run our server inside a shell.</p><p>If you need (or want) to understand this in more detail then <a href="https://www.google.co.uk/search?q=pid+1+docker+node">search online for something along the lines of “pid 1 docker node”</a> and you’ll find a number of articles. If you just want to cut to the chase then read the section <a href="https://github.com/nodejs/docker-node/blob/master/docs/BestPractices.md#handling-kernel-signals">Handling Kernel Signals</a> in the <a href="https://github.com/nodejs/docker-node/blob/master/docs/BestPractices.md">best practises guidance for using Node in Docker</a>.</p><h3>Multiple Services</h3><p>Of course, if we think we might need <em>both</em> of these commands–the one to launch a Bash shell inside the container, ready for playing around, and the one to launch the server–then instead of overwriting our first, we can just add a second entry to our Docker Compose file:</p><pre>version: &quot;3.2&quot;</pre><pre>services:<br>  shell:<br>    image: node:10.5.0-alpine<br>    working_dir: /usr/src/app<br>    ports:<br>    - &quot;3000:3000&quot;<br>    volumes:<br>    - .:/usr/src/app<br>    command: [&quot;/bin/sh&quot;]</pre><pre>  serve:<br>    image: node:10.5.0-alpine<br>    working_dir: /usr/src/app<br>    ports:<br>    - &quot;3000:3000&quot;<br>    volumes:<br>    - .:/usr/src/app<br>    command: [&quot;/bin/sh&quot;, &quot;-c&quot;, &quot;node app.js&quot;]</pre><p>We’ve changed the name of the shell version from dev to shell to indicate what it’s used for, which means we can now launch the server with:</p><pre>docker-compose run --rm --service-ports serve</pre><h3>Don’t Repeat Yourself</h3><p>One last tip involves a way to reuse the common settings we have in our file. As you can see the only difference between our two services is in the command value. Ideally we’d like to place all of the other values into some common collection and share them between both services.</p><p>This is possible in <a href="https://docs.docker.com/compose/compose-file/">version 3.4 onwards of the Docker Compose file format</a> by using YAML anchors:</p><pre>version: &quot;3.4&quot;</pre><pre>x-default-service-settings:<br>  &amp;default-service-settings<br>    image: node:10.5.0-alpine<br>    working_dir: /usr/src/app<br>    ports:<br>    - &quot;3000:3000&quot;<br>    volumes:<br>    - .:/usr/src/app</pre><pre>services:<br>  shell:<br>    &lt;&lt; : *default-service-settings<br>    command: [&quot;/bin/sh&quot;]</pre><pre>  serve:<br>    &lt;&lt; : *default-service-settings<br>    command: [&quot;/bin/sh&quot;, &quot;-c&quot;, &quot;node app.js&quot;]</pre><p>So note first that the version value has been updated at the top of the document. Then, any block that we want to create for sharing goes at the top level with an x- prefix–that’s how we tell Docker Compose not to process this block as some configuration.</p><p>Within the custom block we set an anchor (the &amp;default-service-settings part) and give it any name we want. Then finally we can refer to that block by referencing the anchor with the &lt;&lt; syntax.</p><p>We’ve taken our <a href="https://youknowfordevs.com/2018/07/01/dont-install-node-until-youve-read-this.html">original </a><a href="https://youknowfordevs.com/2018/07/01/dont-install-node-until-youve-read-this.html">docker run command</a> and converted it to use Docker Compose, making complex configurations much easier to manage. We’ve also added some additional commands to help with our development process. And we also now have a way to keep a collection of commands under source control. We can now build on this approach to:</p><ul><li>add more directory mappings so that modules installed with npm install stay <em>inside</em> our container;</li><li>add entries for test containers that include runners like Mocha or TAP;</li><li>add entries for commands that help the build process, for example using Webpack or Parcel;</li><li>launch local Nginx servers that will mirror our live deployments.</li></ul><p>We’ll drill into these techniques and more in future posts.</p><p>Good luck with your projects!</p><p><em>Originally published at </em><a href="https://youknowfordevs.com/2018/07/02/your-development-workflow-just-got-better-with-docker-compose.html"><em>youknowfordevs.com</em></a><em> on July 2, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f71e50a2f3d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>