监视 Docker 卷中的文件更改 [英] Monitoring file changes in Docker volumes

查看:42
本文介绍了监视 Docker 卷中的文件更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个运行 python 脚本的 docker 容器:等待输入请求并相应地处理数据.

I have a docker container that is running a python script: waiting for input requests and processing data accordingly.

由于我使用 docker 进行开发,我希望,每当我更改该 python 文件的源代码(在我的机器中,而不是容器中)时,容器都会停止 python 脚本并重新启动它新代码. 因为现在我必须手动停止容器并重新启动它.我也可以监控我这边的文件更改(而不是在容器内),但我想避免这种情况并在容器本身内进行.

Since I am using docker for development, I would like that, whenever I change the source code of that python file (in my machine, not the container), the container would stop the python script and relaunch it with the new code. Because right now I have to manually stop the container and relaunch it. I could also monitor the file changes on my side (rather than inside the container) but I would like to avoid that and do it within the container itself.

我正在使用 docker-compose 的 volumes 选项在我的 FS 和容器之间共享源代码.

I am using docker-compose's volumes option to share the source code between my FS and the container's.

为了监控文件更改,我一直在尝试使用 watchmedo shell来自 watchdog python 模块的实用程序.我只是有一个奇怪的问题,我无法注意到那个 python 源文件的文件更改,除非我从容器内部而不是在我的本地 FS 中编辑它,即使它们是用 volumes 选项.

To monitor the file changes, I've been trying to use the watchmedo shell utility from the the watchdog python module. I just have this weird problem that I can't notice the file changes of that python source file unless I am editing it from the inside of the container and not in my local FS, even though they are mounted with the volumes option.

我觉得这与 docker 的工作方式有关,也可能与卷有关.我一直在尝试在线阅读它,但运气不佳.有任何想法吗?我完全被困住了!

I get the feeling that this is something to do with how docker works and maybe the volumes thing too. I've been trying to read up on it online, but didn't get much luck. Any ideas? I'm totally stuck!

这是一个可以更好地解释它的 gif.顶部到窗格连接到同一个容器,底部两个连接到我的本地机器.所有窗格都指向同一个文件夹.

Here's a gif that better explains it. The top to panes are connected to the same container and the bottom two to my local machine. All the panes are pointed to the same folder.

推荐答案

你可以让你的容器像这样运行(需要安装 inotify ):

You could have your container run something like this ( need inotify installed ):

while true
do
        inotifywait -e create -e modify  /path/to/python/script
        pkill python
        python /path/to/python/script
done

基本上等待文件的变化,在机器上杀死python,再次运行脚本.如果 python 脚本没有在后台运行/以任何方式取消,你可以使用 &像这样:python/path/to/python/script &

Basically wait for changes on the file, kill python on the machine, run script again. If the python script is not running in the background/deamonized in any way you could use an & like so: the python /path/to/python/script &

把它放到run.sh中,在你的Dockerfile中添加类似这样的东西

Put this into run.sh, add something like this to your Dockerfile

COPY run.sh /run.sh
CMD ["bash", "-l", "/run.sh"]

...你应该很好.

这篇关于监视 Docker 卷中的文件更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