后端工程Technical Deep Dive

Kubernetes 入门:容器编排实战

发布时间2026/03/29
分类后端工程
预计阅读10 分钟
作者吴长龙
*

Kubernetes 入门:容器编排实战

01.内容

# Kubernetes 入门:容器编排实战

Docker Compose 适合本地开发和小型部署,但对于需要高可用、弹性伸缩的生产环境,Kubernetes(K8s)是行业标准。本文介绍 K8s 核心概念和实战配置。

02.一、核心概念

1.1 架构概览

code snippetcode
┌─────────────────────────────────────────────────────────┐
│                     Kubernetes 集群                      │
│  ┌─────────────┐                                        │
│  │   Master    │  ┌─────────────────────────────────┐  │
│  │  (控制平面)  │  │           Node (工作节点)        │  │
│  │             │  │  ┌─────┐ ┌─────┐ ┌─────┐        │  │
│  │ - API Server│  │  │ Pod │ │ Pod │ │Pod  │        │  │
│  │ - Scheduler │  │  └─────┘ └─────┘ └─────┘        │  │
│  │ - Controller│  │                                  │  │
│  │ - etcd      │  │  ┌─────────────────────────────┐│  │
│  └─────────────┘  │  │         Pod                  ││  │
│                   │  │  ┌─────────┐ ┌─────────┐    ││  │
│                   │  │  │Container│ │Container│    ││  │
│                   │  │  └─────────┘ └─────────┘    ││  │
│                   │  └─────────────────────────────┘│  │
│                   └───────────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘

1.2 核心资源

yaml snippetyaml
# Pod:最小部署单元
apiVersion: v1
kind: Pod
metadata:
  name: my-app
  labels:
    app: my-app
spec:
  containers:
  - name: app
    image: my-app:1.0
    ports:
    - containerPort: 3000

# Deployment:管理 Pod 副本
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: app
        image: my-app:1.0
        ports:
        - containerPort: 3000

# Service:服务发现与负载均衡
apiVersion: v1
kind: Service
metadata:
  name: my-app
spec:
  selector:
    app: my-app
  ports:
  - port: 80
    targetPort: 3000
  type: ClusterIP  # ClusterIP / NodePort / LoadBalancer

# Ingress:HTTP 路由
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: my-app
spec:
  rules:
  - host: api.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: my-app
            port:
              number: 80

03.二、实战配置

2.1 完整的 Deployment

yaml snippetyaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
  labels:
    app: api
spec:
  replicas: 3
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  selector:
    matchLabels:
      app: api
  template:
    metadata:
      labels:
        app: api
        version: v1
    spec:
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 100
            podAffinityTerm:
              labelSelector:
                matchExpressions:
                - key: app
                  operator: In
                  values:
                  - api
              topologyKey: kubernetes.io/hostname
      containers:
      - name: api
        image: my-registry.com/api:1.0
        imagePullPolicy: Always
        ports:
        - containerPort: 3000
          name: http
        env:
        - name: NODE_ENV
          value: "production"
        - name: DB_HOST
          valueFrom:
            configMapKeyRef:
              name: api-config
              key: db.host
        - name: DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: api-secrets
              key: db.password
        resources:
          requests:
            memory: "256Mi"
            cpu: "100m"
          limits:
            memory: "512Mi"
            cpu: "500m"
        livenessProbe:
          httpGet:
            path: /health
            port: http
          initialDelaySeconds: 30
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /ready
            port: http
          initialDelaySeconds: 5
          periodSeconds: 5
        volumeMounts:
        - name: app-data
          mountPath: /app/data
      volumes:
      - name: app-data
        persistentVolumeClaim:
          claimName: api-data

2.2 ConfigMap 与 Secret

yaml snippetyaml
# configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: api-config
data:
  db.host: "postgres.default.svc.cluster.local"
  db.port: "5432"
  redis.host: "redis.default.svc.cluster.local"
  log.level: "info"

---
# secrets.yaml
apiVersion: v1
kind: Secret
metadata:
  name: api-secrets
type: Opaque
stringData:
  db.password: "your-password"
  jwt.secret: "jwt-secret-key"
  api.key: "api-key-value"

2.3 水平自动伸缩(HPA)

yaml snippetyaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: api-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: api
  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
  behavior:
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
      - type: Percent
        value: 10
        periodSeconds: 60
    scaleUp:
      stabilizationWindowSeconds: 0
      policies:
      - type: Percent
        value: 100
        periodSeconds: 15

04.三、本地开发

3.1 Minikube

bash snippetbash
# 安装
brew install minikube
minikube start --cpus 4 --memory 8192

# 启用插件
minikube addons enable ingress
minikube addons enable dashboard
minikube addons enable metrics-server

# 部署应用
kubectl apply -f deployment.yaml

# 查看状态
kubectl get pods
kubectl get services
kubectl get ingress

# 访问服务
minikube service my-app

# Dashboard
minikube dashboard

3.2 Kind(Kubernetes in Docker)

bash snippetbash
# 安装
brew install kind

# 创建集群
kind create cluster --name mycluster

# 多节点集群
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
- role: worker
- role: worker

# 部署
kubectl apply -f deployment.yaml

05.四、常用命令

bash snippetbash
# Pod 管理
kubectl get pods
kubectl get pods -o wide
kubectl describe pod my-app-pod
kubectl logs -f my-app-pod
kubectl exec -it my-app-pod -- sh
kubectl delete pod my-app-pod

# Deployment 管理
kubectl apply -f deployment.yaml
kubectl rollout status deployment/api
kubectl rollout undo deployment/api
kubectl get rs  # 查看副本集
kubectl scale deployment/api --replicas=5

# 调试
kubectl port-forward svc/api 3000:3000
kubectl top pods  # 需要 metrics-server
kubectl get events --sort-by='.lastTimestamp'

# 资源清理
kubectl delete -f deployment.yaml
kind delete cluster

06.五、选型建议

方案适用场景复杂度
自建 K8s大型团队,有运维能力
云服务商 EKS/GKE/ACK生产环境,免运维
K3s边缘计算、小型集群
Minikube/Kind本地开发很低

07.总结

  • Pod:最小单元,通常不直接管理
  • Deployment:管理 Pod 副本和更新
  • Service:服务发现和负载均衡
  • Ingress:HTTP 路由
  • HPA:自动伸缩

对于个人开发者或小团队,建议先用托管 K8s(EKS/GKE)或轻量方案(K3s),积累经验后再考虑自建。

---

*下一篇文章将介绍 CI/CD 容器化部署流程。*