Day 3/40 - Multi-Stage Docker Build

CKA Full Course 2024 ☸️

Pre-Requisites

If you’ve already followed the Day 2 video or have Docker installed, skip this step.

Use Docker and Kubernetes Sandbox Environments:

Play with Docker

Play with Kubernetes

Download Docker Desktop

Get Docker Desktop for your operating system here: Docker Desktop


Hands-On: Multi-Stage Build Tutorial

Step 1: Clone a Sample Repository

Use the following repository or your application:

git clone https://github.com/piyushsachdeva/todoapp-docker.git
cd todoapp-docker/

Step 2: Create a Dockerfile

touch Dockerfile

Add this content using your text editor:

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

Step 3: Build and Test the Image

Build the image:

docker build -t todoapp-docker .

Verify the image:

docker images

Step 4: Push to Docker Hub

Login and push the image:

docker login  

docker tag todoapp-docker:latest <username>/<repo>:<tag>

docker push <username>/<repo>:<tag>

Step 5: Pull and Run the Container

Pull the image:

docker pull <username>/<repo>:<tag>

Run the container:

docker run -dp 3000:80 <username>/<repo>:<tag>

Key Multi-Stage Build Commands

Command Explanation:

FROM Specifies the base image and starts a new build stage.

WORKDIR Sets the working directory inside the container.

COPY Copies files from the local system to the container.

RUN Executes commands (e.g., installs dependencies or builds code).

--from Used in COPY to reference artifacts from previous stages.


Why Use Multi-Stage Builds?

Benefits

Optimized Image Size: Remove unnecessary build tools and files.

Improved Security: Reduce the attack surface by minimizing layers in the production image.

Simpler CI/CD Pipelines: Create production-ready images efficiently.


Task 3/40

1. Dockerize an app with multi-stage builds and document the process.

2. Highlight the benefits of multi-stage builds in your blog.

3. Explore and document the docker init command.

4. Share your blog on LinkedIn or Twitter, tagging @PiyushSachdeva and @CloudOps Community with the hashtag #40daysofkubernetes.


Video Tutorial

Happy Learning! Dive deep into Kubernetes and refine your Docker skills!