6.2.1 使用 emptyDir 卷
emptyDir卷是一个与pod共享生命周期的空目录,运行在 pod 内的应用程序可以写入任何文件。因为该卷的生存周期与 pod 的生存周期相关联,所以 删除 pod 时该卷的内容就会丢失。
一个 emptyDir 卷对于在同 pod 中运行的容器之间共享文件特别有用。但是它也可以被单个容器用于将数据临时写入磁盘,例如在大型数据集上执行排序操作时,没有那么多内存可供使用。
在pod中使用 emptyDir 卷
实验介绍:我们将使用Nginx作为WebServer, fortune命令来生成HTML内容,fortune命令每次(10秒间隔)运行时会输出随机的一句格言,并将其输出存储在index.html中。
fortuneloop.sh
#准备nginx镜像
docker pull nginx:alpine
docker tag nginx:alpine 10.0.0.10:5000/luksa/nginx
docker image rm -f nginx:alpine
docker push 10.0.0.10:5000/luksa/nginx
#准备fortune镜像
docker pull luksa/fortune
docker tag luksa/fortune 10.0.0.10:5000/luksa/fortune
docker image rm -f luksa/fortune
docker push 10.0.0.10:5000/luksa/fortune
创建 pod
kubectl delete all --all
cd /root/k8s/
cat >fortune-pod.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: fortune
spec:
containers:
- image: 10.0.0.10:5000/luksa/fortune
name: html-generator
volumeMounts:
- name: html
mountPath: /var/htdocs
- 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
emptyDir: {} #未指定存储介质类型和存储大小限制
EOF
kubectl create -f fortune-pod.yaml
查看 pod 状态
kubectl port-forward fortune 8080:80
#另开一个终端
curl localhost:8080
指定用于 emptyDir 的介质
作为卷来使用的emptyDir,默认是在承载pod工作节点的实际磁盘上创建的,但我们可以让
Kubernetes在tmpfs文件系统 (存在于内存而非硬盘) 上创建emptyDir。
emptyDir 卷是最简单的卷类型,但是其它类型的卷都是在它的基础上构建的,在创建空录后,它们会用数据填充它。
6.2.2 使用 Git 仓库作为存储卷
(不建议使用)
gitRepo卷基本上也是emptyDir卷,它通过克隆Git仓库并在pod启动时(但在创建容器之前)检出特定版本来填充数据,如图6.3所示。
注意:创建gitRepo卷后,它并不能和对应Git仓库保持同步,新建的pod才能获取Git仓库中的最新数据。
从一个克隆的Git仓库中运行web服务器pod
在创建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 被删除时, 卷及其内容被删除。