登录
首页 >  Golang >  Go问答

从存储卷中探索 Kubernetes 的配置映射

来源:stackoverflow

时间:2024-02-16 20:33:22 332浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《从存储卷中探索 Kubernetes 的配置映射》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我正在研究 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 有什么用?


正确答案


感谢 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)))
}

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

本篇关于《从存储卷中探索 Kubernetes 的配置映射》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>