6.2.1 使用 emptyDir 卷

emptyDir卷是一个与pod共享生命周期的空目录,运行在 pod 内的应用程序可以写入任何文件。因为该卷的生存周期与 pod 的生存周期相关联,所以 删除 pod 时该卷的内容就会丢失。

一个 emptyDir 卷对于在同 pod 中运行的容器之间共享文件特别有用。但是它也可以被单个容器用于将数据临时写入磁盘,例如在大型数据集上执行排序操作时,没有那么多内存可供使用。

在pod中使用 emptyDir 卷

实验介绍:我们将使用Nginx作为WebServer, fortune命令来生成HTML内容,fortune命令每次(10秒间隔)运行时会输出随机的一句格言,并将其输出存储在index.html中。

fortuneloop.sh
image.png

  1. #准备nginx镜像
  2. docker pull nginx:alpine
  3. docker tag nginx:alpine 10.0.0.10:5000/luksa/nginx
  4. docker image rm -f nginx:alpine
  5. docker push 10.0.0.10:5000/luksa/nginx
  6. #准备fortune镜像
  7. docker pull luksa/fortune
  8. docker tag luksa/fortune 10.0.0.10:5000/luksa/fortune
  9. docker image rm -f luksa/fortune
  10. docker push 10.0.0.10:5000/luksa/fortune

创建 pod

image.png

  1. kubectl delete all --all
  2. cd /root/k8s/
  3. cat >fortune-pod.yaml <<'EOF'
  4. apiVersion: v1
  5. kind: Pod
  6. metadata:
  7. name: fortune
  8. spec:
  9. containers:
  10. - image: 10.0.0.10:5000/luksa/fortune
  11. name: html-generator
  12. volumeMounts:
  13. - name: html
  14. mountPath: /var/htdocs
  15. - image: 10.0.0.10:5000/luksa/nginx
  16. name: web-server
  17. volumeMounts:
  18. - name: html
  19. mountPath: /usr/share/nginx/html
  20. readOnly: true
  21. ports:
  22. - containerPort: 80
  23. protocol: TCP
  24. volumes:
  25. - name: html
  26. emptyDir: {} #未指定存储介质类型和存储大小限制
  27. EOF
  28. kubectl create -f fortune-pod.yaml

查看 pod 状态

kubectl port-forward fortune 8080:80

#另开一个终端
curl localhost:8080

image.png

指定用于 emptyDir 的介质

作为卷来使用的emptyDir,默认是在承载pod工作节点的实际磁盘上创建的,但我们可以让
Kubernetes在tmpfs文件系统 (存在于内存而非硬盘) 上创建emptyDir。
image.png
emptyDir 卷是最简单的卷类型,但是其它类型的卷都是在它的基础上构建的,在创建空录后,它们会用数据填充它。

6.2.2 使用 Git 仓库作为存储卷

(不建议使用)
gitRepo卷基本上也是emptyDir卷,它通过克隆Git仓库并在pod启动时(但在创建容器之前)检出特定版本来填充数据,如图6.3所示。
image.png

注意:创建gitRepo卷后,它并不能和对应Git仓库保持同步,新建的pod才能获取Git仓库中的最新数据。

从一个克隆的Git仓库中运行web服务器pod

image.png

在创建pod时,首先将卷初始化为个空目录,然后将制定的Git仓库克隆到其中。如果没有将目录设置为.(句点),仓库将会被克隆到kubia-website-exampl示例目录中,远不是我们想要的结果。我们预期仓库克隆到卷的根目录中。在设置仓库时,我们还需要指明让Kubernetes切换到master分支所在的版本。

cd /root/k8s

cat >gitrepo-volume-pod.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: gitrepo-volume-pod
spec:
  containers:
  - image: 10.0.0.10:5000/luksa/nginx
    name: web-server
    volumeMounts:
    - name: html
      mountPath: /usr/share/nginx/html
      readOnly: true
    ports:
    - containerPort: 80
      protocol: TCP
  volumes:
  - name: html
    gitRepo:
      repository: https://github.com/luksa/kubia-website-example.git
      revision: master
      directory: .
EOF

kubectl create -f gitrepo-volume-pod.yaml

kubectl port-forward gitrepo-volume-pod 8080:80

#另开一个终端
curl localhost:8080

确认文件未与 Git 仓库保持同步

对Github项目进行更改,发现pod的web服务器返回没有改变。要查看新版本的站点,需要删除pod并重建。

介绍 sidecar 容器

使用第二个容器sidecar,实现本地目录与Git仓库同步。
去Docker Hub搜索“git sync”镜像。

使用带有私有 Git 仓库的 gitRepo 卷

如果想要将私有的Git repo克隆到容器中,则应该使用gitsync sidecar或类似的方法, 而不是使用gitRepo卷。

总结 gitRepo 存储卷

当 pod 被删除时, 卷及其内容被删除。