一、EmptyDir简介
EmptyDir是最基础的Volume类型,一个EmptyDir就是Host上一个空目录
EmptyDir是在Pod被分配到Node时创建的,它的初始内容为空,并且无需指定宿主机上对应的目录文件,因为Kubernetes会自动分配一个目录,当pod销毁时,EmptyDir中的数据也会被永久删除
EmptyDir的用途如下:
- 临时空间,例如用于某些应用程序运行时所需要的临时目录,且无需永久保留
- 一个容器需要从另一个容器中获取数据的目录(多容器共享目录)
二、EmptyDir应用实例演示
应用场景:在一个pod中准备两个容器nginx和busybox,然后声明一个Volume分别挂到两个容器的目录中,然后nginx容器负责想Volume中写日志,busybox中通过命令将日志内容读取到控制台
编辑emptydir.yaml内容如下:
apiVersion: v1
kind: Namespace
metadata:
name: dev
---
apiVersion: v1
kind: Pod
metadata:
name: volume-emptydir
namespace: dev
spec:
containers:
- name: nginx
image: nginx:1.17.1
ports:
- containerPort: 80
volumeMounts:
- name: logs-volume
mountPath: /var/log/nginx
- name: busybox
image: busybox:1.30
command: ["/bin/sh","-c","tail -f /logs/access.log"]
volumeMounts:
- name: logs-volume
mountPath: /logs
volumes:
- name: logs-volume
emptyDir: {}
然后使用如下命令创建
[root@master Volume]# kubectl apply -f emptydir.yaml
namespace/dev unchanged
pod/volume-emptydir created
[root@master Volume]#
查看创建pod如下:
[root@master Volume]# kubectl get pod -n dev -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
volume-emptydir 2/2 Running 0 5m52s 10.244.1.121 node1 <none> <none>
[root@master Volume]#
验证如下,首先通过curl访问一次nginx,然后就可以看到busybox中有一条输出
[root@master Volume]# curl 10.244.1.121:80
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
[root@master Volume]#
[root@master Volume]# kubectl logs -f volume-emptydir -n dev -c busybox
10.244.0.0 - - [06/Apr/2022:17:27:35 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"