有别于《研发工程师玩转Kubernetes——使用emptyDir在同一Pod不同容器间共享数据》一文中介绍的emptyDir,hostPath可以在同一个Node的不同Pod间共享卷。
下面的清单文件利用了Pod亲和性,让Pod集中到一个Node上。
apiVersion: apps/v1
kind: Deployment
metadata:
name: hostpath-deployment
spec:
selector:
matchLabels:
app: hostpath-container
replicas: 2
template:
metadata:
labels:
app: hostpath-container
spec:
affinity:
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: app
operator: In
values:
- hostpath-container
topologyKey: "kubernetes.io/hostname"
containers:
- name: hostpath-container
image: busybox
command: ["/bin/sh", "-c" ,"if [ -f /tempdir/lockfile ] && ! { set -C; 2>/dev/null >/tempdir/lockfile; }; then tail -f /tempdir/lockfile; else exec 3>/tempdir/lockfile; if [ -n \"$POD_NAME\" ]; then name=$POD_NAME; else name=\"unknown\"; fi; while true; do echo \"this is $name.$name write something to lockfile\"; echo \"$name write something to lockfile\" >&3; sleep 5; done; fi"]
volumeMounts:
- name: hostpath-volume
mountPath: /tempdir
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
volumes:
- name: hostpath-volume
hostPath:
path: /tmp
type: Directory
我们观察创建的两个Pod中文件的内容
kubectl exec pods/hostpath-deployment-65cddc7df8-9qtlv -it -- tail -f /tempdir/lockfile
hostpath-deployment-65cddc7df8-9qtlv write something to lockfile
hostpath-deployment-65cddc7df8-9qtlv write something to lockfile
hostpath-deployment-65cddc7df8-9qtlv write something to lockfile
……
kubectl exec pods/hostpath-deployment-65cddc7df8-ltbgs -it -- tail -f /tempdir/lockfile
hostpath-deployment-65cddc7df8-9qtlv write something to lockfile
hostpath-deployment-65cddc7df8-9qtlv write something to lockfile
hostpath-deployment-65cddc7df8-9qtlv write something to lockfile
……文章来源:https://www.toymoban.com/news/detail-632853.html
可以看到它们的文件内容一样,即可以证明它们可以共享同一个文件。
我们在hostpath映射的宿主机目录/tmp下可以找到lockfile文件,且其内容也是明文可读的。
文章来源地址https://www.toymoban.com/news/detail-632853.html
参考资料
- https://kubernetes.io/zh-cn/docs/concepts/storage/volumes/#hostPath
到了这里,关于研发工程师玩转Kubernetes——hostPath的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!