Recap of Previous Days
- Day 1: We explored Docker fundamentals, the issues before containers, how Docker solves these problems, the differences between Docker and virtual machines, and an overview of Docker's workflow and architecture.
- Day 2: We dockerized a sample application, installed Docker Desktop, cloned an application, wrote a Dockerfile, and explored Docker commands like build, tag, push, pull, and run.
Today's Focus: Docker Multi-Stage Builds
Previously, we faced challenges with our Dockerfile, which resulted in an image size of over 200 MB, even with a lightweight Alpine image. Today, we'll use Docker multi-stage builds to significantly reduce that image size.
Step-by-Step Guide to Multi-Stage Builds
- Clone the Application:
git clone https://github.com/docker/getting-started-app.git
cd getting-started-app
- Create a Dockerfile:
touch Dockerfile
vi Dockerfile
- Write the Dockerfile:
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
FROM nginx:latest AS deployer
COPY --from=builder /app/build /usr/share/nginx/html
- Build the Docker Image:
docker build -t multi-stage .
- Run the Docker Container:
docker run -p 3000:80 multi-stage
Key Benefits of Multi-Stage Builds
- Reduced Image Size: By only copying necessary files from the builder stage to the final image.
- Improved Performance: Smaller images mean faster deployment times and reduced resource consumption.
- Enhanced Security: Only the essential files are included in the final image, reducing the attack surface.
Conclusion
Multi-stage builds are a best practice for creating efficient, secure, and high-performance Docker images. They help in isolating different build stages and only including the necessary artefacts in the final image. This approach not only reduces the image size but also enhances the overall performance and security of the Docker containers.
Thank you for reading, and stay tuned for the next entry in our CKA series. Happy learning!
Top comments (0)