Kubernetes YAML 学习内容


## 一、核心认知

  • K8s 一切皆资源,每个资源都有对应的 API

  • 对外用 YAML 描述"期望状态",控制器不断向期望状态收敛

  • 通式理解:所有 YAML 都是"俄罗斯套娃"——外层固定四件套,spec 里逐层嵌套


二、YAML 基础语法

 # 注释用 #
 key: value              # 冒号后必须有空格
 list:
   - item1
   - item2
 map:
   key1: value1

规则

说明

缩进

只能用空格,不能用 Tab,通常 2 空格

大小写

严格区分

多文档

用 --- 分隔

字符串

一般不用引号,含特殊字符时用引号


三、四大必填字段(必背)

 apiVersion: apps/v1       # ① API 版本
 kind: Deployment          # ② 资源类型
 metadata:                 # ③ 元数据
   name: nginx-deploy
 spec:                     # ④ 期望状态(每种资源结构不同)
   replicas: 3

缺失后果:

字段

缺失后果

apiVersion

无法解析用哪个版本 API

kind

不知道创建什么资源

metadata.name

没有唯一标识,无法管理

spec

控制器不知道你想要什么状态

apiVersion 常用值:

资源

apiVersion

Pod / Service / ConfigMap / Secret / Namespace

v1

Deployment / ReplicaSet / DaemonSet

apps/v1

Job / CronJob

batch/v1

Ingress

networking.k8s.io/v1

HPA

autoscaling/v2

查询:kubectl api-resources | grep <资源名>


四、Deployment YAML 逐行详解

下面这份 YAML 是最典型的 Deployment 模板,每行都加了注释,务必理解。

 apiVersion: apps/v1        # API版本(必选)
 kind: Deployment           # 资源类型(必选)
 metadata:                  # 元数据(必选) 描述、名称、标签、简介、创建时间...
   labels:                  # 标签(可选) 筛选、负载均衡、资源调度
     app: nginx             # Key-Value 可以是多对
   name: nginx              # 资源名称
 spec:                      # 规格(期望状态)
   replicas: 3              # 副本数
   selector:                # 标签选择器 deployment -> rs -> pod
     matchLabels:           # 选择标签
       app: nginx           # 被选择 Pod 的标签
   template:                # Pod模板: 根据 template 模板来创建 Pod
     metadata:              # Pod 的元数据
       labels:              # Pod 的标签
         app: nginx         # KV
     spec:                  # Pod 的规格
       containers:          # 容器的详细设置
       - image: nginx:1.25  # 镜像
         name: nginx        # 容器名称

字段层级关系(必记)

 Deployment
   ├── spec.selector.matchLabels  ← 必须匹配 ↓
   └── spec.template.metadata.labels  ← 被匹配的 Pod 标签

关联链路:

 Deployment → ReplicaSet → Pod
    通过 selector.matchLabels 逐级关联

易错点:spec.selector.matchLabels 必须与 spec.template.metadata.labels 完全匹配,否则 api-server 拒绝创建。

Deployment 完整层级树

 Deployment YAML
 ├── apiVersion: apps/v1
 ├── kind: Deployment
 ├── metadata
 │   ├── name / namespace
 │   └── labels / annotations
 └── spec
     ├── replicas: 3
     ├── revisionHistoryLimit: 10
     ├── strategy (滚动更新策略)
     │   ├── type: RollingUpdate
     │   └── rollingUpdate
     │       ├── maxSurge: 1
     │       └── maxUnavailable: 0
     ├── selector                ← 必须匹配 template.labels
     │   └── matchLabels
     │       └── app: nginx
     └── template                ← Pod 模板
         ├── metadata.labels
         │   └── app: nginx
         └── spec
             └── containers[]
                 ├── name / image / imagePullPolicy
                 ├── ports
                 ├── env (value / valueFrom)
                 ├── resources (requests / limits)
                 ├── livenessProbe / readinessProbe
                 └── volumeMounts

通式理解:所有 K8s YAML 都是"俄罗斯套娃"——外层固定四件(apiVersion、kind、metadata、spec),spec 里再逐层嵌套,理解了通式就掌握了所有资源。


