Why You Should Use Multi-Stage Docker Builds in Production

Bryant Hagadorn
ITNEXT
Published in
5 min readJul 20, 2020

--

It’s not too often that speed and security combine forces, but when they do, it’s a surefire way to know that a pattern is worth adopting. It’s like a car part that looks good and makes your car faster — how can you go wrong? In this post (with copious amounts of examples), I’m going to show you what multi-stage Docker builds are and how they are faster and more secure!

Packaging Docker containers is very similar to an assembly line, multiple stages give us flexibility on what we include or don’t include in our final product.

Optionally, for the source code in this article, please refer to this GitHub repository.

How Dockerfiles Work

Docker containers are usually built with a Dockerfile, a set of instructions that help you package your source code, install dependencies, and build your application (if it compiles a binary). However, a lot of times the things you need to build your application aren’t the things you need to run your application. Let’s consider a standard Node Dockerfile from the Nodejs website.

// Node Sample Dockerfile - Single StageFROM node:12
ADD . /app
WORKDIR /app
RUN npm install
EXPOSE 8080
CMD [ "node", "server.js" ]

You’ll notice that before we start working with directories and copying files into the image, we start with FROM node:12 . You see, Dockerfiles are like a giant onion and the first FROM is the core of your onion. It gives you…

--

--

Writer for

Kubernetes, security, and other ramblings! I love learning and writing about what I learn. LinkedIn: https://www.linkedin.com/in/bryanthagadorn/