Description
Complete guide to containerizing applications with Docker, including multi-stage builds and best practices.
Objective
Enable developers to package, build, and deploy applications efficiently using Docker.
Solution
Environment Setup
- 1Install Docker on your system.
- 2Verify installation with `docker --version`.
- 3Initialize project directory with application code.
Basic Dockerfile
- 1Create a Dockerfile in the project root.
- 2
dockerfile
FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm install --production COPY . . CMD ["node", "index.js"]
Build & Run
- 1Build image with `docker build -t myapp:latest .`.
- 2Run container with `docker run -p 3000:3000 myapp:latest`.
Multi-Stage Builds
- 1Use multiple FROM statements to separate build and runtime.
- 2
dockerfile
# Stage 1: Build FROM node:18-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm install COPY . . RUN npm run build # Stage 2: Runtime FROM node:18-alpine AS runner WORKDIR /app COPY --from=builder /app/dist ./dist COPY package*.json ./ RUN npm install --production CMD ["node", "dist/index.js"]
Best Practices
- 1Use lightweight base images (e.g., alpine).
- 2Leverage multi-stage builds to reduce image size.
- 3Pin versions for reproducibility.
- 4Minimize layers by combining commands.
- 5Use .dockerignore to exclude unnecessary files.
- 6Run as non-root user for security.
- 7Tag images properly (myapp:v1.0.0).
- 8Scan images for vulnerabilities.
Testing & Validation
- 1Run unit tests inside Docker container.
- 2Validate container startup and logs.
- 3Push image to registry with `docker push myrepo/myapp:v1.0.0`.
Deployment
- 1Use Docker Compose for multi-container apps.
- 2Deploy to Kubernetes or ECS for production.
Tool Stack Used
- π³Docker
- π³Docker Compose
- βKubernetes
- βοΈAWS ECS
- πCI/CD Tools