Deployment YAML 配置
学习目标
- 掌握 Deployment YAML 的基本结构
- 理解各字段的含义和作用
- 能够编写完整的 Deployment 配置
核心概念
基本结构
apiVersion: apps/v1 # API 版本
kind: Deployment # 资源类型
metadata:
name: my-app # Deployment 名称
labels:
app: my-app # 标签
spec:
replicas: 3 # 副本数量
selector:
matchLabels:
app: my-app # 选择器(匹配 Pod 标签)
template: # Pod 模板
metadata:
labels:
app: my-app # Pod 标签
spec:
containers:
- name: my-app
image: nginx:1.24 # 容器镜像
ports:
- containerPort: 80
必填字段说明
| 字段 | 说明 |
|---|---|
apiVersion | apps/v1(Deployment 固定用这个) |
kind | Deployment |
metadata.name | Deployment 名称 |
spec.replicas | Pod 副本数量 |
spec.selector | 选择哪些 Pod 由这个 Deployment 管理 |
spec.template | Pod 模板(定义 Pod 长什么样) |
selector 配置
spec:
selector:
matchLabels: # 匹配 Pod 标签
app: my-app
tier: frontend
template:
metadata:
labels: # Pod 标签必须和 selector 匹配
app: my-app
tier: frontend
重要:selector 一旦创建不能修改
Pod 模板配置
spec:
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-app
image: nginx:1.24
ports:
- containerPort: 80
resources: # 资源限制
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "500m"
memory: "256Mi"
env: # 环境变量
- name: ENV
value: "production"
完整示例
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
environment: production
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.24
ports:
- containerPort: 80
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "200m"
memory: "256Mi"
livenessProbe: # 存活探针
httpGet:
path: /
port: 80
initialDelaySeconds: 10
periodSeconds: 5
readinessProbe: # 就绪探针
httpGet:
path: /
port: 80
initialDelaySeconds: 5
periodSeconds: 3
常用可选配置
spec:
minReadySeconds: 10 # Pod 就绪后等待多久才认为可用
revisionHistoryLimit: 10 # 保留多少旧 ReplicaSet
strategy: # 更新策略
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1 # 更新时最多有几个不可用
maxSurge: 1 # 更新时最多多出几个 Pod
实践练习
练习 1:编写基础 Deployment
编写一个 Deployment,要求:
- 名称:web-app
- 镜像:nginx:1.24
- 副本数:2
- 端口:80
练习 2:添加资源配置
在上面的 Deployment 中添加:
- CPU 请求:100m,限制:200m
- 内存请求:128Mi,限制:256Mi
练习 3:添加探针
添加存活探针和就绪探针,检查 /health 端口 8080
常见错误
1. selector 和 labels 不匹配
# 错误:selector 和 template.labels 不一致
spec:
selector:
matchLabels:
app: web # 这里是 web
template:
metadata:
labels:
app: nginx # 这里是 nginx,不匹配!
# 正确:必须一致
spec:
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web # 保持一致
2. 忘记写 selector
# 错误:没有 selector
spec:
replicas: 3
template: ...
# 正确:必须有 selector
spec:
replicas: 3
selector:
matchLabels:
app: my-app
template: ...
小结
| 要点 | 说明 |
|---|---|
| apiVersion | 固定为 apps/v1 |
| selector | 选择管理哪些 Pod,必须和 template.labels 匹配 |
| template | 定义 Pod 模板 |
| replicas | 指定副本数量 |
| resources | 建议设置资源限制 |
| probes | 建议配置存活和就绪探针 |
练习编辑器
bash
Loading...