多容器 Pod(Multi-Container Pod)
1
| kubectl get pod <pod-name> -n <namespace> -o yaml | grep "uid:"
|
会输出如下类似行
uid: bcfbdfb5-ce0f-11e9-b83e-080027d4916d
1
| ls -l /var/lib/kubelet/pods/对应UID
|
该目录用于挂载该 Pod 的卷、保存日志以及其他与 Pod 生命周期相关的数据
一、概念与节点结构
- Pod 是 Kubernetes 中可调度的最小单元,包含一个或多个容器,容器共享网络和存储:contentReference[oaicite:17]{index=17}。
- 多容器 Pod用于在一个 Pod 内运行多个高度协作容器(如 sidecar、adapter、ambassador 模式):contentReference[oaicite:18]{index=18}。
- Sidecar 容器是一种辅助主容器功能的容器,在 Kubernetes v1.33 起可以通过
initContainers + restartPolicy: Always 实现 native sidecar 功能:contentReference[oaicite:19]{index=19}。
- Pod 运行在集群中的某个节点上,共享节点资源。
二、访问方式与容器任务
- 容器间通信:Pod 内容器共享网络,通过
localhost 和端口通信:contentReference[oaicite:20]{index=20}。
- 外部访问:可以通过 Pod IP + 服务端口(如 Nginx 80)访问应用。
- 辅助容器任务:使用 Alpine 镜像,搭配
while true; do ...; sleep 10 脚本,每 10 秒生成 index.html,演示数据写入。
三、数据共享与卷挂载
- 使用
emptyDir 卷在容器间共享数据,数据随 Pod 生命周期存在:contentReference[oaicite:21]{index=21}。
- 写入容器写入共享卷,服务容器从相同卷读取数据,对外提供服务,类似云环境中的弹性文件系统。
四、YAML 示例结构
1 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
| apiVersion: v1 kind: Pod metadata: name: multi-container-demo labels: app: multi-demo spec: volumes: - name: shared-volume emptyDir: {} containers: - name: writer image: alpine:latest command: ["/bin/sh", "-c"] args: - | while true; do date > /data/index.html sleep 10 done volumeMounts: - name: shared-volume mountPath: /data - name: nginx image: nginx:1.21-alpine ports: - containerPort: 80 volumeMounts: - name: shared-volume mountPath: /usr/share/nginx/html
|
五 删除重置某个容器(非删POD)
1 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
|
kubectl apply -f multi-container-pod.yaml
kubectl get pod multi-container-pod -o wide
kubectl describe pod multi-container-pod
sudo crictl ps
sudo crictl stop ABC
sudo crictl rm ABC
sudo crictl ps kubectl describe pod multi-container-pod
curl <POD IP>
kubectl delete pod multi-container-pod
|
五、核心要点总结
要点说明 :
- 容器重启 通过 crictl stop + crictl rm 实现,仅重启单个容器,卷数据不丢失
- 删除 Pod 会销毁 emptyDir 卷,导致数据丢失
- 适用场景 emptyDir 更适用于临时数据、缓存或日志等不需持久保存的情况
- 服务连续性 短暂的容器重启(ms 级)不会影响服务连续性,数据持续可用