<?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 Navneet Singh on Medium]]></title>
        <description><![CDATA[Stories by Navneet Singh on Medium]]></description>
        <link>https://medium.com/@nav.marwaha?source=rss-a4f777fe3108------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*zUaCINIwETWVCNaFiL5eUg.jpeg</url>
            <title>Stories by Navneet Singh on Medium</title>
            <link>https://medium.com/@nav.marwaha?source=rss-a4f777fe3108------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:28:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nav.marwaha/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[Dockerfile Instructions & Best Practices]]></title>
            <link>https://medium.com/@nav.marwaha/dockerfile-instructions-best-practices-29381d349aee?source=rss-a4f777fe3108------2</link>
            <guid isPermaLink="false">https://medium.com/p/29381d349aee</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <dc:creator><![CDATA[Navneet Singh]]></dc:creator>
            <pubDate>Fri, 03 Apr 2020 07:24:46 GMT</pubDate>
            <atom:updated>2022-05-03T18:06:27.435Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XvJ0GDWOAEHNApZvw-dOVQ.png" /></figure><h3>After reading this post you will be knowing:</h3><ul><li>What a Dockerfile is?</li><li>How a Dockerfile looks like?</li><li>How to build &amp; tag a Docker Image?</li><li>Some of the most commonly used Dockerfile instructions.</li><li>Best practices to be followed for writing a Dockerfile.</li></ul><h3>What is Dockerfile?</h3><p>A Dockerfile is a text file, that consists of a set of instructions which are built into a Docker image using docker image build command.</p><p>Let’s take an example:</p><pre>#Custom Nginx Dockerfile<br>FROM nginx</pre><pre>RUN apt-get update &amp;&amp; apt-get install -y curl</pre><pre>EXPOSE 80</pre><p>This is the content of a Dockerfile, wherein we are using the base Nginx image, installing curl command &amp; using the EXPOSE instruction to document that the container from this image will listen on port 80.</p><p>Now let’s build an image from this Dockerfile using docker image build command &amp; tag it as mynginx:v1.0 using the-t flag.</p><pre>root@dockerlab:~# docker image build -t mynginx:v1.0 .<br>Sending build context to Docker daemon  21.21MB<br>Step 1/3 : FROM nginx<br>---&gt; 2073e0bcb60e<br>Step 2/3 : RUN apt-get update &amp;&amp; apt-get install -y curl<br>---&gt; Using cache<br>---&gt; aca9f0412b69<br>Step 3/3 : EXPOSE 80<br>---&gt; Running in df0742ce2a20<br>Removing intermediate container df0742ce2a20<br>---&gt; 2d9c603554f9<br>Successfully built 2d9c603554f9<br>Successfully tagged mynginx:v1.0</pre><p>Now you can check using docker image ls that this image is available locally.</p><pre>root@dockerlab:~# docker image ls</pre><pre>REPOSITORY    TAG          IMAGE ID        CREATED            SIZE<br>mynginx       v1.0         2d9c603554f9    3 minutes ago      152MB<br>nginx         latest       2073e0bcb60e    3 weeks ago        127MB</pre><p>A ‘<strong><em>Docker Image</em></strong>’ is a read-only template with instructions for creating a Docker container. Each instruction in a Dockerfile creates a new layer in the image.</p><p>Now that we know what a Dockerfile is and how we can build a Docker image from a Dockerfile. Let’s try to know about some of the commonly used Dockerfile instructions.</p><h3>Dockerfile Instructions</h3><p>Following are some of the commonly used instructions for writing Dockerfiles. Let’s understand what they are used for.</p><blockquote><strong>LABEL</strong></blockquote><p>The LABEL instruction is used to add meta-data to a Docker image. A LABEL is a combination of a key-value pair. Let us look at an example.</p><pre>FROM nginx</pre><pre>RUN apt-get update &amp;&amp; apt-get install -y curl</pre><pre>LABEL app-name=nginx app-version=1.17.8</pre><pre>EXPOSE 80</pre><p>You can check the details of a Docker image using docker image inspect.</p><pre>docker image inspect &lt;image-name&gt; --format=&#39;{{json .Config.Labels}}&#39;</pre><p>The --format=&#39;{{json .Config.Labels}}&#39; flag will print out only the labels added to a Docker Image.</p><blockquote><strong>FROM</strong></blockquote><p>The FROM instruction initializes a new build stage and sets the “<em>Base Image” </em>for all the subsequent instructions. Any Dockerfile should ideally start with FROM instruction, <a href="https://docs.docker.com/engine/reference/builder/#understand-how-arg-and-from-interact#understand-how-arg-and-from-interact">ARG</a> is the only instruction that can precede FROM.</p><blockquote><strong>RUN</strong></blockquote><p>RUN instruction is used to execute commands in a new layer on top of the current image and commit the results. The resulting image is used for the subsequent instruction in Dockerfile.</p><blockquote><strong>COPY</strong></blockquote><p>It copies new files or directories from &lt;src&gt; and adds them to the filesystem of the container at the &lt;dest&gt; path. For a few examples of COPY instruction please have a look at this Dockerfile.</p><pre>FROM nginx</pre><pre>#copying deployments directory recursiverly into /opt directory<br>COPY deployments /opt/deployments</pre><pre># this copy instruction will copy the content of conf directory directly into /opt/deployments/<br>COPY conf /opt/deployments/</pre><pre>#copying file example.conf into /etc/nginx/conf.d/<br>COPY example.conf /etc/nginx/conf.d/</pre><pre>EXPOSE 80</pre><blockquote><strong>ADD</strong></blockquote><p>ADD is similar to COPY, it also lets you copy from a location on the host into a Docker Image. But ADD supports two additional sources. First, you can use a URL instead of a local file/directory. Secondly, it can automatically unpack a tar file from the source directly into the destination.</p><p>If you are copying local files to your Docker image, always use COPY because it’s more transparent than ADD.</p><blockquote><strong>ENV</strong></blockquote><p>It is used to set an environment variable &lt;key&gt; to the value &lt;value&gt;. This value will be in the environment for all the subsequent instructions in the build stage &amp; can be <a href="https://docs.docker.com/engine/reference/builder/#environment-replacement">replaced inline</a> in many.</p><pre>FROM nginx</pre><pre>ENV myVersion 1.17.8</pre><pre>ENV myName=nginx</pre><pre>EXPOSE 80</pre><p>In this Dockerfile, you can see that ENV have been set in two ways. Both of these ways are valid. You can set multiple environment variables at one time using the second method i.e. ENV &lt;key&gt;=&lt;value&gt; ..</p><p>Adding multiple ENV instructions in a Dockerfile creates a single layer in the Docker image.</p><blockquote><strong>EXPOSE</strong></blockquote><p>The EXPOSE instruction informs Docker that the container listens on the specified network ports at the runtime. It acts as documentation about which ports are intended to be published &amp; does not actually publishes the port.</p><blockquote><strong>HEALTHCHECK</strong></blockquote><p>Using HEALTHCHECK instruction we can tell Docker daemon how to test a container whether the application is healthy or not. It can detect cases such as a web service is unable to connect to its dependencies and unable to return the expected response, even though the process is still running.</p><p>The syntax for HEALTHCHECK instruction is</p><pre>HEALTHCHECK [OPTIONS] CMD command</pre><p>The options that can be used with HEALTHCHECK are:</p><p>--interval=DURATION (default 30s)</p><p>--timeout=DURATION (default 30s)</p><p>--start-period=DURATION (default 0s)</p><p>--retries=N (default 3)</p><p>Let’s look at an example.</p><pre>FROM nginx</pre><pre>RUN apt-get update &amp;&amp; apt-get install -y curl</pre><pre>HEALTHCHECK --interval=10s --timeout=3s \</pre><pre>CMD curl -f <a href="http://localhost/healthcheck">http://localhost/healthcheck</a> || exit 1</pre><p>You can check the health status of the container using the following command.</p><pre>docker container inspect healthcheck --format=&#39;{{json .State.Health.Status}}&#39;</pre><p>The possible output values for this command can be:</p><ul><li>starting</li><li>healthy</li><li>unhealthy</li></ul><blockquote><strong>CMD</strong></blockquote><p>The main purpose of a CMD is to specify the command to be executed when a container starts. There can be only one CMD instruction in a Dockerfile if you list more than one CMD then the last one will take effect.</p><pre>FROM openjdk</pre><pre>CMD [&quot;java&quot;,&quot;--version&quot;]</pre><p>You cannot pass arguments to CMD instruction, but the CMD instruction can be overwritten while starting a container.</p><pre>docker container run -d --name &lt;container-name&gt; &lt;image-name&gt; &lt;cmd-to-override&gt;</pre><blockquote><strong>ENTRYPOINT</strong></blockquote><p>The ENTRYPOINT instruction works quite similar to CMD, it is also used to specify the command to execute when a container is started. But it doesn’t allow you to override the command.</p><p>Instead, you can add arguments to the command, by adding them towards the end of the docker container run command.</p><pre>FROM openjdk</pre><pre>ENTRYPOINT [&quot;java&quot;]</pre><p>Now if you start a container using the following command you will get the version details of <strong>JAVA</strong> as the output.</p><pre>docker container run -it --name entrypoint entrypoint-test:v1.0 --version</pre><p>Now as we have covered the commonly used instructions, let’s see what best practices should be followed while writing a Dockerfile.</p><p>You can read more about Dockerfile &amp; get to know more about instructions <a href="https://docs.docker.com/engine/reference/builder/">here</a>.</p><h3>Dockerfile Example</h3><pre>FROM golang:latest</pre><pre>WORKDIR /opt/myapp</pre><pre>COPY myapp /opt/myapp</pre><pre>RUN apt-get update &amp;&amp; apt-get install -y vim</pre><pre>EXPOSE 8080</pre><pre>ENTRYPOINT [&quot;go&quot;, &quot;run&quot;, &quot;server.go&quot;]</pre><p>It is a typical looking Dockerfile. We selectgolang:latest as the base image, set a working directory, copy the files we need, install vim editor, open the port and finally run our application.</p><blockquote><strong><em>Is this an optimized </em></strong><strong><em>Dockerfile?</em></strong></blockquote><p>Not exactly!! Let&#39;s get to know some of the <strong>best practices</strong> to write an optimized Dockerfile.</p><blockquote><strong>Base Image Size</strong></blockquote><p>We have used golang:latest as the base image in our example. Let’s build a Docker image from this Dockerfile.</p><pre>docker image build -t myapp:v1.0 .</pre><p>Once the image is ready let&#39;s run docker image ls to see some stats about our image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eoSXdQr55WCV9eoD7vxpWA.png" /><figcaption>Whopping 861 MB.</figcaption></figure><p>Let’s try using another version of golang image as our base image.</p><pre>FROM golang:alpine</pre><pre>WORKDIR /opt/myapp</pre><pre>COPY myapp /opt/myapp</pre><pre>RUN apk add --no-cache vim</pre><pre>EXPOSE 8080</pre><pre>ENTRYPOINT [&quot;go&quot;, &quot;run&quot;, &quot;server.go&quot;]</pre><p>Let’s build a new version of our image.</p><pre>docker image build -t myapp:v1.1 .</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZpmkS_W4H6q2quqGQuuRA.png" /><figcaption>Just 398 MB.</figcaption></figure><p>Imagev1.1is 54% smaller as compared to the previous version.</p><blockquote><strong>Leverage Cache</strong></blockquote><p>For each command in the Dockerfile, Docker creates a new image layer. Before creating a new layer Docker checks whether an existing layer in the cache can be reused.</p><p>If you do not want to leverage the cache at all, you can use --no-cache=true flag while running the docker image build command.</p><blockquote><strong>Order Matters</strong></blockquote><p>To leverage the cache we should make sure to place the instructions in the Dockerfile in order of least likely to change to the most likely to change.</p><p>In our, Dockerfile we have placed the COPY instruction before the RUN instruction. Which is not correct, as we will be more frequently changing our application code, then the version of vim.</p><blockquote><strong>Limit the attack surface</strong></blockquote><p>Do not install any unnecessary packages, this not only helps in reducing the size of the image but also reduces the attack surface of a container launched from that image.</p><blockquote><strong>Minimize the number of layers</strong></blockquote><p>Each RUN, COPY, ADD instruction creates a new layer, whereas other instructions create intermediate images. To minimize the number of layers &amp; size of the image you should chain multiple instructions into a single instruction.</p><pre>RUN apt-get update<br>RUN apt-get install -y git</pre><p>Instead of adding to instructions in the Dockerfile, this can be chained into a single instruction.</p><pre>RUN apt-get update &amp;&amp; apt-get install -y git</pre><blockquote><strong>Use COPY over ADD</strong></blockquote><p>Although ADD and COPY are functionally similar, but COPY is preferred. As it supports only basic copying of local files into the image, while ADD has some special features like:</p><ul><li>Auto extraction of a local tar file into the image</li><li>Fetch files from remote URL.</li></ul><p>Because the image size matters usingADD for fetching files remotely is strongly discouraged. Rather you should use curl or wget to download the files. For example, you should avoid doing things like:</p><pre>ADD http://example.com/big.tar.xz /usr/src/things/<br>RUN make -C /usr/src/things all</pre><p>&amp; instead, do it like this</p><pre>RUN mkdir -C /usr/src/things \<br>    &amp;&amp; curl -SL http://example.com/big.tar.xz \<br>    | tar -xJC /usr/src/things \<br>    &amp;&amp; make -C /usr/src/things all</pre><p>There are many more best practices to follow for writing better Dockerfile. You can read about them over <a href="https://docs.docker.com/develop/develop-images/dockerfile_best-practices/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29381d349aee" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>