从虚拟机迁移到 Kubernetes

适用场景

把运行在虚拟机上的应用迁移到 Kubernetes,获得弹性、标准化发布和资源隔离。迁移不是简单把进程放进容器,需要处理配置、存储、网络和运维方式。

前置条件

步骤

  1. 盘点应用:
systemctl list-units --type=service --state=running
ss -lntp
ps -eo pid,cmd --sort=-%mem | head
  1. 容器化应用:
cat > Dockerfile <<'EOF'
FROM eclipse-temurin:21-jre
WORKDIR /app
COPY target/app.jar app.jar
USER 10001
ENTRYPOINT ["java","-jar","/app/app.jar"]
EOF
docker build -t registry.example.com/app:1.0.0 .
docker push registry.example.com/app:1.0.0
  1. 拆分配置和密钥:
kubectl create configmap app-config --from-file=application.yaml
kubectl create secret generic app-secret --from-literal=DB_PASSWORD='***'
  1. 编写 Deployment 和 Service:
kubectl apply -f - <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
spec:
  replicas: 2
  selector:
    matchLabels: {app: app}
  template:
    metadata:
      labels: {app: app}
    spec:
      containers:
      - name: app
        image: registry.example.com/app:1.0.0
        ports: [{containerPort: 8080}]
        envFrom:
        - configMapRef: {name: app-config}
        - secretRef: {name: app-secret}
        readinessProbe:
          httpGet: {path: /health, port: 8080}
EOF
  1. 处理有状态数据:数据库、文件存储和会话。优先使用托管数据库或独立 PVC。

  2. 配置 Ingress/Gateway、NetworkPolicy 和 HPA。

  3. 灰度切流:先迁移非核心流量,再逐步扩大。

验证

回滚

常见坑

相关命令