如何将文件传递到容器

问题描述 投票:0回答:1

我有一个用例,其中我需要将文件路径作为环境变量传递给在 k8s 中运行的 java 应用程序。

env:
 name: INPUT
 value: /path/to/input.txt

应用程序将从指定位置读取文件。

所以我需要确保当 pod 启动时,这个文件被传递到上面提供的位置的容器。

我知道使用卷和卷挂载,我们可以做到这一点。

spec:
 containers:
 - name: myapp
   image: myapp:latest
   volumeMounts:
   - name: xyz
     mountPath: /app/config
...
...
spec:
 volumes:
 - name: xyz

我不太清楚这是如何工作的。

mounthPath 在整个安排中代表什么位置?

如何使 input.txt 可用于 kubernetes 中的所有设置?

编辑:mountPath 代表容器知道的位置。所以应用程序可以访问它。

kubernetes
1个回答
0
投票

因此,在 Kubernetes Pod 定义中,当您在容器规范内定义

volumeMounts
部分时,
mountPath
是容器内可访问卷(包括您的一个或多个文件)的位置。您的应用程序可以读取和写入此路径,就像它是容器内的本地路径一样。

要将

input.txt
文件传递到您的应用程序,您需要创建一个包含该文件的卷,然后将该卷安装到容器中的所需位置。在 Kubernetes 中创建卷的方法有多种,例如使用 ConfigMap、秘密或直接挂载主机路径。

对于像

input.txt
文件这样的文件,ConfigMap 通常是合适的,除非该文件包含敏感信息(在这种情况下,您需要使用 Secret)。

要使用配置映射,请首先 cd 进入本地计算机上包含

input.txt
的目录。

然后,使用

kubectl
从该文件创建一个 ConfigMap:

kubectl create configmap input-file --from-file=input.txt -n your-namespace

此命令将创建一个名为

input-file
的 ConfigMap,其中包含您的
input.txt

然后更新您的部署 YAML 以使用此 ConfigMap:

    spec:
      containers:
      - name: myapp
        image: myapp:latest
        volumeMounts:
        - name: config-volume
          mountPath: /app/config  # Your app reads the file from /app/config/input.txt
        env:
        - name: INPUT
          value: /app/config/input.txt
      volumes:
      - name: config-volume
        configMap:
          name: input-file  # The name of the ConfigMap created earlier

让我进一步分解:

  • ConfigMap
    input-file
    安装到容器中的路径
    /app/config
  • 在容器内,您的应用程序可以访问位于
    /app/config/input.txt
    的文件。
  • 环境变量
    INPUT
    设置为
    /app/config/input.txt
    ,这是您的应用程序可以用来访问文件的路径。

这可以确保当您的 pod 启动时,

input.txt
文件已安装在容器内的指定位置,并且您的应用程序可以立即开始从中读取。

部署后,您可以通过在正在运行的容器中执行来验证所有设置是否正确:

kubectl exec -it <pod-name> -n your-namespace -- /bin/bash

然后,使用以下命令检查

input.txt
文件是否存在于正确的位置:

cat /app/config/input.txt

希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.