docker 检查挂载文件系统的变化

docker check for changes on mounted file system

我想在 docker 容器中创建一个 ruby 构建环境。 Ruby安装在容器中,我可以在我的win10主机上开发。我将主机工作目录挂载到容器并构建项目。但现在我想到了一点生活质量的改善:如果容器只监听挂载的文件系统,并在我更改项目中的某些内容时构建,那不是很好吗?

在 google 5 分钟后,我发现了 inotifywait,乍一看,它看起来很棒,所以我首先尝试了它 没有 安装文件系统:

[root@a3193720c4f1 testfolder]# inotifywait -m /tmp/testfolder/ -e modify -e create -e open |
>     while read path action file; do
>         echo "The file '$file' appeared in directory '$path' via '$action'"
>     done
Setting up watches.
Watches established.
The file '' appeared in directory '/tmp/testfolder/' via 'OPEN,ISDIR'
The file 'newfile' appeared in directory '/tmp/testfolder/' via 'OPEN'

这成功了,但是 /tmp/testfolder 不是挂载目录,它只是我在容器中创建的一个测试目录,用于适应 inotifywait 命令。所以这次我启动了我的容器并挂载了目录:

docker run -it --rm -v "D:\LokaleDaten\ELK_Docker\Docker\RVM\testfolder":"/tmp/testfolder" -w "/tmp/testfolder" myrvm

然后我再次启动inotifywait,更改了一个文件(在挂载到容器的主机系统上),但是inotify 没有捕获更改的文件。我还检查了文件是否在容器中更改,是的,进行了更改。 所以我很好奇我是否错过了什么,或者 inotify 不是正确的工具?

此致,曼努埃尔

由于列出了解决方法 here requires you to install python, I kept searching. I then found a solution,您不必在其中安装 python,但需要在我的主机上安装不同的工具。

所以基本上我最终得到的是一个自制的脚本,它每隔几秒就轮询一次文件系统并检查目录的 md5sum 是否有变化。这是脚本,如果有人需要它(注意:这是我制作的第一个 bash 脚本,所以如果有什么不起作用或不好的做法,请随时发表评论!):

#!/bin/sh
# script that gets a hash of a directory and checks every few seconds if the hash has changed
# if it has changed, it executes a command

if [ -d  ] || [ -f  ]; then
 f=""
else
 echo $(date +"%d.%m.%Y %T %:::z") ERROR: arg1 is neither a directory nor a file
 exit 1
fi

shift

if [ -z "$*" ]; then
 echo $(date +"%d.%m.%Y %T %:::z") ERROR: arg2 is required otherwise no command is executed
 exit 1
fi
cmd=$*

readonly getmd5sum="tar -cP $f | md5sum"
md5val="`eval ${getmd5sum}`"

while : ; do
 if [[ $md5val != `eval ${getmd5sum}` ]]; then
  md5val="`eval ${getmd5sum}`"
  $cmd
 fi
 sleep 2
done