最佳实践

1. 使用命名空间隔离
# 创建专用命名空间
kubectl create namespace production
kubectl create namespace development

# 设置默认命名空间
kubectl config set-context --current --namespace=production
2. 最小权限原则(RBAC)
# 创建 ServiceAccount
kubectl create serviceaccount myapp-sa

# 创建 Role
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: default
  name: pod-reader
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "watch", "list"]

# 绑定 Role
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-pods
  namespace: default
subjects:
- kind: ServiceAccount
  name: myapp-sa
  namespace: default
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io
3. 使用 Secret 存储敏感信息
# 避免在环境变量中直接传递密码
# 使用 Secret 或外部密钥管理系统(如 Vault)
4. 网络策略
# 限制 Pod 间通信
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-all
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress
5. 镜像安全
  • 使用官方或可信的镜像
  • 定期扫描镜像漏洞
  • 使用最小化基础镜像(如 alpine)
  • 避免使用 root 用户运行容器

1. 始终设置资源请求和限制
resources:
  requests:
    memory: "256Mi"
    cpu: "500m"
  limits:
    memory: "512Mi"
    cpu: "1000m"
2. 使用 Horizontal Pod Autoscaler(HPA)
# 创建 HPA
kubectl autoscale deployment myapp \
  --cpu-percent=50 \
  --min=2 \
  --max=10

# YAML 定义
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: myapp-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: myapp
  minReplicas: 2
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 50
3. 使用资源配额(Resource Quotas)
apiVersion: v1
kind: ResourceQuota
metadata:
  name: compute-resources
  namespace: development
spec:
  hard:
    requests.cpu: "4"
    requests.memory: 8Gi
    limits.cpu: "8"
    limits.memory: 16Gi
4. 使用 LimitRange
apiVersion: v1
kind: LimitRange
metadata:
  name: default-limits
  namespace: default
spec:
  limits:
  - default:
      memory: 512Mi
      cpu: "1"
    defaultRequest:
      memory: 256Mi
      cpu: "500m"
    type: Container

1. 配置 Liveness Probe
livenessProbe:
  httpGet:
    path: /health
    port: 8080
  initialDelaySeconds: 30
  periodSeconds: 10
  timeoutSeconds: 5
  failureThreshold: 3
2. 配置 Readiness Probe
readinessProbe:
  httpGet:
    path: /ready
    port: 8080
  initialDelaySeconds: 10
  periodSeconds: 5
  timeoutSeconds: 3
  failureThreshold: 3
3. 使用 Startup Probe(慢启动应用)
startupProbe:
  httpGet:
    path: /startup
    port: 8080
  initialDelaySeconds: 0
  periodSeconds: 5
  timeoutSeconds: 3
  failureThreshold: 30  # 最多等待 150 秒
4. 探针配置建议
  • initialDelaySeconds:给应用足够的启动时间
  • periodSeconds:不要过于频繁,避免浪费资源
  • timeoutSeconds:根据应用响应时间设置
  • failureThreshold:避免因暂时性问题导致频繁重启
  • 使用 TCP、HTTP、EXEC 三种探针类型

1. 使用声明式配置
# 使用 YAML 文件管理部署
kubectl apply -f deployment.yaml

# 使用 git 管理 YAML 文件
git add deployment.yaml
git commit -m "Update deployment"
git push
2. 配置滚动更新
strategy:
  type: RollingUpdate
  rollingUpdate:
    maxSurge: 25%
    maxUnavailable: 25%
3. 使用多个副本
# 生产环境至少 2-3 个副本
replicas: 3
4. 使用标签组织资源
metadata:
  labels:
    app: myapp
    version: v1.0.0
    environment: production
    team: backend
5. 配置反亲和性
affinity:
  podAntiAffinity:
    preferredDuringSchedulingIgnoredDuringExecution:
    - weight: 100
      podAffinityTerm:
        labelSelector:
          matchExpressions:
          - key: app
            operator: In
            values:
            - myapp
        topologyKey: kubernetes.io/hostname

1. 集中式日志收集
  • 使用 ELK Stack(Elasticsearch、Logstash、Kibana)
  • 使用 EFK Stack(Elasticsearch、Fluentd、Kibana)
  • 使用 Loki + Grafana
2. 监控指标
  • 使用 Prometheus + Grafana
  • 监控 Pod、Node、Cluster 指标
  • 设置告警规则
3. 使用标签和注释
metadata:
  labels:
    app: myapp
    version: v1.0.0
  annotations:
    description: "My application"
    owner: "team@example.com"
4. 日志规范
  • 使用结构化日志(JSON 格式)
  • 包含时间戳、日志级别、请求 ID
  • 避免记录敏感信息

1. 配置与代码分离
  • 使用 ConfigMap 存储非敏感配置
  • 使用 Secret 存储敏感信息
  • 考虑使用外部配置中心(如 Consul)
2. 使用不可变 ConfigMap
apiVersion: v1
kind: ConfigMap
metadata:
  name: immutable-config
immutable: true
3. 配置版本管理
  • 使用 git 管理 YAML 配置文件
  • 使用标签区分不同环境配置
  • 使用 ConfigMap 版本控制
4. 使用 Helm 管理复杂应用
# 安装 Helm
curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash

# 使用 Helm 部署应用
helm install myapp ./myapp-chart

# 升级应用
helm upgrade myapp ./myapp-chart

# 回滚应用
helm rollback myapp