dockergodockerfileviper-go

Viper config file found on dev but not on production using Dockerfile


In normal development (included build binary) go finds the config.yaml file, but in production, when using a Dockerfile image, it does not.

My project folder is:

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

config.go is:

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

My dockerfile is:

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

And the error (panic) displayed when running the container from that built image is:

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

How can I point to /app/config/config.yaml where the config file resides?

Thank you.


Solution

  • From the viper docs you can add multiple search paths for configs by calling viper.AddConfigPath multiple times.

    So try:

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