☸️ DevOps

Kubernetes 部署最佳实践:容器编排实战指南

深入讲解Kubernetes容器编排的核心概念和最佳实践,包括Pod配置、Service配置、Ingress配置、水平扩展等关键技术

一、Kubernetes概述

Kubernetes是Google开源的容器编排平台,提供自动化部署、扩展和管理容器化应用的能力。

二、Pod配置最佳实践

Pod是Kubernetes的最小部署单元,合理配置Pod可以提高应用的稳定性和性能。

apiVersion: v1
kind: Pod
metadata:
  name: my-app
spec:
  containers:
  - name: app
    image: my-app:latest
    resources:
      requests:
        memory: "128Mi"
        cpu: "250m"
      limits:
        memory: "256Mi"
        cpu: "500m"
    livenessProbe:
      httpGet:
        path: /health
        port: 80
      initialDelaySeconds: 10
      periodSeconds: 5
    readinessProbe:
      httpGet:
        path: /ready
        port: 80
      initialDelaySeconds: 5
      periodSeconds: 3

三、Service配置策略

Service提供了Pod的稳定访问地址,支持多种服务发现模式。

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  type: ClusterIP
  selector:
    app: my-app
  ports:
  - port: 80
    targetPort: 8080

四、Ingress配置与SSL

Ingress提供了HTTP/HTTPS路由和负载均衡功能。

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: my-ingress
  annotations:
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
spec:
  tls:
  - hosts:
    - example.com
    secretName: example-tls
  rules:
  - host: example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: my-service
            port:
              number: 80

五、Deployment配置策略

Deployment管理Pod的部署和更新,支持滚动更新和回滚。

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-deployment
spec:
  replicas: 3
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: app
        image: my-app:v1.0.0

六、水平自动扩展(HPA)

HPA根据CPU或自定义指标自动调整Pod副本数。

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: my-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: my-deployment
  minReplicas: 2
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70

七、ConfigMap与Secret管理

ConfigMap和Secret用于管理应用配置和敏感信息。

八、持久化存储方案

选择合适的存储类满足应用的数据持久化需求。

九、监控与日志

使用Prometheus和EFK栈进行监控和日志管理。

十、安全最佳实践

包括RBAC配置、网络策略、镜像安全等方面。