Docker Image Building
This chapter covers how to build custom Docker images using Dockerfiles, including the build process, multi-stage builds, and optimization techniques.
Build Basics
docker build Command
bash
docker build -t myapp:v1.0 . # Basic build
docker build -t myapp:v1.0 -f Dockerfile.prod . # Specify Dockerfile
docker build --no-cache -t myapp:v1.0 . # No cache
docker build --build-arg VERSION=1.0 -t myapp:v1.0 . # Build argumentsBuild Context
Use .dockerignore to exclude unnecessary files:
node_modules
.git
*.md
.env
distBuild Examples
Node.js Application
dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]Python Application
dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "app.py"]Go Application
dockerfile
FROM golang:1.22-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o main .
FROM alpine:3.19
COPY --from=builder /app/main /main
EXPOSE 8080
CMD ["/main"]Java Application
dockerfile
FROM maven:3.9-eclipse-temurin-21 AS builder
WORKDIR /app
COPY pom.xml .
RUN mvn dependency:go-offline
COPY src ./src
RUN mvn package -DskipTests
FROM eclipse-temurin:21-jre-alpine
COPY --from=builder /app/target/*.jar app.jar
EXPOSE 8080
CMD ["java", "-jar", "app.jar"]Multi-Stage Builds
Separate build and runtime environments to reduce final image size:
dockerfile
FROM node:20 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]| Build Method | Image Size |
|---|---|
| Single-stage (with Node.js) | ~1.2 GB |
| Multi-stage (Nginx + static files) | ~30 MB |
Optimization Tips
1. Choose the Right Base Image
dockerfile
FROM node:20 # Full (~900MB)
FROM node:20-slim # Slim (~200MB)
FROM node:20-alpine # Alpine (~130MB)2. Merge RUN Instructions
dockerfile
# ✅ Single RUN, fewer layers
RUN apt-get update && \
apt-get install -y curl && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*3. Leverage Build Cache
Place less-frequently-changing instructions first:
dockerfile
COPY package*.json ./
RUN npm ci
COPY . .4. Use Non-Root User
dockerfile
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser
CMD ["node", "server.js"]Image Tag Management
bash
docker build -t myapp:v1.0 -t myapp:latest .
docker tag myapp:v1.0 myregistry.com/myapp:v1.0
docker push myregistry.com/myapp:v1.0Chapter Summary
Image building is a core Docker skill. Use multi-stage builds, choose minimal base images, and leverage build cache to create small, secure, fast-building images.