如何使用 hostPath 将一个文件映射到 kubernetes pod 中?

How to map one single file into kubernetes pod using hostPath?

我有一个自己的 nginx 配置 /home/ubuntu/workspace/web.conf 由脚本生成。除了 default.conf

之外,我更喜欢把它放在 /etc/nginx/conf.d

下面是nginx.yaml

apiVersion: v1
kind: Pod
metadata:
    name: nginx
spec:
    volumes:
      - name: webconf
        hostPath:
          path: /home/ubuntu/workspace/web.conf
    containers:
      - image:  nginx
        name: nginx
        ports:
          - containerPort: 18001
            protocol: TCP                               
        volumeMounts:
          - mountPath: /etc/nginx/conf.d/web.conf
            name: web

虽然仅映射为文件夹

$ kubectl create -f nginx.yaml
pod "nginx" created
$ kubectl exec -it nginx -- bash
root@nginx:/app# ls -al /etc/nginx/conf.d/
total 12
drwxr-xr-x 1 root root 4096 Aug  3 12:27 .
drwxr-xr-x 1 root root 4096 Aug  3 11:46 ..
-rw-r--r-- 2 root root 1093 Jul 11 13:06 default.conf
drwxr-xr-x 2 root root    0 Aug  3 11:46 web.conf

它适用于 docker 容器 -v hostfile:containerfile

我如何在 kubernetes 中执行此操作?

顺便说一句:我在 Ubuntu 16.04 LTSkvm

上使用 minikube 0.21.0

尝试像这样使用 volumeMounts 上的 subPath 键:

apiVersion: v1
kind: Pod
metadata:
  name: singlefile
spec:
  containers:
  - image: ubuntu
    name: singlefiletest
    command:
      - /bin/bash
      - -c
      - ls -la /singlefile/ && cat /singlefile/hosts
    volumeMounts:
    - mountPath: /singlefile/hosts
      name: etc
      subPath: hosts
  volumes:
  - name: etc
    hostPath:
      path: /etc

示例:

$ kubectl apply -f singlefile.yaml
pod "singlefile" created
$ kubectl logs singlefile
total 24
drwxr-xr-x. 2 root root 4096 Aug  3 12:50 .
drwxr-xr-x. 1 root root 4096 Aug  3 12:50 ..
-rw-r--r--. 1 root root 1213 Apr 26 21:25 hosts
# /etc/hosts: Local Host Database
#
# This file describes a number of aliases-to-address mappings for the for 
# local hosts that share this file.
...

其实是minikube使用的kvm造成的。

path: /home/ubuntu/workspace/web.conf

如果我登录到 minikube,它是 vm 中的文件夹。

$ ls -al /home/ubuntu/workspace # in minikube host
total 12
drwxrwxr-x 2 ubuntu ubuntu 4096 Aug  3 12:11 .
drwxrwxr-x 5 ubuntu ubuntu 4096 Aug  3 19:28 ..
-rw-rw-r-- 1 ubuntu ubuntu 1184 Aug  3 12:11 web.conf
$ minikube ssh
$ ls -al /home/ubuntu/workspace # in minikube vm
total 0
drwxr-xr-x 3 root root 0 Aug  3 19:41 .
drwxr-xr-x 4 root root 0 Aug  3 19:41 ..
drwxr-xr-x 2 root root 0 Aug  3 19:41 web.conf

我不知道为什么 kvm 主机文件夹会这样代表共享。

因此我使用 minikube mount 命令,参见 host_folder_mount.md,然后它按预期工作。