返回首页

Kubernetes 入门

为什么需要 K8s

当容器数量超过个位数,手工管理变得不现实:

K8s 把这些自动化了。

核心概念

Pod

K8s 调度的最小单位。一个 Pod 可以包含一个或多个共享网络和存储的容器。

apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
    - name: nginx
      image: nginx:alpine
      ports:
        - containerPort: 80

Deployment

管理 Pod 的副本数,支持滚动更新和回滚:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: web
          image: nginx:1.25

Service

给一组 Pod 一个稳定的网络入口:

apiVersion: v1
kind: Service
metadata:
  name: web-svc
spec:
  selector:
    app: web
  ports:
    - port: 80
      targetPort: 80

常用命令

kubectl get pods -o wide          # 查看 Pod 及所在节点
kubectl logs -f <pod>             # 跟踪日志
kubectl exec -it <pod> -- sh      # 进入 Pod
kubectl apply -f deploy.yaml      # 应用配置
kubectl rollout status deploy/web # 查看滚动更新状态
kubectl rollout undo deploy/web   # 回滚

心智模型

K8s 是「声明式」的:你不告诉它怎么做,而是告诉它你要什么状态。它不停地把集群往你描述的那个状态拉。

与 [[docker-basics]] 对比:Docker 管单台机器上的容器,K8s 管整个集群。