微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Viper 配置文件在开发中找到,但在使用 Dockerfile 的生产中未找到

如何解决Viper 配置文件在开发中找到,但在使用 Dockerfile 的生产中未找到

在正常开发(包括构建二进制文件)中,go 找到 config.yaml 文件,但在生产中,当使用 Dockerfile 图像时,它不会。

我的项目文件夹是:

|-cmd
   |- server
     |- main.go
     |- server (executable when built)
|-config
   |-config.yaml
   |-config.go

config.go 是:

func readConfigFile(viperConfig ViperConfig) {
    // Set default values if nil
    if viperConfig.ConfigName == "" {
        viperConfig.ConfigName = "config"
    }
    if viperConfig.ConfigType == "" {
        viperConfig.ConfigType = "yaml"
    }
    if viperConfig.ConfigAddpath == "" {
        // main execute it,so it's path is relative to who execute it.
        viperConfig.ConfigAddpath = "../../config"
    }
    // Read the config
    viper.SetConfigName(viperConfig.ConfigName)
    viper.SetConfigType(viperConfig.ConfigType)
    // This path is from main
    viper.AddConfigPath(viperConfig.ConfigAddpath)

    err := viper.ReadInConfig()
    if err != nil {
        log.Panic(err)
    }
}

我的 dockerfile 是:

FROM golang:alpine AS base

workdir /app
copY . .

RUN go build -o ./cmd/server/server ./cmd/server/main.go

FROM alpine AS final

workdir /app
copY --from=base /app/cmd/server/server ./cmd/server/
copY --from=base /app/config/config.yaml ./config/

CMD [ "./cmd/server/server" ]

从构建的镜像运行容器时显示错误(恐慌)是:

2021/05/12 18:08:32 Config File "config" Not Found in "[/config]"

如何指向配置文件所在的 /app/config/config.yaml

谢谢。

解决方法

viper docs 中,您可以通过多次调用 viper.AddConfigPath 来为配置添加多个搜索路径。

那就试试吧:

viper.AddConfigPath(viperConfig.ConfigAddPath)
viper.AddConfigPath("/app/config") // <- to work with Dockerfile setup

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。