主题
32 · Kubernetes 入门
目标:理解 Pod / Deployment / Service / Ingress 与声明式部署,能在本地(kind/minikube)把 Compose 里的 API 镜像跑起来。
前置:22 · Docker 与 Compose · 30 · Prometheus
官方:Kubernetes Docs · kubectl · 本地:kind / minikube
1. 从 Compose 到 K8s 的心智
| Compose | Kubernetes |
|---|---|
service + replicas 弱 | Deployment 管副本与滚动更新 |
| 容器 | Pod(可多容器,调度最小单位) |
| 端口映射 | Service 稳定虚拟 IP/DNS |
| 无统一入口 | Ingress / Gateway |
docker compose up | kubectl apply -f |
先会 Docker 镜像,再学编排——没有镜像,K8s 无处可跑。
2. 必背对象
text
Deployment → 创建/更新 Pod 模板(副本数、镜像)
Service → 把一组 Pod 暴露给集群内外
ConfigMap / Secret → 配置与敏感信息
Ingress → HTTP 路由到 Service(可选)1
2
3
4
2
3
4
| 对象 | 你要会的 |
|---|---|
| Pod | 为何「直接跑 Pod」生产不够(无自愈/扩缩) |
| Label / Selector | Service 如何找到 Pod |
| Probe | liveness / readiness(对标健康检查) |
| Namespace | 环境隔离 |
3. 最小清单示例
deploy.yaml(示意):
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: notesapi
spec:
replicas: 2
selector:
matchLabels:
app: notesapi
template:
metadata:
labels:
app: notesapi
spec:
containers:
- name: api
image: notesapi:local
ports:
- containerPort: 8080
env:
- name: APP_JWT_SECRET
valueFrom:
secretKeyRef:
name: notes-secret
key: jwt
readinessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 3
periodSeconds: 5
---
apiVersion: v1
kind: Service
metadata:
name: notesapi
spec:
selector:
app: notesapi
ports:
- port: 80
targetPort: 80801
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
bash
# kind 示例:先 kind load docker-image notesapi:local
kubectl apply -f deploy.yaml
kubectl get pods,svc
kubectl port-forward svc/notesapi 8080:80
curl http://127.0.0.1:8080/health1
2
3
4
5
2
3
4
5
4. 与 Cron / 配置
| Compose 做法 | K8s |
|---|---|
| 进程内 cron 多副本双跑 | CronJob 或独立 1 副本 scheduler |
.env 文件 | ConfigMap + Secret |
| volume | PVC(DB 等有状态慎用;托管云更常见) |
有状态(MySQL/Redis):学习可单节点;生产优先托管服务,不必暑假自建 Operator。
5. 动手清单
- [ ] 本地集群能
kubectl get nodes - [ ] Deployment 2 副本;删一个 Pod 会拉起
- [ ] Service + port-forward 访问
/health - [ ] 改镜像 tag 滚动更新;
kubectl rollout status - [ ] 口述:Pod 与 Deployment 的关系
6. 项目驱动
| 目标 | 做法 |
|---|---|
| 练手仓上 K8s | 只部署 API;MySQL/Redis 仍 Compose 或云 |
| 可观测 | ServiceMonitor / 注解刮取(进阶);先 port-forward Prom |
| 简历 | 「本地 kind 部署 + 滚动更新」,别写假「大规模集群」 |
7. 常见坑 + AI 审查
| 坑 | 说明 |
|---|---|
镜像 latest + imagePullPolicy 怪象 | 学习钉 tag;kind 需 load 本地镜像 |
| 把 Secret 写进 Git | 用密封/外部注入;示例可用本地 apply |
| 只创建 Pod 无 Deployment | 无自愈 |
| AI 甩一堆 Helm/ServiceMesh | 暑假先裸 YAML 懂对象 |
| readiness 不配 | 未就绪仍接流量 |
8. 下一篇
框架扫读与系列收束:
→ 33 · 微服务框架扫读与总复盘
