问题描述
在正常开发(包括构建二进制文件)中,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