K8s挂载文件到目录,不清空原有目录文件

问题

如果只是使用mount功能来挂载一个文件到某个路径下,则这个路径下原有的文件将会被清空。

挂载config.toml到/etc/apt/下

apiVersion: apps/v1
kind: Deployment
    spec:
      volumes:
        - name: runner-config-demo1
          configMap:
            name: runner-config-demo1
            items:
              - key: config.toml
                path: config.toml
      containers:
        - name: lcdp-runner
          image: gitlab-runner:v13.5.0
          volumeMounts:
            - name: runner-config-demo1
              mountPath: /etc/apt/

挂载前

$ ls /etc/apt/
apt.conf.d  auth.conf.d  preferences.d  sources.list  sources.list.d  trusted.gpg.d

挂载后

$ ls /etc/apt/
config.toml

解决

使用subPath功能即可

apiVersion: apps/v1
kind: Deployment
    spec:
      volumes:
        - name: runner-config-demo1
          configMap:
            name: runner-config-demo1
            items:
              - key: config.toml
                path: config.toml
      containers:
        - name: lcdp-runner
          image: gitlab-runner:v13.5.0
          volumeMounts:
            - name: runner-config-demo1
              # 注意,区别只在此处,另外,mountPath和subPath都要加上config.toml。
              mountPath: /etc/apt/config.toml
              subPath: config.toml

挂载后

$ ls /etc/apt/
apt.conf.d  auth.conf.d  config.toml  preferences.d  sources.list  sources.list.d  trusted.gpg.d

备注

Docker Swarm也有类似的挂载问题,还没找到解决方案,有大佬知道解决方案的,希望可以不吝赐教,在评论区留下解决方案可否

原文地址:https://www.cnblogs.com/xiaojiluben/p/14983056.html