五、完整 Deployment 示例(含高级字段)

 apiVersion: apps/v1
 kind: Deployment
 metadata:
   name: api-deploy
   namespace: default
   labels:
     app: api
     version: v1
 spec:
   replicas: 3
   revisionHistoryLimit: 10                # 保留 10 个历史版本用于回滚
   strategy:
     type: RollingUpdate
     rollingUpdate:
       maxSurge: 1                         # 更新时最多多出 1 个 Pod
       maxUnavailable: 0                   # 更新时不可用 Pod 数为 0(零停机)
   selector:
     matchLabels:
       app: api
   template:
     metadata:
       labels:
         app: api
     spec:
       containers:
       - name: api
         image: harbor.example.com/app:v1.0
         imagePullPolicy: IfNotPresent     # 本地有就不拉取
         ports:
         - containerPort: 8080
           name: http
         env:
         - name: LOG_LEVEL
           value: "info"
         - name: DB_HOST
           valueFrom:
             configMapKeyRef:              # 从 ConfigMap 取环境变量
               name: app-config
               key: DB_HOST
         resources:
           requests: { cpu: "200m", memory: "256Mi" }   # 最小需求
           limits:   { cpu: "1", memory: "512Mi" }      # 最大上限
         livenessProbe:                    # 存活探针:失败则重启容器
           httpGet: { path: /health, port: 8080 }
           initialDelaySeconds: 15         # 启动后等 15 秒再探测
           periodSeconds: 10               # 每 10 秒探测一次
         readinessProbe:                   # 就绪探针:失败则从 Service 摘除
           httpGet: { path: /ready, port: 8080 }
           initialDelaySeconds: 5
           periodSeconds: 5


六、高频资源模板速查

6.1 Pod

 apiVersion: v1
 kind: Pod
 metadata:
   name: nginx-pod
 spec:
   containers:
     - name: nginx
       image: nginx:1.25
       ports:
         - containerPort: 80
       resources:
         requests: { cpu: "100m", memory: "128Mi" }
         limits:   { cpu: "500m", memory: "256Mi" }
   restartPolicy: Always        # Always / OnFailure / Never

6.2 Service

apiVersion: v1
kind: Service
metadata:
  name: nginx-svc
spec:
  type: ClusterIP              # ClusterIP / NodePort / LoadBalancer / ExternalName
  selector:
    app: nginx                 # 匹配 Pod 标签
  ports:
    - port: 80                 # Service 端口
      targetPort: 80           # 容器端口
      nodePort: 30080          # 仅 NodePort(30000-32767)

类型

说明

ClusterIP

集群内部访问(默认)

NodePort

节点 IP + 端口访问

LoadBalancer

云厂商负载均衡

ExternalName

DNS CNAME 映射

6.3 ConfigMap

apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  LOG_LEVEL: debug
  app.properties: |
    key1=value1

6.4 Secret

apiVersion: v1
kind: Secret
metadata:
  name: db-secret
type: Opaque
data:
  password: cGFzc3dvcmQ=       # base64 编码
stringData:                    # 明文写法(推荐)
  username: admin

base64 生成:echo -n 'password' | base64

6.5 在 Pod 中使用 ConfigMap/Secret

# 方式一:环境变量
env:
  - name: LOG_LEVEL
    valueFrom:
      configMapKeyRef: { name: app-config, key: LOG_LEVEL }
  - name: DB_PASSWORD
    valueFrom:
      secretKeyRef: { name: db-secret, key: password }

# 方式二:挂载为文件
volumeMounts:
  - name: config
    mountPath: /etc/config
volumes:
  - name: config
    configMap: { name: app-config }

6.6 其他常用资源(一句话记住)

资源

apiVersion

用途

Namespace

v1

资源隔离

Job

batch/v1

一次性任务

CronJob

batch/v1

定时任务(schedule: "*/5 * * * *")

Ingress

networking.k8s.io/v1

七层入口

ResourceQuota

v1

命名空间总额限

LimitRange

v1

单 Pod 默认限制


七、高频字段速查

7.1 探针三种方式

# HTTP
httpGet: { path: /health, port: 8080 }
# TCP
tcpSocket: { port: 8080 }
# 命令
exec:
  command: ["cat", "/tmp/healthy"]

7.2 生命周期

lifecycle:
  postStart:                   # 容器启动后执行
    exec: { command: ["/bin/sh", "-c", "echo started"] }
  preStop:                     # 容器停止前执行(优雅退出)
    exec: { command: ["/bin/sh", "-c", "sleep 5"] }

7.3 调度约束

nodeSelector:                  # 简单节点选择
  disktype: ssd
tolerations:                   # 容忍污点
  - key: "key1"
    operator: "Equal"
    value: "value1"
    effect: "NoSchedule"

7.4 Labels 设计规范(官方推荐)

labels:
  app.kubernetes.io/name: nginx
  app.kubernetes.io/instance: my-api-abcxzy
  app.kubernetes.io/version: "1.24.0"
  app.kubernetes.io/component: frontend
  app.kubernetes.io/part-of: shop-system
  app.kubernetes.io/managed-by: helm
  # 自定义加前缀
  zj.com/env: prod

