第327集容器化部署架构实战:Docker与Kubernetes企业级容器编排的完整解决方案
|字数总计:2.3k|阅读时长:11分钟|阅读量:
容器化部署架构实战:Docker与Kubernetes企业级容器编排
一、Docker基础
1.1 Docker简介
Docker是一个开源的容器化平台,允许将应用和依赖打包到轻量级、可移植的容器中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| Docker核心概念: Image (镜像): - 应用的只读模板 - 包含运行所需的所有内容 - 可以从仓库拉取或自己构建 Container (容器): - 镜像的运行实例 - 轻量级、隔离的运行环境 - 可以启动、停止、删除 Dockerfile: - 用于构建镜像的脚本 - 定义应用的运行环境 - 包含构建步骤和依赖 Registry (仓库): - 存储和分发镜像的地方 - Docker Hub、阿里云、Harbor
|
1.2 Docker安装
1 2 3 4 5 6 7 8 9 10 11 12
| curl -fsSL https://get.docker.com -o get-docker.sh sudo sh get-docker.sh
sudo yum install -y docker sudo systemctl start docker sudo systemctl enable docker
docker --version docker run hello-world
|
1.3 Docker基础命令
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| docker images docker pull nginx docker rmi nginx docker build -t myapp:1.0 .
docker run -d nginx docker ps docker ps -a docker stop container_id docker start container_id docker rm container_id
docker logs container_id docker inspect container_id docker exec -it container_id bash
|
二、Dockerfile构建
2.1 Dockerfile编写
基础Dockerfile示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| FROM ubuntu:20.04
LABEL maintainer="devops@example.com" LABEL version="1.0"
ENV DEBIAN_FRONTEND=noninteractive \ PYTHON_VERSION=3.9
WORKDIR /app
COPY requirements.txt . COPY app.py .
RUN apt-get update && \ apt-get install -y python3 python3-pip && \ pip3 install -r requirements.txt && \ apt-get clean && \ rm -rf /var/lib/apt/lists/*
EXPOSE 8080
CMD ["python3", "app.py"]
|
2.2 多阶段构建
优化镜像大小
1 2 3 4 5 6 7 8 9 10 11 12 13
| FROM node:16 AS builder WORKDIR /app COPY package*.json ./ RUN npm install COPY . . RUN npm run build
FROM nginx:alpine COPY --from=builder /app/dist /usr/share/nginx/html EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]
|
2.3 最佳实践Dockerfile
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| FROM python:3.9-slim
RUN useradd -m -u 1000 appuser
WORKDIR /app
COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt
COPY --chown=appuser:appuser . .
USER appuser
HEALTHCHECK --interval=30s --timeout=3s \ CMD curl -f http://localhost:8000/health || exit 1
EXPOSE 8000
CMD ["python", "app.py"]
|
三、Docker Compose
3.1 Compose基础配置
docker-compose.yml示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| version: '3.8'
services: web: build: . ports: - "8000:8000" environment: - DATABASE_URL=postgresql://db:5432/myapp depends_on: - db - redis networks: - app-network restart: unless-stopped
db: image: postgres:13 environment: - POSTGRES_DB=myapp - POSTGRES_USER=appuser - POSTGRES_PASSWORD=secret volumes: - db-data:/var/lib/postgresql/data networks: - app-network restart: unless-stopped
redis: image: redis:6-alpine command: redis-server --appendonly yes volumes: - redis-data:/data networks: - app-network restart: unless-stopped
nginx: image: nginx:alpine ports: - "80:80" volumes: - ./nginx.conf:/etc/nginx/nginx.conf depends_on: - web networks: - app-network
volumes: db-data: redis-data:
networks: app-network: driver: bridge
|
3.2 Compose命令
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| docker-compose up -d
docker-compose ps
docker-compose logs -f
docker-compose down
docker-compose up -d --build
docker-compose up -d --scale web=3
|
四、Kubernetes基础
4.1 Kubernetes架构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| Kubernetes核心组件: Master节点: - API Server: 集群入口 - etcd: 分布式存储 - Controller Manager: 控制器管理 - Scheduler: 调度器 Worker节点: - Kubelet: 节点代理 - Kube-proxy: 网络代理 - Container Runtime: 容器运行时 Pod: - 最小部署单元 - 一个或多个容器的集合 - 共享网络和存储 Service: - 稳定的网络端点 - 负载均衡 - 服务发现
|
4.2 核心概念
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| Kubernetes资源对象: Deployment: - 声明式更新 - 滚动更新 - 回滚能力 Service: - ClusterIP: 集群内部访问 - NodePort: 节点端口暴露 - LoadBalancer: 云负载均衡 ConfigMap: - 配置数据存储 - 应用配置 Secret: - 敏感数据存储 - 密码、token等 Namespace: - 资源隔离 - 多租户
|
五、Kubernetes部署实战
5.1 Deployment配置
完整的Deployment示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| apiVersion: apps/v1 kind: Deployment metadata: name: web-app namespace: production labels: app: web-app version: v1.0 spec: replicas: 3 strategy: type: RollingUpdate rollingUpdate: maxSurge: 1 maxUnavailable: 0 selector: matchLabels: app: web-app template: metadata: labels: app: web-app version: v1.0 spec: containers: - name: web image: myregistry/web-app:v1.0 ports: - containerPort: 8080 protocol: TCP env: - name: DATABASE_URL valueFrom: secretKeyRef: name: db-secret key: url - name: LOG_LEVEL valueFrom: configMapKeyRef: name: app-config key: log_level resources: requests: memory: "256Mi" cpu: "250m" limits: memory: "512Mi" cpu: "500m" livenessProbe: httpGet: path: /health port: 8080 initialDelaySeconds: 30 periodSeconds: 10 readinessProbe: httpGet: path: /ready port: 8080 initialDelaySeconds: 5 periodSeconds: 5 volumeMounts: - name: config mountPath: /app/config readOnly: true volumes: - name: config configMap: name: app-config
|
5.2 Service配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| apiVersion: v1 kind: Service metadata: name: web-app-service namespace: production spec: type: LoadBalancer ports: - port: 80 targetPort: 8080 protocol: TCP name: http selector: app: web-app
|
5.3 ConfigMap和Secret
ConfigMap配置
1 2 3 4 5 6 7 8 9
| apiVersion: v1 kind: ConfigMap metadata: name: app-config namespace: production data: log_level: info max_connections: "100" timeout: "30s"
|
Secret配置
1 2 3 4 5 6 7 8 9
| apiVersion: v1 kind: Secret metadata: name: db-secret namespace: production type: Opaque data: url: cG9zdGdyZXNxbDovL3VzZXI6cGFzc0Bob3N0OjU0MzIvZGI= password: c2VjcmV0cGFzc3dvcmQ=
|
5.4 命名空间管理
1 2 3 4 5 6 7 8 9 10 11 12
| kubectl create namespace production kubectl create namespace development
kubectl config set-context --current --namespace=production
kubectl get namespaces
kubectl get all -n production
|
六、Kubernetes高级特性
6.1 HPA自动扩缩容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: name: web-app-hpa namespace: production 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 - type: Resource resource: name: memory target: type: Utilization averageUtilization: 80
|
6.2 Ingress配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: web-app-ingress namespace: production annotations: nginx.ingress.kubernetes.io/rewrite-target: / cert-manager.io/cluster-issuer: letsencrypt-prod spec: ingressClassName: nginx tls: - hosts: - app.example.com secretName: web-app-tls rules: - host: app.example.com http: paths: - path: / pathType: Prefix backend: service: name: web-app-service port: number: 80
|
6.3 持久化存储
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| apiVersion: v1 kind: PersistentVolumeClaim metadata: name: db-pvc namespace: production spec: accessModes: - ReadWriteOnce resources: requests: storage: 20Gi storageClassName: fast-ssd --- apiVersion: apps/v1 kind: Deployment metadata: name: database spec: replicas: 1 selector: matchLabels: app: database template: metadata: labels: app: database spec: containers: - name: postgres image: postgres:13 volumeMounts: - name: data mountPath: /var/lib/postgresql/data volumes: - name: data persistentVolumeClaim: claimName: db-pvc
|
七、CI/CD集成
7.1 GitLab CI配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
stages: - build - test - deploy
variables: DOCKER_REGISTRY: registry.example.com IMAGE_TAG: $CI_COMMIT_REF_SLUG
build: stage: build script: - docker build -t $DOCKER_REGISTRY/web-app:$IMAGE_TAG . - docker push $DOCKER_REGISTRY/web-app:$IMAGE_TAG only: - main - develop
test: stage: test script: - docker run --rm $DOCKER_REGISTRY/web-app:$IMAGE_TAG npm test
deploy: stage: deploy script: - kubectl set image deployment/web-app web-app=$DOCKER_REGISTRY/web-app:$IMAGE_TAG -n production environment: name: production only: - main
|
7.2 Jenkins Pipeline
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
pipeline { agent any environment { DOCKER_REGISTRY = 'registry.example.com' K8S_NAMESPACE = 'production' } stages { stage('Build') { steps { sh 'docker build -t ${DOCKER_REGISTRY}/web-app:${BUILD_NUMBER} .' sh 'docker push ${DOCKER_REGISTRY}/web-app:${BUILD_NUMBER}' } } stage('Test') { steps { sh 'docker run --rm ${DOCKER_REGISTRY}/web-app:${BUILD_NUMBER} npm test' } } stage('Deploy') { steps { sh ''' kubectl set image deployment/web-app web-app=${DOCKER_REGISTRY}/web-app:${BUILD_NUMBER} -n ${K8S_NAMESPACE} kubectl rollout status deployment/web-app -n ${K8S_NAMESPACE} ''' } } } }
|
八、监控和日志
8.1 Prometheus监控
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| apiVersion: apps/v1 kind: Deployment metadata: name: prometheus spec: replicas: 1 template: spec: containers: - name: prometheus image: prom/prometheus volumeMounts: - name: config mountPath: /etc/prometheus volumes: - name: config configMap: name: prometheus-config ---
apiVersion: monitoring.coreos.com/v1 kind: ServiceMonitor metadata: name: web-app-monitor spec: selector: matchLabels: app: web-app endpoints: - port: http path: /metrics
|
8.2 Elasticsearch日志采集
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| apiVersion: v1 kind: ConfigMap metadata: name: fluentd-config data: fluent.conf: | <source> @type tail path /var/log/containers/*.log pos_file /var/log/fluentd-containers.log.pos tag kubernetes.* read_from_head true </source> <match **> @type elasticsearch host elasticsearch port 9200 logstash_format true </match>
|
九、生产环境最佳实践
9.1 安全配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| apiVersion: v1 kind: Pod metadata: name: secure-pod spec: securityContext: runAsNonRoot: true runAsUser: 1000 fsGroup: 1000 containers: - name: app image: myapp:latest securityContext: allowPrivilegeEscalation: false readOnlyRootFilesystem: true capabilities: drop: - ALL
|
9.2 资源限制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| apiVersion: v1 kind: Pod metadata: name: resource-limited spec: containers: - name: app image: myapp:latest resources: requests: memory: "128Mi" cpu: "100m" limits: memory: "256Mi" cpu: "500m"
|
9.3 健康检查
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| apiVersion: v1 kind: Pod metadata: name: health-checked spec: containers: - name: app image: myapp:latest livenessProbe: httpGet: path: /health port: 8080 initialDelaySeconds: 30 periodSeconds: 10 failureThreshold: 3 readinessProbe: httpGet: path: /ready port: 8080 initialDelaySeconds: 5 periodSeconds: 5
|
十、故障排查
10.1 Pod问题排查
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| kubectl get pods -n production
kubectl describe pod web-app-xxx -n production
kubectl logs web-app-xxx -n production
kubectl exec -it web-app-xxx -n production -- bash
kubectl get events --sort-by=.metadata.creationTimestamp
|
10.2 服务问题排查
1 2 3 4 5 6 7 8 9 10 11
| kubectl get svc -n production
kubectl get endpoints web-app-service -n production
kubectl port-forward svc/web-app-service 8080:80 -n production
kubectl run -it --rm debug --image=busybox --restart=Never -- nslookup web-app-service
|
10.3 集群问题排查
1 2 3 4 5 6 7 8 9 10 11 12
| kubectl get nodes
kubectl describe node node-name
kubectl get events --all-namespaces --sort-by=.metadata.creationTimestamp
kubectl top nodes kubectl top pods -n production
|
十一、总结
容器化部署已成为现代应用部署的标准。本文涵盖了:
Docker核心
- Dockerfile构建:多阶段构建、最佳实践
- Docker Compose:多容器编排
- 镜像优化:减少大小、加速构建
Kubernetes核心
- 资源管理:Deployment、Service、ConfigMap、Secret
- 自动扩缩容:HPA、VPA
- 网络和存储:Ingress、PVC
企业级实践
- CI/CD集成:GitLab CI、Jenkins
- 监控和日志:Prometheus、EFK
- 安全配置:非root用户、权限限制
实践建议
- 镜像构建:遵循多阶段构建
- 资源配置:合理设置requests和limits
- 健康检查:启用liveness和readiness探针
- 监控告警:实施全链路监控
- 安全合规:最小权限与定期审计
通过Docker和Kubernetes,可实现高效、可扩展的容器化部署。