Codementor Events

Multi Stage Docker Build

Published May 29, 2020
Multi Stage Docker Build

Hello everyone! 👋
I am here with a fairly concise article on what is multi stage build and how to use it effectively to make your docker build more secure especially when working with sensitive configuration files like .npmrc for npm configuration in a NodeJS project.
So without further adieu, we will get right into it!
What is multi stage build?
Multi-stage builds are a feature requiring Docker 17.05 or higher on the daemon and client.

  • Multistage builds are useful to anyone who has struggled to optimize Dockerfiles while keeping them easy to read and maintain.
  • It’s a better way to write your dockerfiles so that the build images are created in multi stage and each stage can use a different base(for eg).
  • This allows you to selectively copy artifacts from one stage to another thereby not including anything that’s not required in the final image.
  • Multi stage build with .npmrc
    I have an example for you guys to show how a multi stage build can be used to securely use .npmrc file in your NodeJS project.
    1_dJ3giQA14vHjstqWxeMAKg.png
    What you see above is explained below —
  1. It’s one Dockerfile with builds in two stages.
  2. You would notice few docker labels that are usually added to label docker images. There is a draft of the convention that can be seen here but more on this later…
  3. In the first stage, an image is created with all the necessary attributes and please note the following line of code in the above file —
RUN echo "Something${ARG1}" > .npmrc && \
npm install --production && \
rm -rf .npmrc

What’s happening here is that the necessary contents are copied to .npmrc on runtime, immediately followed by npm install and removal of .npmrc in the same layer. This ensures that .npmrc is used only when npm install is required and not exposed in any of the intermediate layers. 😎
4. In the second stage of the build, the necessary content from the image built in first stage is copied over and the final image is created.
5. Steps 2,3,4 are observed when you will run the following in your CI/CD pipeline
docker build --build-arg ARG1=<some-value> -t <image-tag> .
6. You can run docker history <image-tag> to check if any sensitive content was exposed in one of the intermediate layers in your docker build step. In this particular example, you wouldn’t find anything like that.

This is just one way of using multi stage build and can be highly effective in managing your Dockerfiles even if you aren’t working with any sensitive content.

Let me know in the comments if you guys have any questions! 😇

Discover and read more posts from Saurabh R
get started
post commentsBe the first to share your opinion
Show more replies