<?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 Mac Rusek on Medium]]></title>
        <description><![CDATA[Stories by Mac Rusek on Medium]]></description>
        <link>https://medium.com/@macrusek?source=rss-ddcc02cd7cc1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*xLcXfuI_k2cZtBkv</url>
            <title>Stories by Mac Rusek on Medium</title>
            <link>https://medium.com/@macrusek?source=rss-ddcc02cd7cc1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:41:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@macrusek/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[How to Improve Docker Image Size With Layers]]></title>
            <link>https://medium.com/better-programming/how-to-improve-docker-image-size-with-layers-3ad62be0da9b?source=rss-ddcc02cd7cc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ad62be0da9b</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Mac Rusek]]></dc:creator>
            <pubDate>Thu, 23 Apr 2020 22:05:16 GMT</pubDate>
            <atom:updated>2020-04-23T22:05:16.741Z</atom:updated>
            <content:encoded><![CDATA[<h4>Optimize your containers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eABiEHEHdNkjGXoS" /><figcaption>Photo by <a href="https://unsplash.com/@hasanalmasi?utm_source=medium&amp;utm_medium=referral">Hasan Almasi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Today we’re going to dive deeper into Docker’s union file system (UFS) layers. I’ll try to explain how layers work and then how to use them properly to reduce the size of your images.</p><p>Have you ever wondered why your Docker images ended up so huge? Or maybe you’ve deleted or uninstalled bits from your image, and size didn’t change. That’s because you’re working against UFS’ layers. As soon as you get an idea of how layers work, it’ll be easier for you to create smaller images and do way better versioning of all changes. Let’s start from the beginning: What are those layers?</p><p>Note: If you’re looking for a solution on how to minimize the size of your images, just scroll past the layers part.</p><h3>Layers Explained</h3><p>Docker containers are made of layers. Whenever we add, change, or delete files, we add a new layer on top of the old one. A combination of all those layers or the <em>union</em> is what the user or container sees; it’s a top-to-bottom view. On the other hand, the actual layered perspective is different.</p><p>Let’s start with the example. We’ll create a new container using an Ubuntu image and add a new file to it.</p><pre>docker run --name mod_ubuntu ubuntu:latest touch /mychange</pre><p>We can see all the changes to the file system with docker diff and al. layers with docker history. Let’s check it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ymrExsNkspYYVnGIYJeKg.png" /><figcaption>Nickoloff, J. (2016) <a href="https://www.manning.com/books/docker-in-action-second-edition">Docker in Action</a></figcaption></figure><p>We can see all the changes to the file system with <a href="https://docs.docker.com/engine/reference/commandline/diff/">docker diff</a> and all layers with <a href="https://docs.docker.com/engine/reference/commandline/history/">docker history</a>. Let’s check it.</p><pre>docker diff mod_ubuntu</pre><pre># output<br>A /mychange</pre><p>Letter A means that the file was added. There are three options in total, and these are:</p><ul><li>A — A file or directory was added</li><li>C — A file or directory was changed</li><li>D — A file or directory was deleted</li></ul><p>Let’s check all the layers in our new image. To do that, we first have to commit it and tag it.</p><pre>docker commit mod_ubuntu mod_ubuntu:latest</pre><p>Then we can run history to see all the layers.</p><pre>docker history mod_ubuntu</pre><p>Output will be something like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M-FsCh2aDxir4c1J0IRpeA.png" /><figcaption>Docker history output</figcaption></figure><p>We can see all the layers for the original ubuntu image, and then ours on top.</p><p>If we keep adding, deleting, and changing files to images with a commit, our image will grow in size. An important bit is that size of the image is a sum of all its layers.</p><p>Let&#39;s take a look at another example. We’ll take our mod_ubuntu image, add git, and then call it git_ubuntu. To do that, we have to run a container and get into its terminal.</p><pre>docker run -it --name git_ubuntu mod_ubuntu /bin/bash</pre><pre>#output<br>root@898d6e1aef74:/#</pre><p>We’re inside our container, so let’s update tools and instal git.</p><pre>apt-get update &amp;&amp; apt-get -y install git</pre><p>We’ll see plenty of text. When it finishes, just type exit. Now we want to commit our container as a new image, this time with a commit message so we know what was added. Messages are added with -m or --message.</p><pre>docker commit -m &quot;added git&quot; git_ubuntu git_ubuntu:latest</pre><p>You should see the new image id as confirmation. Let’s see all our images.</p><pre>docker image ls</pre><p>Output should be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYkof1YCBIt5OsHhurzFaQ.png" /><figcaption>List of Docker images</figcaption></figure><p>Our new image is bigger. We can check its layers as well with docker history git_ubuntu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8XOPGy63ja_ZC4ikzfW06w.png" /><figcaption>Docker history for new image</figcaption></figure><p>We have two layers, our old one we extended from mod_ubuntu and a new one with the installed git.</p><p>Now we create another image. This time, we’ll take git_ubuntu, uninstall git, delete the mychange file, and then create a new image. The new image will be called plain_ubuntu. In theory, we deleted everything, so we’re supposed to end up with the same size as ubuntu:latest. Let’s find out what’s going to happen.</p><p>Again, run plain_ubuntu container’s terminal and all the actions there.</p><pre>docker run -it --name plain_ubuntu git_ubuntu /bin/bash</pre><pre>#output<br>root@cace613e4176:/#</pre><pre>#in container&#39;s terminal<br>apt-get uninstall -y git &amp;&amp; rm mychange</pre><pre>#then<br>exit</pre><pre>#finally commit changes<br>docker commit -m &quot;removed git&quot; plain_ubuntu plain_ubuntu</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*36W9yy4EH17Jhekg3Y0Jyw.png" /><figcaption>List of images</figcaption></figure><p>Surprisingly, the new image is bigger than the previous one. The difference isn’t much, but still, it’s supposed to be smaller. Let’s see its layers now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Rc5ylQNpg5pbCRyLBcm2g.png" /><figcaption>All commits for plain_ubuntu image</figcaption></figure><p>The reason behind this result is that every time we commit something, we add a new layer. As I mentioned earlier, the total size of an image is a sum of all its layers. The graphic below shows why this is happening.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yf-5mtP8NZD_JKsmiCVvjA.png" /><figcaption>Nickoloff, J. (2016) <a href="https://www.manning.com/books/docker-in-action-second-edition">Docker in Action</a></figcaption></figure><p>From the user perspective, we can see only the files that are left after all operations, but under the hood, everything is still there. Everything we add and then remove is still in our image. It’s helpful in general, as we have access to all commits, so we know what’s happened and when it happened. However, if we want to ship small images, we have to take that into consideration and deal with it.</p><h3>Manage the Size</h3><p>There are two methods to make images smaller. One is quite brutal but easy and efficient. Second is more tedious but defiantly more agile and robust.</p><p>The easy one is simply to export the image with Docker and later import it. The more complicated one is more like doing the whole flow.</p><h4>Flatten the image</h4><p>This process will create a <em>flattened</em> image. As the name suggests, all layers will be flattened to only one. This will reduce the size significantly but never to a minimum. It should be used only for simple images where we don’t need to track changes, commits, etc.; it’s just a plain simple container.</p><p>Let’s work on our previous example. We have the plain_ubuntu image that is basically ubuntu:latest, but its size is the same as git_ubuntu. What we can do is to export it locally to a file with <a href="https://docs.docker.com/engine/reference/commandline/export/">docker export</a>.</p><pre>docker export -o plain_ubuntu.tar plain_ubuntu</pre><p>There is output in the console, but we ended up with the archive of our image. The important bit is that it only exports the container and doesn’t consider container volumes.</p><p>The next step is, obviously, to import the image back. We do it with <a href="https://docs.docker.com/engine/reference/commandline/import/">docker import</a>. Let’s tag the new imported image as plain_ubuntu:imported so we can find it easier later.</p><pre>docker import plain_ubuntu.tar plain_ubntu:imported</pre><p>The console will return the new image’s id as confirmation. Now the moment we’re waiting for. How much space have we saved by flattening our image?<br>Let’s check with docker images ls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*he8CckUZQMq9IH3KIA7o0g.png" /><figcaption>List of all images with imported on top</figcaption></figure><p>It’s smaller, that’s something, but it’s not even close to the original ubuntu_latest. Now let’s check its commits with docker_history.</p><pre>docker history plain_ubntu:imported</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PW71epWlo5UrEOhxKytnHA.png" /><figcaption>History of commits for flatten image</figcaption></figure><p>With export and import, we lost all information about commits history but we saved some size. It’s a quick and easy way, but as I mentioned, only applies to simple images where we don’t care about versioning and history.</p><h4>Branching</h4><p>The idea is to branch changes, tag them properly, and reuse them when needed. It adds more manual work, as sometimes we have to go back and start from the beginning, but it’ll cut images in size. Additionally, they’ll only contain required files, without any unnecessary additions.</p><p>Whenever we add, change, or delete something (basically anything that can add more layers and increase the size of the image), we should commit a new image with an appropriate tag. The idea is to tag changes as minor releases or patches. We should focus on patches especially.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*erQ6swW9671cavc3mv3xsA.png" /><figcaption>Nickoloff, J. (2016) <a href="https://www.manning.com/books/docker-in-action-second-edition">Docker in Action</a></figcaption></figure><p>As per the example above, detailed tagging not only helps us to manage the history and size of the image but also helps people who use our image. Dashed lines indicate a previous connection between image and tag, and solid lines show the current connection. We can assign and reassign tags to images. A single image can have several tags, so don’t be afraid of tagging. It can only help.</p><p>In our example of the modified Ubuntu image, starting from the beginning, we can tag it as 1.0.0. Then we add mychange and create a new image with a tag of 1.0.1 as a patch only. Then we decide to install git, so let’s make it now 1.1.0 as a minor release. We worked on something and decided to add another bit to our image, so now we tag it as 1.1.1. Now we decide to uninstall git; that’s the point where manual work comes to play.</p><p>We should take our 1.0.1 image and branch off. Then we add the changes we made in 1.1.1 and tag it as 1.0.2, for example. Of course, it’s tedious sometimes, but in the long run, we’ll end up with nicely packed images and a properly tagged repo.</p><h3>Summary</h3><p>Let’s summarize what we know:</p><ul><li>Whenever we commit something, we add a new layer.</li><li>The image is a stack of layers and the user sees only the top one.</li><li>Image size is a sum of all layers.</li><li>We can flatten the image by export and import, but we lose the commit history.</li><li>We can assign several tags to one image.</li><li>We should tag generously.</li><li>Don’t forget to keep the latest tag for the actual latest release.</li></ul><p>This article was quite long, but knowing how layers work is very important to fully understanding how to properly optimise container size. Hopefully, you got through it in one piece! Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ad62be0da9b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-improve-docker-image-size-with-layers-3ad62be0da9b">How to Improve Docker Image Size With Layers</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Persistent Databases Using Docker’s Volumes and MongoDB]]></title>
            <link>https://medium.com/better-programming/persistent-databases-using-dockers-volumes-and-mongodb-9ac284c25b39?source=rss-ddcc02cd7cc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ac284c25b39</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Mac Rusek]]></dc:creator>
            <pubDate>Thu, 02 Apr 2020 00:37:04 GMT</pubDate>
            <atom:updated>2020-04-02T00:37:04.596Z</atom:updated>
            <content:encoded><![CDATA[<h4>With Docker Compose version 3</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wGFcfAtp-IVSfnG9aG4CPw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@imgix?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">imgix</a> on <a href="https://unsplash.com/s/photos/storage?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This will help you to understand Volumes in Docker and explain how to use them to store data. It’s an up-to-date guide for <a href="https://docs.docker.com/compose/">Docker Compose</a> version 3.</p><p>In my previous post about <a href="https://medium.com/better-programming/dockerizing-react-app-and-express-api-with-mongodb-f3a06bebf570">Dockerizing Express, Mongo, and React</a>, I used a non-persistent <a href="https://www.mongodb.com/">Mongo</a> container, in this post, I’ll explain how to store your data properly and how it’s working.</p><h3>Docker</h3><p>Let’s start by explaining how Docker stores data. Doesn’t matter if you’re working with a single container and Docker CLI or many containers with docker-compose, the idea is the same.</p><p>When we run Docker, it takes an image, which is read-only, and adds an additional layer on top, which is read-write, that’s out of temporary storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*XXEFWUJ4jK-mLfhfwnGWiw.png" /><figcaption>Layers of base images under writable layers</figcaption></figure><p>When a container modifies files or adds data, it uses one writable layer to do that. The problem is that the layer is deleted when the container is deleted. When we relaunch Docker, all our saved data is gone.</p><p>This technique is called <a href="https://docs.docker.com/glossary/#copy-on-write">copy-on-write</a> and normally it speeds up start time and overall performance and minimizes the footprint of the image.</p><p>To be able to persist data, Docker came up with the idea of Volumes.</p><h3>Volumes</h3><p>Volumes are basically data storages that are outside of containers and exist on the host filesystem. There are two types of Volumes, Docker-managed volumes and bind-mount volumes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypKs6Czr8L8uV9CRjnvM4w.png" /><figcaption>Nickoloff, J. (2016) Docker in Action</figcaption></figure><p>As per the image above, you can see that containers are separate entities from volumes, which are stored on the host’s hard drive. The path where they’re located depends on the type of volume.</p><h4>Bind-mount volumes</h4><p>These volumes, as the names suggest, points to a user-specified place on the host’s filesystem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bUPk-iAdcofNOSax8uJ1Sg.png" /><figcaption>Nickoloff, J. (2016) Docker in Action</figcaption></figure><p>To use them with Mongo, we have to specify a path to the chosen location on the host’s drive, it has to be an absolute path. In our case, that’s going to be ~/mongo/data.</p><p>Next, we bind that location to Mongo’s data location in a container, which is /data/db. Defining the volume with the Docker CLI is done with the -v or --volume flags.</p><pre>docker run -d --name db \<br>  -v ~/mongo/data:/data/db \ <br>  -p 27017:27017 \<br>  mongo:latest</pre><p>You can do the same for the docker-compose file, the syntax is very similar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea960e5ff9537417acb45e0fdb76318d/href">https://medium.com/media/ea960e5ff9537417acb45e0fdb76318d/href</a></iframe><p><strong>Pros</strong></p><ul><li>Great if you need to point several containers to one storage.</li><li>If you delete the container with the -v flag it, the volume is still there.</li><li>You know exactly where data is in the host’s filesystem.</li></ul><p><strong>Cons</strong></p><ul><li>Difficult to remove, you have to do it manually.</li><li>Ties containers to that one particular host.</li><li>With many confiners using the same volume, it is quite easy to overwrite data.</li><li>Complicated to manage in large systems with many containers and volumes.</li></ul><h4>Docker-managed volumes</h4><p>Managed volumes are created automatically by the Docker daemon. The user can’t choose the location as they are created in the portion of the host’s filesystem owned by Docker.</p><p>Docker creates a directory with volumes’ own IDs. All managed volumes are stored in the same Docker directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RhW4I9Wrv-3DmQg34jQ4vw.png" /><figcaption>Nickoloff, J. (2016) Docker in Action</figcaption></figure><p>Usage is fairly easy, for Mongo it’s only a matter of providing Mongo’s data location in a container which is /data/db.</p><pre>docker run -d --name db \<br>  -v /data/db \ <br>  -p 27017:27017 \<br>  mongo:latest</pre><p>The same for the docker-compose file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aea70e63de2e6844109f13d904d9ee24/href">https://medium.com/media/aea70e63de2e6844109f13d904d9ee24/href</a></iframe><p><strong>Pros</strong></p><ul><li>Easy to remove when removing the container, docker rm &lt;name&gt; -v.</li><li>Binds to a single container.</li><li>Independent from the host.</li><li>Easier to manage in large systems with many containers and volumes.</li></ul><p><strong>Cons</strong></p><ul><li>Difficult to remove when you forget to use -v when deleting a container.</li><li>Trickier to share one volume with many containers.</li></ul><h3>Sharing a Docker-Managed Volume</h3><p>To share a Docker-managed volume between containers, we’re going to use the <em>volume container pattern</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Tomha3ghMWZZ8CrLUGosQ.png" /><figcaption>Nickoloff, J. (2016) Docker in Action</figcaption></figure><p>With this pattern, we create two containers and link them to one volume. First, we create a <em>volume container</em> as a Docker-managed volume, we call the image with the vc_ prefix. In our case, that’s going to be vc_db.</p><p>The next step is to create a named volume with the top-level <a href="https://docs.docker.com/compose/compose-file/#volumes">volumes</a> key.</p><p>This feature is available in Docker Compose version 3. The old version used the --volumes-from flag.</p><p>Our docker-compose file should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f23af3ed091460f8806b2c12a3907b5/href">https://medium.com/media/2f23af3ed091460f8806b2c12a3907b5/href</a></iframe><p>Some might notice that there are no ports for the vc_db container. They are not needed as we won’t be connecting to it. It’s only there to hold a connection to the shared volume.</p><p>Now we have to link our two images to the named volume we created. The syntax is quite similar to binding modules but instead of an absolute path to a volume, we just provide the volume’s name. In our case, it’s shared_database.</p><p>We still use MongoDB’s data location, /data/db, as in <em>container</em>.</p><pre>volumes: shared_database:/data/db</pre><p>Let’s update our docker-compose file and add binding to the named volume.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e2db99ba157f9b9f8978194e6b212bf/href">https://medium.com/media/1e2db99ba157f9b9f8978194e6b212bf/href</a></iframe><p>The idea behind this pattern is:</p><ol><li>To be able to share a volume easily with other containers, just by binding the named volume.</li><li>Whenever you delete the main database image for some reason, even with the -v flag, the volume is still there. Volumes can’t be deleted as long as they are connected to at least one container.</li><li>Since we using Docker-managed volumes, we get all the perks mentioned above with this.</li></ol><p>Thanks for your time reading it. I hoped this helped you understand Docker’s volumes better and encourages you to use that fundamental feature.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ac284c25b39" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/persistent-databases-using-dockers-volumes-and-mongodb-9ac284c25b39">Persistent Databases Using Docker’s Volumes and MongoDB</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quickly Improve Your Docker and Node.Js Containers]]></title>
            <link>https://medium.com/better-programming/quickly-improve-your-docker-and-node-js-containers-b841858a0b38?source=rss-ddcc02cd7cc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b841858a0b38</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mac Rusek]]></dc:creator>
            <pubDate>Fri, 06 Mar 2020 18:21:30 GMT</pubDate>
            <atom:updated>2020-03-06T18:21:30.266Z</atom:updated>
            <content:encoded><![CDATA[<h4>Better containers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*epfvG4ZmlzhhNCBPvFgC9A.png" /></figure><p>We all know how to makes a basic Dockerfile for Node.js app, like Express. A simple, single-stage build will look like this:</p><pre>FROM node:12-alpine</pre><pre>WORKDIR /app<br>COPY package.json /app/package.json<br>RUN npm install<br>COPY . /app</pre><pre>EXPOSE 8080<br>CMD [&quot;npm&quot;, &quot;start&quot;]</pre><p>It really couldn’t be simpler. Unfortunately this solution has a couple of flaws. We’re going to fix them.</p><h3>User</h3><p>By default, Docker runs all Node.js as theroot user, which can lead to security vulnerabilities. In most cases we want the non-root user running our containers. The solution is to use a different user in Dockerfile. All Node.js images for Docker come with a non-root user called node.</p><p>The user can be added in Dockerfile with the <a href="https://docs.docker.com/engine/reference/builder/#user">USER</a> statement:</p><pre>FROM node:12-alpine</pre><pre>WORKDIR /app<br>COPY package.json /app/package.json<br>RUN npm install<br>COPY . /app</pre><pre>EXPOSE 8080</pre><pre>## define user just at the end<br>USER node    <br>             <br>CMD [&quot;npm&quot;, &quot;start&quot;]</pre><p>Or, if you’re using <a href="https://docs.docker.com/engine/reference/commandline/run/">Docker CLI </a>to run an already built container, you can use --user, -u flags.</p><pre>docker run --user node my_image</pre><h3>CMD</h3><p>Sometimes we use npm start or yarn start as CMD command to start Docker container. I guess it’s just out of habit when working with npm/yarn.</p><p>There are two problems with this solution. First, we add additional processes to our container, which are unnecessary. Second, we block some exit signals like <a href="https://docs.docker.com/engine/reference/commandline/stop/">SIGTERM</a> between Docker and Node.js as they’re being captured by npm/yarn.</p><p>The solution is pretty straightforward. We use node as the starting command:</p><pre>FROM node:12-alpine</pre><pre>WORKDIR /app<br>COPY package.json /app/package.json<br>RUN npm install<br>COPY . /app</pre><pre>EXPOSE 8080<br>USER node</pre><pre>## use node instead of npm/yarn<br>CMD [&quot;node&quot;, &quot;index.js&quot;]</pre><p>If you have some env variables in npm start command you can still pass them to your container with <a href="https://docs.docker.com/engine/reference/builder/#env">ENV</a>.</p><h3>Bcrypt</h3><p>Bcrypt is a popular library for hashing password but it won’t work on node:alpine containers. Some people just back up to full node or node:slim images but they’re still heavier than alpine.</p><p>It’s a well-known problem. The solution is to install additional packages and Python before installing npm packages.</p><pre>FROM node:12-alpine</pre><pre>WORKDIR /app<br>COPY package.json /app/package.json</pre><pre>## install required packages before npm<br>RUN apk --no-cache add --virtual builds-deps build-base python</pre><pre>RUN npm install<br>COPY . /app</pre><pre>EXPOSE 8080<br>USER node   <br>CMD [&quot;node&quot;, &quot;index.js&quot;] </pre><p>These were three quick tips to improve work with Docker. But don’t stop here, read some more at <a href="https://github.com/nodejs/docker-node/blob/master/docs/BestPractices.md">Docker and Node.js Best Practices</a> and <a href="https://github.com/kelektiv/node.bcrypt.js/wiki/Installation-Instructions">Bcrypt Wiki</a>.</p><p>Thanks for taking the time to read this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b841858a0b38" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/quickly-improve-your-docker-and-node-js-containers-b841858a0b38">Quickly Improve Your Docker and Node.Js Containers</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerize a React App and an Express API With MongoDB]]></title>
            <link>https://medium.com/better-programming/dockerizing-react-app-and-express-api-with-mongodb-f3a06bebf570?source=rss-ddcc02cd7cc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3a06bebf570</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mac Rusek]]></dc:creator>
            <pubDate>Wed, 26 Feb 2020 22:04:42 GMT</pubDate>
            <atom:updated>2020-03-04T19:08:16.555Z</atom:updated>
            <content:encoded><![CDATA[<h4>A simple guide on how to move your React app, Express API, and MongoDB to Docker using containers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eAVVl4etCTr78TezjDX9og.jpeg" /><figcaption>Image by <a href="https://pxhere.com/en/photographer/767067">Mohamed Hassan</a> on <a href="https://pxhere.com/en/photo/1449859">PxHere</a></figcaption></figure><p>For sake of simplicity, I assume you have a working front end and back end — as well as connected database.</p><p>The best idea is to have both the API and client repos in one folder. You can have one remote repo with both of them or use two separate remote repos and then combine them with parent remote using Git submodules. That’s how I did that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*3HzqpqAUxcrdow4MX7bcLg.png" /><figcaption>Parent repo folder tree</figcaption></figure><h3>React App</h3><p>I used Create React App (CRA) with TypeScript for my project. It was a simple blog with a couple views.</p><p>The first thing to do is to create a Dockerfile in the client root folder. To do that, just type:</p><pre>$ touch Dockerfile</pre><p>Open the file, and let’s fill it out. I’m using TypeScript with my CRA, so first I have to build my application. Then, I take what I get and host it all as static files. To achieve that, we’ll go with a <a href="https://docs.docker.com/develop/develop-images/multistage-build/">two-stage Docker build</a>.</p><p>The first stage is using Node to build the app. I use the<strong> </strong>Alpine version — as it’s the lightest, so our container will be tiny.</p><pre>FROM node:12-alpine as builder</pre><pre>WORKDIR /app<br>COPY package.json /app/package.json<br>RUN npm install --only=prod<br>COPY . /app<br>RUN npm run build</pre><p>That’s how the beginning of the Dockerfile looks like. We’re using node:12-alpine as builder, then setting up a working directory to /app. That’s going to create a new folder in our container. We copy our<strong> </strong>package.json to a new folder in the container and install all of the packages. Next, we copy everything from the /services/client folder and paste it into our container. The last bit of that step is to build everything.</p><p>Now we have to host our freshly created build. To do that, we’re going to use NGINX — again in the Alpine version to cut on size.</p><pre>FROM nginx:1.16.0-alpine<br>COPY --from=builder /app/build /usr/share/nginx/html<br>EXPOSE 80<br>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><p>We copy the build from the previous step and paste it into the nginx folder. Then expose port 80 — that’s going to be the port on which our container will be listening for connections. The last line is to start NGINX.</p><p>That’s all for the client part. The whole Dockerfile should look like this:</p><pre>FROM node:12-alpine as build</pre><pre>WORKDIR /app<br>COPY package.json /app/package.json<br>RUN npm install --only=prod<br>COPY . /app<br>RUN npm run build</pre><pre>FROM nginx:1.16.0-alpine<br>COPY --from=build /app/build /usr/share/nginx/html<br>EXPOSE 80<br>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><h3>Express API</h3><p>The API is quite simple as well — with RESTful routing to create posts, handle the authorization, etc. Lets start with creating a Dockerfiler in the API root folder in the same way as we did in the previous part.</p><p>I used ES6 features, so I have to compile everything to Vanilla JS to run it, and I went with Babel. As you can guess, that’s going to be a two-stage build again.</p><pre>FROM node:12-alpine as builder</pre><pre>WORKDIR /app<br>COPY package.json /app/package.json<br>RUN apk --no-cache add --virtual builds-deps build-base python<br>RUN npm install<br>COPY . /app<br>RUN npm run build</pre><p>It’s very similar to the client’s Dockerfile, so I won’t be explaining it again. There’s one difference, though.</p><pre>RUN apk --no-cache add --virtual builds-deps build-base python</pre><p>I used <a href="https://www.npmjs.com/package/bcrypt">bcrypt</a> to hash my passwords before saving them to the database. It’s a very popular package, but it has some problems when using Alpine images. You might find errors similar to:</p><pre>node-pre-gyp WARN Pre-built binaries not found for bcrypt@3.0.8 and node@12.16.1 (node-v72 ABI, musl) (falling back to source compile with node-gyp)</pre><pre>npm ERR! Failed at the bcrypt@3.0.8 install script.</pre><p>It’s a well-known problem, and the <a href="https://github.com/kelektiv/node.bcrypt.js/wiki/Installation-Instructions#docker">solution</a> is to install additional packages and Python before installing npm packages.</p><p>The next stage, similarly as for the client, is to take the build API and run it with Node.</p><pre>FROM node:12-alpine<br>WORKDIR /app<br>COPY --from=builder /app/dist /app<br>COPY package.json /app/package.json<br>RUN apk --no-cache add --virtual builds-deps build-base python<br>RUN npm install --only=prod</pre><pre>EXPOSE 8080 <br>USER node<br>CMD [&quot;node&quot;, &quot;index.js&quot;]</pre><p>One exception is to install only production packages. We don’t need Babel anymore — as everything was complied in step one. Then we expose port 8080 to listen to requests and start Node.</p><p>The whole Dockerfile should looks like this:</p><pre>FROM node:12-alpine as builder</pre><pre>WORKDIR /app<br>COPY package.json /app/package.json<br>RUN apk --no-cache add --virtual builds-deps build-base python<br>RUN npm install<br>COPY . /app<br>RUN npm run build</pre><pre>FROM node:12-alpine<br>WORKDIR /app<br>COPY --from=builder /app/dist /app<br>COPY package.json /app/package.json<br>RUN apk --no-cache add --virtual builds-deps build-base python<br>RUN npm install --only=prod</pre><pre>EXPOSE 8080 <br>USER node<br>CMD [&quot;node&quot;, &quot;index.js&quot;]</pre><h3>Docker Compose</h3><p>The last step is to combine the API and client containers with the MongoDB container. To do that, we use a docker-compose file that’s placed in our parent repo root directory — as it has to get access to both the client and the API’s Dockerfiles.</p><p>Let’s create the docker-compose file:</p><pre>$ touch docker-compose.yml</pre><p>We should end up with a file structure like the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*3HzqpqAUxcrdow4MX7bcLg.png" /><figcaption>Parent repo folder tree</figcaption></figure><p>Fill in the docker-compose file with the following code, and I’ll explain it afterward.</p><pre>version: &quot;3&quot;</pre><pre>services:<br>  api:<br>    build: ./services/api<br>    ports:<br>      - &quot;8080:8080&quot;<br>    depends_on:<br>      - db<br>    container_name: blog-api</pre><pre>  client:<br>    build: ./services/client<br>    ports:<br>      - &quot;80:80&quot;<br>    container_name: blog-client</pre><pre>  db:<br>    image: mongo<br>    ports:<br>      - &quot;27017:27017&quot;<br>    container_name: blog-db</pre><p>It’s really as simple as that. We have three services: the client, the API, and MongoDB. There’s no Dockerfile for MongoDB — Docker will download images from its hub and create a container out of them. That means our database it perishable, but for the beginning it’s enough.</p><p>In the API and client we have a build key, which points to the Dockerfile locations for both services respectively (the root folder). The port container’s assigned in the Dockerfile to go to our docker-compose network port so the containers can talk to each other. The API service also has depends_on key. This tells Docker to wait with starting it until the database container is fully running. Because of that, we’re going to avoid connection errors from the API container.</p><p>One more bit for MongoDB: In our codebase for the back end, we have to update MongoDB connection string. Usually, we point to the localhost:</p><pre>mongodb://localhost:27017/blog</pre><p>But with docker-compose, it has to point to a container name:</p><pre>mongodb://blog-db:27017/blog</pre><p>The final touch is to run everything with the following command in the parent repo root directory (where the docker-compose.yml is):</p><pre>$ docker-compose up</pre><p>That’s all. More reading than coding, I guess. Thanks for staying till the end!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3a06bebf570" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/dockerizing-react-app-and-express-api-with-mongodb-f3a06bebf570">Dockerize a React App and an Express API With MongoDB</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cookies with React, Express and Docker]]></title>
            <link>https://itnext.io/cookies-with-react-express-and-docker-15296fac20fb?source=rss-ddcc02cd7cc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/15296fac20fb</guid>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Mac Rusek]]></dc:creator>
            <pubDate>Tue, 02 Jul 2019 13:14:50 GMT</pubDate>
            <atom:updated>2019-07-05T10:49:39.798Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I had to move JWT to cookies to use it between Docker microservices seamlessly. We ran each container on separate url prefixes, it was tricky to figure out as cookies have to be there when the url is changed. I couldn’t find any straightforward solution so I decided to write this article, it might be useful for someone or even for future me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k87q1EVhYNPZ6Li_dcwV4g.jpeg" /></figure><p>I just assume you have working front-end and back-end containers and everything runs fine. I won’t be explaining what cookies are as there’re plenty of better articles on that topic.</p><h4>Basic setup</h4><p>Let’s use simple Express server as example how to send cookies.</p><pre>// index.js</pre><pre>const express = require(&quot;express&quot;)<br>const session = require(&quot;express-session&quot;);</pre><pre>const app = express()</pre><pre>app.use(<br>  session({<br>    secret: process.env.LOGIN_SERVER_SECRET,<br>    saveUninitialized: true,<br>    resave: true,<br>    cookie: {<br>      httpOnly: false,<br>      secure: false,<br>    },<br>  }),<br>);</pre><pre>app.get(&quot;/cookie&quot;, (req, res) =&gt; {<br>  const options = {<br>    secure: false,<br>    httpOnly: false,<br>    domain: &quot;.your.domain.com&quot;<br>  }</pre><pre>  return res<br>    .cookie(&quot;cookieName&quot;, &quot;cookieValue&quot;, options)<br>    .status(200)<br>    .send(&quot;cookie sent&quot;)<br>})<br><br>app.listen(8080)</pre><p>In this case whenever we send request to <em>localhost:8080/cookie</em> server responds with Set-Cookie header. That works fine when you type it directly in your browser or in app like Postman. The problems start when you run your client on <em>client.your.domain.com</em> and server on <em>server.your.domain.com. </em>We start getting CORS issues.</p><p>Let’s see basic setup for out client app. I used create-react-app and just modified it by adding <a href="https://www.npmjs.com/package/superagent">superagent</a> (great library for requests) and sending request whenever I click on the link.</p><pre>// App.js</pre><pre>import React from &quot;react&quot;;<br>import superagent from &quot;superagent&quot;;<br>import logo from &quot;./logo.svg&quot;;<br>import &quot;./App.css&quot;;</pre><pre>function App() {</pre><pre>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;header className=&quot;App-header&quot;&gt;<br>        &lt;img src={logo} className=&quot;App-logo&quot; alt=&quot;logo&quot; /&gt;<br>        &lt;p&gt;<br>          Edit &lt;code&gt;src/App.js&lt;/code&gt; and save to reload.<br>        &lt;/p&gt;<br>        &lt;a<br>          className=&quot;App-link&quot;<br>          onClick={() =&gt;<br>            superagent<br>              .get(&quot;http://localhost:8080/cookie&quot;)<br>              .then(response =&gt; {<br>                console.log(response);<br>              })<br>          }<br>        &gt;<br>          Get Cookie<br>        &lt;/a&gt;<br>      &lt;/header&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default App;</pre><h4>CORS</h4><p>Since we’re sending request from different originators we get CORS issues. Simple solution to do that is to install <a href="https://www.npmjs.com/package/cors">cors</a> package and add it as by simple example in their docs.</p><p>Again, simple cors with wildcard (*/*) won’t work. We have to set up some custom config for cors and catch pre-flight OPTION check.</p><pre>// index.js</pre><pre>const express = require(&quot;express&quot;)<br>const session = require(&quot;express-session&quot;);<br>const cors <strong>=</strong> require(&quot;cors&quot;)</pre><pre>const app = express()</pre><pre>app.use(<br>  session({<br>    secret: process.env.LOGIN_SERVER_SECRET,<br>    saveUninitialized: true,<br>    resave: true,<br>    cookie: {<br>      httpOnly: false,<br>      secure: false,<br>    },<br>  }),<br>);</pre><pre>const corsOptions <strong>=</strong> {<br>  origin: /\.your.domain\.com$/,    <em>// reqexp will match all prefixes<br>  </em>methods: &quot;GET,HEAD,POST,PATCH,DELETE,OPTIONS&quot;,<br>  credentials: true,                // required to pass<br>  allowedHeaders: &quot;Content-Type, Authorization, X-Requested-With&quot;,<br>}</pre><pre><em>// intercept pre-flight check for all routes<br></em>app.options(&#39;*&#39;, cors(corsOptions))</pre><pre><em>// add cors middleware to route </em><br>app.get(&quot;/cookie&quot;, cors(corsOptions), (req, res) =&gt; {<br>  const options = {<br>    secure: false,<br>    httpOnly: false,<br>    domain: &quot;.your.domain.com&quot;<br>  }</pre><pre>return res<br>    .cookie(&quot;cookieName&quot;, &quot;cookieValue&quot;, options)<br>    .status(200)<br>    .send(&quot;cookie sent&quot;)<br>})<br><br>app.listen(8080)</pre><p>There is one more change on the front-end. Since our server now accepts request with credentials we have to send one to pass the cookie. It’s literally one line extra</p><pre>// App.js</pre><pre>import React from &quot;react&quot;;<br>import superagent from &quot;superagent&quot;;<br>import logo from &quot;./logo.svg&quot;;<br>import &quot;./App.css&quot;;</pre><pre>function App() {</pre><pre>return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;header className=&quot;App-header&quot;&gt;<br>        &lt;img src={logo} className=&quot;App-logo&quot; alt=&quot;logo&quot; /&gt;<br>        &lt;p&gt;<br>          Edit &lt;code&gt;src/App.js&lt;/code&gt; and save to reload.<br>        &lt;/p&gt;<br>        &lt;a<br>          className=&quot;App-link&quot;<br>          onClick={() =&gt;<br>            superagent<br>              .get(&quot;http://localhost:8080/cookie&quot;)<br>              .withCredentials()           <em>// it&#39;s simple as that</em><br>              .then(response =&gt; {<br>                console.log(response);<br>              })<br>          }<br>        &gt;<br>          Get Cookie<br>        &lt;/a&gt;<br>      &lt;/header&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default App;</pre><h4>Secured cookies</h4><p>As you might have noticed, I used unsecured cookies in the above examples. That’s for dev/local purposes only. If you want to use it in production you have to take care about security. Secure cookies will work only on https so you have to take care of that as well. Good idea is to set cookies security dependent on NODE_ENV, so we don’t have to remember about it when working on dev and then deploy to prod.</p><pre>// index.js</pre><pre>===</pre><pre>app.use(<br>  session({<br>    secret: process.env.LOGIN_SERVER_SECRET,<br>    saveUninitialized: true,<br>    resave: true,<br>    cookie: {<br>      httpOnly: true,            <em>// change both to true</em><br>      secure: true,<br>    },<br>  }),<br>);</pre><pre>===</pre><pre><em>// dynamic change</em><br>const isCookieSecure = <br>  process.env.NODE_ENV === &quot;production&quot; ? true : false;</pre><pre><em>// add cors middleware to route </em><br>app.get(&quot;/cookie&quot;, cors(corsOptions), (req, res) =&gt; {<br>  const options = {<br>    secure: isCookieSecure,<br>    httpOnly: isCookieSecure,<br>    domain: &quot;.your.domain.com&quot;<br>  }</pre><pre>return res<br>    .cookie(&quot;cookieName&quot;, &quot;cookieValue&quot;, options)<br>    .status(200)<br>    .send(&quot;cookie sent&quot;)<br>})</pre><p>That’s basically it. You can add as many apps and servers to your docker as you want and enjoy cookies everywhere. They’ll be passed automatically in the request and responses headers. Thanks you all for getting that far, hopefully that’s gonna be useful for someone :)</p><p>Read more about <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">CORS</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS">OPTIONS</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies">cookies</a> at MDN. Any questions or feedback just post a comment. Thanks 🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15296fac20fb" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/cookies-with-react-express-and-docker-15296fac20fb">Cookies with React, Express and Docker</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>