原则:前缀约定、≤63 字符、name+instance 唯一标识、有意义的枚举值、宁缺毋滥。


八、资源缩写速查表

缩写

全称

说明

no

nodes

节点

po

pods

最小调度单位

svc

services

负载均衡

deploy

deployments

无状态服务控制器

rs

replicasets

副本集

ns

namespaces

命名空间

cm

configmaps

配置管理

pv / pvc

persistentvolumes / claims

持久卷 / 声明

ing

ingresses

访问入口

sa

serviceaccounts

服务账户

sts

statefulsets

有状态服务

ds

daemonsets

每节点一个

sc

storageclasses

存储类型

netpol

networkpolicies

网络策略

hpa

horizontalpodautoscalers

自动扩缩容

rb / crb

rolebindings / clusterrolebindings

RBAC 授权


九、常用 kubectl 指令速查(附注释)

9.1 生成 YAML(dry-run)

# 生成 Deployment 骨架,不真正创建(--dry-run=client 只试运行)
kubectl create deploy nginx --image=nginx --replicas=3 --dry-run=client -o yaml > deploy.yaml

# 生成 Pod 骨架(--restart=Never 表示生成 Pod 而非 Deployment)
kubectl run my-pod --image=busybox --restart=Never --dry-run=client -o yaml > pod.yaml

# 生成 Service(clusterip 类型,--tcp=80:80 表示 Service端口:容器端口)
kubectl create svc clusterip nginx --tcp=80:80 --dry-run=client -o yaml > svc.yaml

# 生成 NodePort 类型 Service(--node-port 指定节点暴露端口)
kubectl create svc nodeport nginx --tcp=80:80 --node-port=30080 --dry-run=client -o yaml > svc-np.yaml

# 生成 ConfigMap(--from-literal 直接写键值对)
kubectl create cm app-config --from-literal=LOG_LEVEL=debug --dry-run=client -o yaml > cm.yaml

# 从文件生成 ConfigMap(--from-file 把文件内容作为配置)
kubectl create cm nginx-conf --from-file=nginx.conf --dry-run=client -o yaml > cm-file.yaml

# 生成 Secret(明文写入,自动 base64 编码)
kubectl create secret generic db-password --from-literal=password=root123 --dry-run=client -o yaml > secret.yaml

# 生成 Namespace
kubectl create ns team-dev --dry-run=client -o yaml > ns.yaml

# 生成 Job(一次性任务)
kubectl create job migrate --image=myapp:migrate --dry-run=client -o yaml > job.yaml

# 生成 CronJob(--schedule 定时表达式,分 时 日 月 周)
kubectl create cj daily-backup --image=mysql:8.0 --schedule="0 2 * * *" --dry-run=client -o yaml > cj.yaml

9.2 查看与导出

# 导出已有资源为 YAML(用于备份)
kubectl get deploy nginx -o yaml > nginx-backup.yaml

# 查看资源列表(-A 表示所有命名空间)
kubectl get pods -A

# 查看资源详情(describe 会显示事件、状态等排错信息)
kubectl describe pod nginx-pod

# 查看资源日志(-f 实时跟踪)
kubectl logs -f nginx-pod

# 进入容器(-it 交互式终端,-- 后面跟命令)
kubectl exec -it nginx-pod -- /bin/sh

9.3 应用与删除

# 应用 YAML(创建或更新,声明式)
kubectl apply -f deploy.yaml

# 删除资源(-f 指定文件,或用资源名)
kubectl delete -f deploy.yaml
kubectl delete pod nginx-pod

# 编辑在线资源(保存后立即生效)
kubectl edit deploy nginx

9.4 排错与查询

# 查看 API 资源版本(确认 apiVersion 写什么)
kubectl api-resources | grep hpa

# 查看字段说明(内置 API 文档)
kubectl explain deployment.spec.strategy

# 递归查看所有字段(输出极长,建议重定向)
kubectl explain deployment.spec.template --recursive > fields.txt

# 查看字段是否必填
kubectl explain deployment.spec.selector | grep -i required

9.5 扩缩容与回滚

# 扩缩容(副本数改为 5)
kubectl scale deploy nginx --replicas=5

# 查看滚动更新历史
kubectl rollout history deploy nginx

# 回滚到上一版本
kubectl rollout undo deploy nginx

# 回滚到指定版本(--to-revision 指定版本号)
kubectl rollout undo deploy nginx --to-revision=2

# 查看滚动更新状态
kubectl rollout status deploy nginx