我的 K8s 集群有一个主节点和一个工作节点。
场景 – 1 我正在同一个 POD 中部署一个简单的 sidecar 容器,其中我将emptyDir 定义为共享卷,并且它工作正常。清单文件
apiVersion: apps/v1
kind: Deployment
metadata:
name: pod-with-sidecar
namespace: test
spec:
replicas: 1
selector:
matchLabels:
app: debian-nginx
template:
metadata:
labels:
app: debian-nginx
spec:
containers:
- name: main-debian
image: debian
command: ["/bin/sh"]
args: ["-c", "while true; do date >> /var/log/index.html; sleep 2;done"]
volumeMounts:
- mountPath: /var/log
name: shared-log
- name: sidecar-nginx
image: nginx
volumeMounts:
- mountPath: /usr/share/nginx/index.html
name: shared-log
volumes:
- name: shared-log
emptyDir: {}
这里
在 Container – 1 中,文件被创建并且内容在 /car/log/index.html 中可用
同样,在 Container – 2 中,文件被创建,内容在 usr/share/nginx/html/index.html 中可用
场景 – 2 我正在同一 POD 中部署相同的简单 sidecar 容器,其中我将 hosPath 定义为共享卷,但它不起作用。清单文件
apiVersion: apps/v1
kind: Deployment
metadata:
name: pod-with-sidecar
namespace: test
spec:
replicas: 1
selector:
matchLabels:
app: debian
app: nginx
template:
metadata:
labels:
app: debian
app: nginx
spec:
containers:
# Main application container
- name: main-debian
image: debian
command: ["/bin/sh", "-c"]
args: ["while true; do data >> /var/log/index.html; sleep 2;done"]
volumeMounts:
- mountPath: /var/log
name: shared-vol
# Sidecar container
- name: sidecar-nginx
image: nginx:1.7.9
ports:
- containerPort: 80
volumeMounts:
- mountPath: /usr/share/nginx/html # nginx-specific mount path
name: shared-vol
volumes:
- name: shared-vol
hostPath:
path: /mydata
type: DirectoryOrCreate
这里
在 Container – 1 中创建了文件,但 /car/log/index.html 中没有可用内容
testuser@kmasterl:~$ kubectl exec -it pod-with-sidecar-85f88c9d5d-xjcgh -c main-debian -n test -- /bin/bash
root@pod-with-sidecar-85f88c9d5d-xjcgh:/# ls -lrt var/log
total 0 -rw-r--r-- 1 root root 0 Dec 14 21:28 index.html
root@pod-with-sidecar-85f88c9d5d-xjcgh:/# cat /var/log/index.html
root@pod-with-sidecar-85f88c9d5d-xjcgh:/#
类似地,在 Container – 2 中创建了文件,但 usr/share/nginx/html/index.html 中没有可用内容
testuser@kmasterl:~$ kubectl exec -it pod-with-sidecar-85f88c9d5d-xjcgh -c sidecar-nginx -n test -- /bin/bash
root@pod-with-sidecar-85f88c9d5d-xjcgh:/# ls -lrt /usr/share/nginx/html
total 0 -rw-r--r-- 1 root root 0 Dec 14 21:28 index.html
root@pod-with-sidecar-85f88c9d5d-xjcgh:/# cat usr/share/nginx/html/index.html
root@pod-with-sidecar-85f88c9d5d-xjcgh:/#
有人可以建议为什么当 hostPath 定义为共享卷时它不起作用吗?
如果我正确理解您想要实现的目标,我会使用
emptyDir
方法。
也就是说,当您使用
hostPath
时,在底层主机上创建的文件或目录只能由 root 写入。您需要在特权容器中以 root 身份运行进程,或者修改主机上的文件权限以便能够写入 hostPath
卷。有关更多详细信息,请参阅:https://kubernetes.io/docs/concepts/storage/volumes/