Docker and Kubernetes in Production: A Practical Guide
Containerization has become the standard for deploying modern applications. This guide covers everything you need to know about running Docker and Kubernetes in production environments.
Understanding Containers
Containers package applications with their dependencies, ensuring consistency across environments.
Docker Basics
# Multi-stage build for optimization
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
Kubernetes Architecture
Kubernetes orchestrates containers across clusters of machines.
Key Components
- Pods: Smallest deployable units
- Services: Network access to pods
- Deployments: Manage pod replicas
- ConfigMaps: Configuration data
- Secrets: Sensitive information
Deployment Example
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-app
spec:
replicas: 3
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: web
image: myapp:latest
ports:
- containerPort: 3000
resources:
requests:
memory: "128Mi"
cpu: "100m"
limits:
memory: "256Mi"
cpu: "200m"
Production Best Practices
1. Health Checks
livenessProbe:
httpGet:
path: /health
port: 3000
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 3000
initialDelaySeconds: 5
periodSeconds: 5
2. Resource Management
Always set resource requests and limits to prevent resource starvation.
3. Security
- Use non-root users
- Scan images for vulnerabilities
- Implement network policies
- Use secrets management
4. Monitoring
Implement comprehensive monitoring with Prometheus and Grafana.
Scaling Strategies
Horizontal Pod Autoscaling
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web-app-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web-app
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
Conclusion
Docker and Kubernetes provide powerful tools for deploying scalable, resilient applications. Master these technologies to build production-ready systems.
Comments