Why You Should Use Multi-Stage Docker Builds in Production
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!
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…