kubernetes 从卷中理解 configmap

kubernetes understanding configmap from volume

我正在玩弄 kubernetes 配置映射,想了解卷挂载是如何工作的

我有一个名为 client_config.json 的 json 配置文件,即

{
  "name": "place",
  "animal": "thing",
  "age": 10
}

我使用命令创建了一个配置映射

kubectl create configmap client-config --from-file=client_config.json

然后我将它挂载到我部署的一个卷上

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: go-web-app
spec:
  replicas: 2
  selector:
    matchLabels:
      name: go-web-app
  template:
    metadata:
      labels:
        name: go-web-app
    spec:
      containers:
        - name: application
          image: my/repo
          ports:
            - containerPort: 3000
          volumeMounts:
            - name: config
              mountPath: /client-config
              readOnly: true
      volumes:
        - name: config
          configMap:
            name: client-config

在我的 go 应用程序中,我可以使用

读取配置
func config(w http.ResponseWriter, r *http.Request) {
    b, err := ioutil.ReadFile(filepath.Clean("./client_config.json"))
    if err != nil {
        fmt.Fprintf(w, fmt.Sprintf("error reading config: %s", err))
    } else {
        fmt.Fprintf(w, fmt.Sprintf("config value is : %s", string(b)))
    }

}

我的问题是 configmap 被挂载到挂载路径

mountPath: /client-config

但我是从代码中读取它的

b, err := ioutil.ReadFile(filepath.Clean("./client_config.json"))

当我将 configmap 作为文件读取时甚至不需要引用它时,挂载路径 /client-config 有什么用?

./client_config.json 是相对文件路径。您应用的当前工作目录很可能是 /client-config。您的实际文件位于 /client-config/client_config.json.

感谢 David 的评论,我得以解决问题。

问题是我将 client_config.json 文件与图像一起包含在内,因此我的代码能够通过路径 ./client_config.json

引用它

在我重建没有 client_config.json 的图像后,我得到了错误

error reading config: open client_config.json: no such file or directory

然后我更正了我的代码以使用挂载路径,现在我能够从卷中将配置映射作为文件读取

b, err := ioutil.ReadFile(filepath.Clean("/client-config/client_config.json"))
if err != nil {
    fmt.Fprintf(w, fmt.Sprintf("error reading config: %s", err))
} else {
    fmt.Fprintf(w, fmt.Sprintf("config value is : %s", string(b)))
}