在正常开发中(包含构建二进制文件),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
配置文件所在的位置?
谢谢你。