Multi Stage Docker Build

Always learning
3 min read4 days ago

--

Multi-stage build, you will first build the image that contains only the dependencies needed to build your application. Then, after the image has been built, you can add in any additional layers needed to create your application and configure it for deployment.

It helps minimize the attack surface and reduces the time required to pull and deploy images.

Improved Build Performance: Multi-stage builds enable parallelism by separating the build process into distinct stages.

Multi-stage builds, you use multiple FROM statements in your Dockerfile. Each FROM instruction represents a different base image and begins a new stage of the build process.

Benefits of Multi-Stage Builds:

  1. Smaller Images
  2. Enhanced Security
  3. Improved Efficiency
  4. Uniform Syntax
  5. Debugging and Targeting Specific Stages

buymeacoffee ☕ 👈 Click the link

Hands on Docker Multistage

Clone github repository

https://github.com/Ibrahimsi/todoapp-docker.git
cd todoapp-docker/

Create Empty Dockerfile

touch Dockerfile

Before Multistage

FROM node:18-alpine AS installer
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

Paste the code .. Create a new Dockerfile

FROM node:18-alpine AS installer
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

FROM nginx:latest AS deployer
COPY --from=installer /app/build /usr/share/nginx/html

Stage 1 (Installer):

  • Base image: node:18-alpine
  • Working directory: /app
  • Copy package*.json files to the working directory.
  • Run npm install
  • Copy the entire context (including your source code) to the working directory.
  • Build your application using npm run build

Stage 2 (Deployer):

  • Base image: nginx:latest
  • Copy the build artifacts from the installer stage (specifically, the /app/build directory) to the Nginx web server’s default HTML directory (/usr/share/nginx/html)

Build Dockerfile

docker build -t todo-project .

After Multistage

Run Docker Container

# Run container image in the local environment.
docker run -dp 3010:3010 todo-project

Logs check

docker logs CONTAINER ID

Access the inside of container

docker exec -it 756db6740f7f sh

Check html folder

cd /usr/share/nginx/html

View the content of Docker container

Thank you 🙏 for taking the time to read our blog.

--

--

Always learning

கற்றுக் கொள்ளும் மாணவன்...