在开发上找到的 Viper 配置文件,但在使用 Dockerfile 的生产环境中找不到

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


我的项目文件夹是:


|-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" ]


从该构建映像运行容器时显示的错误(panic)是:


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

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


慕码人2483693
浏览 197回答 2
2回答

慕妹3242003

从&nbsp;Viper 文档中,您可以通过多次调用来为配置添加多个搜索路径。viper.AddConfigPath所以试试:viper.AddConfigPath(viperConfig.ConfigAddPath) viper.AddConfigPath("/app/config")&nbsp;//&nbsp;<-&nbsp;to&nbsp;work&nbsp;with&nbsp;Dockerfile&nbsp;setup

30秒到达战场

此外,您可以在 Docker 文件中添加此命令。src >>cmd >> apiCOPY&nbsp;--from=build-env&nbsp;/app/src/cmd/api&nbsp;/app/
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go