一、核心结构
```yaml
apiVersion: v1 # 资源类型所属API组(如 apps/v1, networking.k8s.io/v1)
kind: Pod # 资源类型(Pod/Deployment/Service等)
metadata: # 元数据(名称、标签、注解等)
name: web-app
labels:
app: nginx
spec: # 资源的具体配置(核心部分)
containers:
- name: nginx
image: nginx:1.25
二、常用资源类型及配置
1. Pod
apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
containers:
- name: main
image: busybox
command: ["sh", "-c", "sleep 3600"]
- name: sidecar
image: nginx
resources:
limits:
memory: "128Mi"
cpu: "500m"
关键字段
command
: 覆盖容器启动命令resources
: 资源限制(CPU/内存)env
: 环境变量volumeMounts
: 挂载存储卷
2. Deployment(无状态应用)
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-deploy
spec:
replicas: 3
selector:
matchLabels:
app: web
template: # Pod模板(类似Pod的spec)
metadata:
labels:
app: web
spec:
containers:
- name: nginx
image: nginx:1.25
readinessProbe: # 就绪探针
httpGet:
path: /
port: 80
关键字段
replicas
: 副本数strategy
: 更新策略(RollingUpdate/Recreate)revisionHistoryLimit
: 保留的历史版本数
3. Service(服务暴露)
apiVersion: v1
kind: Service
metadata:
name: web-svc
spec:
type: NodePort # ClusterIP/NodePort/LoadBalancer
selector:
app: web # 关联Pod的标签
ports:
- protocol: TCP
port: 80 # Service端口
targetPort: 80 # 容器端口
nodePort: 30080 # NodePort模式下宿主机端口
三、高级技巧
1. 多配置文件管理
- 使用
---
分隔多个资源 - 通过
kubectl apply -f <dir>
批量部署
# deploy.yaml
apiVersion: apps/v1
kind: Deployment
metadata: { ... }
---
apiVersion: v1
kind: Service
metadata: { ... }
2. 动态变量注入
env:
- name: DB_HOST
valueFrom:
configMapKeyRef:
name: db-config
key: host
- name: SECRET_KEY
valueFrom:
secretKeyRef:
name: app-secrets
key: api-key
四、调试命令
# 验证YAML语法
kubectl apply --dry-run=client -f deploy.yaml
# 查看资源详情
kubectl describe pod/web-app
# 查看事件日志
kubectl get events --sort-by='.metadata.creationTimestamp'
# 导出当前运行配置为YAML
kubectl get deploy/web-deploy -o yaml > current.yaml
五、常见错误
错误现象 | 解决方案 |
| 检查镜像名称/权限/仓库地址 |
| 查看容器日志 |
端口冲突(如题) | 修改 |
graph TD
A[编写YAML] --> B{语法校验}
B -->|通过| C[部署]
B -->|失败| D[修正字段]
C --> E[查看Pod状态]
E --> F{Running?}
F -->|是| G[完成]
F -->|否| H[排查日志/事件]
💡 最佳实践
- 使用
kustomize
或helm
管理复杂配置 - 为资源添加
labels
和annotations
增强可读性 - 生产环境配置
resource limits
防止资源耗尽