Viper: WatchConfig() does not work inside container

Created on 1 Jun 2020  路  2Comments  路  Source: spf13/viper

viper version: v1.7.0
go version go1.14.3 darwin/amd64
OS version: MacOS 10.15.2

I am using WatchConfig() to do hot config job. I mount a config file to container, which is watching by the app. The expected behavior is, when I updated the config file, the app inside the container will feel about it. However, it failed in my test.

Here is how reproduce it:

(main.go)

package main

import (
    "log"

    "github.com/fsnotify/fsnotify"
    "github.com/spf13/viper"
)

var Config config

type config struct {
    Name string `mapstructure:"name"`
}

func main() {
    viper.SetConfigFile("config.yaml")
    viper.AddConfigPath(".")
    viper.AddConfigPath("./config")
    viper.SetConfigType("yaml")
    if err := viper.ReadInConfig(); err != nil {
        log.Fatal(err)
    }

    if err := viper.Unmarshal(&Config); err != nil {
        log.Fatal(err)
    }

    viper.WatchConfig()
    viper.OnConfigChange(func(event fsnotify.Event) {
        if event.Op == fsnotify.Write {
            if err := viper.Unmarshal(&Config); err != nil {
                log.Fatal(err)
            }
            log.Printf("Change occurs %#v", Config)
        }
    })
    select {}
}

(Dockerfile)

FROM ubuntu:18.04

WORKDIR /

COPY ./config.yaml .

COPY ./m .

ENTRYPOINT ["/m"]

(docker-compose.yml)

version: '2.4'

services:

  mmmmm:
    image: mmmmm:latest
    container_name: mmmmm
    volumes:
      - ./config.yaml:/config.yaml
    restart: unless-stopped

The config.yaml mod set to 666.
After I build the docker image, and up the docker-compose, I edit the config.yaml file, and save it. The app inside the container does not feel it. I am sure that the inode of the config.yaml keeps the same both inside and outside the container, and the file is changed both inside and outside the container.

I am not sure whether this feature is used in a proper way, but I really have no idea about what is going on there. Much appreciated if someone can help me out.

Most helpful comment

The reason this happens is that viper sets a watch on the directory containing the file, not the file itself. In my case the solution was to mount the config directory instead of the file, but this won't work for everyone.

All 2 comments

I just tested on CentOS 7, also failed.

The reason this happens is that viper sets a watch on the directory containing the file, not the file itself. In my case the solution was to mount the config directory instead of the file, but this won't work for everyone.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kwk picture kwk  路  5Comments

jeffwillette picture jeffwillette  路  5Comments

noandrea picture noandrea  路  4Comments

TWinsnes picture TWinsnes  路  3Comments

lllama picture lllama  路  3Comments